PHP code example of mkoprek / request-validation-bundle

1. Go to this page and download the library: Download mkoprek/request-validation-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/ */

    

mkoprek / request-validation-bundle example snippets



declare(strict_types=1);

use MKoprek\RequestValidation\Request\AbstractRequest;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Validator\Constraints as Assert;

class UserCreateRequest extends AbstractRequest
{
    protected string $id;
    protected ?string $name;

    public function getId(): Uuid
    {
        return Uuid::fromString($this->id);
    }
    
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * @return array<Assert\Collection>
     */
    public function getValidationRules(): array
    {
        return [
            new Assert\Collection([
                'id' => new Assert\Required([
                    new Assert\NotNull(),
                    new Assert\NotBlank(),
                    new Assert\Uuid(),
                ]),
                'name' => new Assert\Required([
                    new Assert\NotNull(),
                    new Assert\NotBlank(),
                    new Assert\Type('string'),
                ]),
            ]),
        ];
    }
}



declare(strict_types=1);

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

#[Route('/api')]
class UserCreateController
{
    #[Route('/users', name: 'users.create', methods: 'POST')]
    public function post(UserCreateRequest $request): JsonResponse
    {
        $id = $request->getId();
        $name = $request->getName();

        $this->commandBus->handle(
            CreateUserCommand($request->getId(), $request->getName())
        );

        return new JsonResponse(['id' => $id->toRfc4122()], Response::HTTP_CREATED);
    }
}