Use the new mapper component

This commit is contained in:
Tim
2025-08-18 12:30:30 +02:00
parent 2152468bdc
commit 0dc7555ed1
5 changed files with 98 additions and 15 deletions

View File

@ -10,6 +10,7 @@ use App\Security\Voter\SnipVoter;
use App\Service\SnipContent\SnipContentService;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
use Symfony\Component\Routing\Attribute\Route;
class ApiController extends AbstractApiController
@ -49,6 +50,7 @@ class ApiController extends AbstractApiController
#[MapRequestPayload] SnipPostRequest $request,
SnipContentService $cs,
SnipRepository $repo,
ObjectMapperInterface $mapper,
): Response
{
$this->denyAccessUnlessGranted(SnipVoter::EDIT, $snip);
@ -57,7 +59,7 @@ class ApiController extends AbstractApiController
return $this->errorResponse('Snip is not the latest version');
}
$request->pushToSnip($snip);
$mapper->map($request, $snip);
$repo->save($snip);
if ($request->content !== null) {
$cs->update($snip, $request->content, $request->contentName);

View File

@ -0,0 +1,14 @@
<?php
namespace App\Dto\Condition;
use Symfony\Component\ObjectMapper\ConditionCallableInterface;
class ConditionNotNull implements ConditionCallableInterface
{
public function __invoke(mixed $value, object $source, ?object $target): bool
{
return null !== $value;
}
}

View File

@ -2,28 +2,21 @@
namespace App\Dto;
use App\Dto\Condition\ConditionNotNull;
use App\Entity\Snip;
use Symfony\Component\ObjectMapper\Attribute\Map;
#[Map(target: Snip::class)]
class SnipPostRequest
{
public function __construct(
#[Map(if: new ConditionNotNull())]
public ?string $name = null,
public ?string $content = null,
#[Map(if: new ConditionNotNull())]
public ?bool $public = null,
#[Map(if: new ConditionNotNull())]
public ?bool $visible = null,
public ?string $contentName = null,
) {}
public function pushToSnip(Snip $snip): void
{
if ($this->name !== null) {
$snip->name = $this->name;
}
if ($this->public !== null) {
$snip->public = $this->public;
}
if ($this->visible !== null) {
$snip->visible = $this->visible;
}
}
}