PHP code example of dualmedia / symfony-request-dto-bundle

1. Go to this page and download the library: Download dualmedia/symfony-request-dto-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dualmedia / symfony-request-dto-bundle example snippets


return [
    Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
    // other bundles ...
    DualMedia\DtoRequestBundle\DtoBundle::class => ['all' => true],
];


use \DualMedia\DtoRequestBundle\Attributes\Dto\Path;
use \DualMedia\DtoRequestBundle\Model\AbstractDto;

class MyDto extends AbstractDto
{
    public int|null $myVar = null;
    
    #[Path("custom_path")]
    public string|null $myString = null;
}



class MyController extends \Symfony\Bundle\FrameworkBundle\Controller\AbstractController
{
    public function myAction(MyDto $dto): \Symfony\Component\HttpFoundation\Response
    {
        // your dto here is already validated!
    }
}

class ErrorSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    public function __construct(
        private readonly ErrorListener $decorated
    ) {
    }

    public static function getSubscribedEvents(){
        return [
            \Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent::class => 'onControllerArguments',
        ];
    }
    
    public function onControllerArguments(
        ControllerArgumentsEvent $event
    ): void {
        $this->decorated->onControllerArguments($event);

        $violationList = new ConstraintViolationList();

        foreach ($event->getArguments() as $argument) {
            if ($argument instanceof DtoInterface
                && !$argument->isOptional()
                && !$argument->isValid()) {
                $violationList->addAll($argument->getConstraintViolationList());
            }
        }

        if (0 !== $violationList->count()) {
            throw new ValidatorException($violationList); // handle and display, or just do whatever really
        }
    }
}


use \DualMedia\DtoRequestBundle\Constraints\MappedToPath;
use \DualMedia\DtoRequestBundle\Model\AbstractDto;
use Symfony\Component\Validator\Constraints as Assert;

#[MappedToPath(
    'property',
    new Assert\Expression(
        'this.property != null',
        message: 'This property cannot be null'
    )
)]
class MyDto extends AbstractDto
{
    public int|null $property = null;
}