PHP code example of pln0w / rest-api-validator

1. Go to this page and download the library: Download pln0w/rest-api-validator 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/ */

    

pln0w / rest-api-validator example snippets


    
    declare(strict_types=1);
    
    namespace User\Infrastructure\Request;
    
    use Pawly\RestApiValidator\Request\AbstractCustomRequest;
    use Symfony\Component\Validator\Constraints as Assert;
    
    class RegisterUserRequest extends AbstractCustomRequest
    {
        protected ?string $email = null;
        protected ?string $password = null;
    
        /**
         * @inheritDoc
         */
        public function getValidationRules()
        {
            return new Assert\Collection([
                'email' => new Assert\Email(),
                'password' => [
                    new Assert\NotBlank(),
                    new Assert\Length(['min' => 6])
                ]
            ]);
        }
    }
    

    
    declare(strict_types=1);
    
    namespace User\Infrastructure\Controller;
    
    use Pawly\RestApiValidator\Response\ApiResponse;
    use User\Infrastructure\Request\RegisterUserRequest;
    
    final class RegisterUserAction
    {
        public function __invoke(RegisterUserRequest $request): ApiResponse
        {
            // do some stuff ...
            $email = $request->getEmail();
            
            return ApiResponse::json(['email' => $email], ApiResponse::HTTP_OK);
        }
    }
    

    
    declare(strict_types=1);
    
    namespace User\Infrastructure\Request;
    
    use Pawly\RestApiValidator\Request\AbstractCustomRequest;
    use Symfony\Component\Validator\Constraints as Assert;
    use Shared\Domain\ValueObject\Email;

    class RegisterUserRequest extends AbstractCustomRequest
    {
        protected ?string $email = null;
        protected ?string $password = null;
    
        /**
         * @inheritDoc
         */
        public function getValidationRules()
        {
            return new Assert\Collection([
                'email' => new Assert\Email(),
                'password' => [
                    new Assert\NotBlank(),
                    new Assert\Length(['min' => 6])
                ]
            ]);
        }
      
        public function getEmail(): Email
        {
             return new Email($this->email);
        }
    }