namespace App\Security;
final class Roles
{
const ROLE_ADMIN = 'ROLE_ADMIN';
const ROLE_USER = 'ROLE_USER';
/**
* @return array
*/
public static function getRoles()
{
return [
self::ROLE_ADMIN,
self::ROLE_USER,
];
}
private function __construct()
{
}
}
{% transchoice count with { '%count%': count } %}
%count% балл|%count% балла|%count% баллов
{% endtranschoice %}
class ModelResolver implements ArgumentValueResolverInterface
{
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @var ValidatorInterface
*/
private $validator;
/**
* @var string
*/
private $namespace;
public function __construct(
SerializerInterface $serializer,
ValidatorInterface $validator,
$namespace = 'App\\DTO\\'
) {
$this->serializer = $serializer;
$this->validator = $validator;
$this->namespace = $namespace;
}
/**
* @inheritDoc
*/
public function resolve(Request $request, ArgumentMetadata $argument)
{
$model = $this->serializer->deserialize($request->getContent(), $argument->getType());
$validationGroups = $request->attributes->get('validation_groups', null);
$violations = $this->validator->validate($model, null, $validationGroups);
if ($violations->count() > 0) {
throw new ValidationException($violations);
}
yield $model;
}
/**
* @inheritDoc
*/
public function supports(Request $request, ArgumentMetadata $argument)
{
return strpos($argument->getType(), $this->namespace) === 0;
}
}
@Route(path="/submit", name="order_submit", defaults={"validation_groups": {"Group1", "Group2"} })
$validationGroups = $request->attributes->get('validation_groups', null);
use Symfony\Component\Validator\Constraints as Assert;
class DTO
{
/**
* @var string
*
* @Assert\NotBlank()
*/
public $name;
/**
* @var string
*
* @Assert\NotBlank()
* @Assert\Email()
*/
public $email;
/**
* @var string
*
* @Assert\NotBlank()
*/
public $address;
}
class OrderModelResolver implements ArgumentValueResolverInterface
{
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @var ValidatorInterface
*/
private $validator;
public function __construct(SerializerInterface $serializer, ValidatorInterface $validator)
{
$this->serializer = $serializer;
$this->validator = $validator;
}
/**
* @inheritDoc
*/
public function resolve(Request $request, ArgumentMetadata $argument)
{
$model = $this->>serializer->deserialize($request->getContent(), OrderModel::class)
$violations = $this->validator->validate($model);
if ($violations->count() > 0) {
throw new ValidationException($violations);
}
yield $model;
}
/**
* @inheritDoc
*/
public function supports(Request $request, ArgumentMetadata $argument)
{
return $argument->getType() == OrderModel::class;
}
}
class ValidationExceptionListener implements EventSubscriberInterface
{
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => 'onException',
];
}
public function onException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if (!$exception instanceof ValidationException) {
return;
}
$errors = [];
/** @var ConstraintViolationInterface $violation */
foreach ($exception->getViolations() as $violation) {
$errors[$violation->getPropertyPath()] = $violation->getMessage();
}
$response = new JsonResponse([
'errors' => $errors,
], 400);
$event->setResponse($response);
$event->stopPropagation();
}
}
Через чур сложно для новичка.
$validator = Validation::createValidator();
$violations = $validator->validate($_POST, new Assert\Collection(array(
'name' => new Assert\Collection([
new Assert\NotBlank(),
new Assert\Length(['min' => 2]),
])
)));
Validator::addRule(
'name',
'Поле name обязательное',
'required');
Validator::addRule(
'name',
'Имя должно состоять не менне чем из 2-х символов',
'minlength',
3);
Validator::addEntries($_POST);
Validator::validate();
Если бы SomeBundle был не ваш, то тогда надо было реализовывать через PrependExtensionInterface: