ApiPlatform\Core\Bridge\Symfony\Validator\EventListener\ValidateListener::onKernelView PHP Метод

onKernelView() публичный метод

Validates data returned by the controller if applicable.
public onKernelView ( GetResponseForControllerResultEvent $event )
$event Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent
    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $request = $event->getRequest();
        try {
            $attributes = RequestAttributesExtractor::extractAttributes($request);
        } catch (RuntimeException $e) {
            return;
        }
        if ($request->isMethodSafe(false) || $request->isMethod(Request::METHOD_DELETE)) {
            return;
        }
        $data = $event->getControllerResult();
        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
        if (isset($attributes['collection_operation_name'])) {
            $validationGroups = $resourceMetadata->getCollectionOperationAttribute($attributes['collection_operation_name'], 'validation_groups');
        } else {
            $validationGroups = $resourceMetadata->getItemOperationAttribute($attributes['item_operation_name'], 'validation_groups');
        }
        if (!$validationGroups) {
            // Fallback to the resource
            $validationGroups = $resourceMetadata->getAttributes()['validation_groups'] ?? null;
        }
        if (is_callable($validationGroups)) {
            $validationGroups = call_user_func_array($validationGroups, [$data]);
        }
        $violations = $this->validator->validate($data, null, $validationGroups);
        if (0 !== count($violations)) {
            throw new ValidationException($violations);
        }
    }

Usage Example

Пример #1
0
 /**
  * @expectedException \ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException
  */
 public function testThrowsValidationExceptionWithViolationsFound()
 {
     $data = new DummyEntity();
     $expectedValidationGroups = ['a', 'b', 'c'];
     $violationsProphecy = $this->prophesize(ConstraintViolationListInterface::class);
     $violationsProphecy->count()->willReturn(1)->shouldBeCalled();
     $violations = $violationsProphecy->reveal();
     $validatorProphecy = $this->prophesize(ValidatorInterface::class);
     $validatorProphecy->validate($data, null, $expectedValidationGroups)->shouldBeCalled()->willReturn($violations)->shouldBeCalled();
     $validator = $validatorProphecy->reveal();
     list($resourceMetadataFactory, $event) = $this->createEventObject($expectedValidationGroups, $data);
     $validationViewListener = new ValidateListener($validator, $resourceMetadataFactory);
     $validationViewListener->onKernelView($event);
 }