PHP code example of monkeyscloud / monkeyslegion-validation
1. Go to this page and download the library: Download monkeyscloud/monkeyslegion-validation 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/ */
monkeyscloud / monkeyslegion-validation example snippets
declare(strict_types=1);
namespace App\Dto;
use MonkeysLegion\Validation\Attributes as Assert;
final readonly class CreateUserRequest
{
public function __construct(
#[Assert\NotBlank]
#[Assert\Email]
public string $email,
#[Assert\NotBlank]
#[Assert\Length(min: 8, max: 64)]
public string $password,
#[Assert\SameAs(otherField: 'password')]
public string $confirmPassword,
) {}
}
use MonkeysLegion\Validation\Validator;
$validator = new Validator();
$result = $validator->validate($dto);
if (!$result->isValid) {
foreach ($result->errors as $error) {
echo "{$error->field}: {$error->message}\n";
}
}
// Or throw on failure:
$result->throwIfInvalid();
$result = validate($dto);
if ($result->hasErrorsFor('email')) {
echo $result->firstError('email');
}
use MonkeysLegion\Validation\DtoBinder;
use MonkeysLegion\Validation\Validator;
use MonkeysLegion\Validation\Middleware\ValidationMiddleware;
$middleware = new ValidationMiddleware(
binder: new DtoBinder(new Validator()),
responseFactory: $responseFactory, // PSR-17 ResponseFactoryInterface
streamFactory: $streamFactory, // PSR-17 StreamFactoryInterface
dtoMap: [
'user.create' => \App\Dto\CreateUserRequest::class,
],
);
public function createUser(ServerRequestInterface $request): ResponseInterface
{
/** @var CreateUserRequest $dto */
$dto = $request->getAttribute('dto');
$this->userService->register($dto->email, $dto->password);
return $this->responseFactory->createResponse(201);
}
declare(strict_types=1);
namespace App\Validation;
use MonkeysLegion\Validation\Contracts\ConstraintInterface;
use MonkeysLegion\Validation\ValidationError;
use Attribute;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_PARAMETER)]
final readonly class Slug implements ConstraintInterface
{
public function __construct(
public string $message = 'Value must be a valid URL slug.',
) {}
public function validate(mixed $value, string $field, object $dto): ?ValidationError
{
if ($value === null || $value === '') {
return null;
}
if (!preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', (string) $value)) {
return new ValidationError($field, $this->message);
}
return null;
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.