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();try {
throw new \Exception('exception1');
} catch (\Exception $e1) {
try {
throw new \Exception('exception2', 0, $e1);
} catch (\Exception $e2) {
throw new \Exception('exception3', 0, $e2);
}
}public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
dump($event->getException());
}foreach ($this->file as $k => $v) {
foreach ($this->file as $k => $v) {
echo "$k - $v - ";
var_dump($this->file[$k]);
}if ($this->file = $v) {
} Strings containing valid decimal integers, unless the number is preceded by a + sign, will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.