Completed
Push — master ( d0bde7...345612 )
by Antoine
26s queued 11s
created

ValidateListener::onKernelView()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nc 3
nop 1
dl 0
loc 20
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Validator\EventListener;
15
16
use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
17
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
18
use ApiPlatform\Core\Util\RequestAttributesExtractor;
19
use ApiPlatform\Core\Validator\ValidatorInterface;
20
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
21
22
/**
23
 * Validates data.
24
 *
25
 * @author Kévin Dunglas <[email protected]>
26
 */
27
final class ValidateListener
28
{
29
    private $validator;
30
    private $resourceMetadataFactory;
31
32
    public function __construct(ValidatorInterface $validator, ResourceMetadataFactoryInterface $resourceMetadataFactory)
33
    {
34
        $this->validator = $validator;
35
        $this->resourceMetadataFactory = $resourceMetadataFactory;
36
    }
37
38
    /**
39
     * Validates data returned by the controller if applicable.
40
     *
41
     * @throws ValidationException
42
     */
43
    public function onKernelView(GetResponseForControllerResultEvent $event): void
44
    {
45
        $request = $event->getRequest();
46
        if (
47
            $request->isMethodSafe(false)
48
            || $request->isMethod('DELETE')
49
            || !($attributes = RequestAttributesExtractor::extractAttributes($request))
50
            || !$attributes['receive']
51
        ) {
52
            return;
53
        }
54
55
        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);
56
        $inputMetadata = $resourceMetadata->getOperationAttribute($attributes, 'input', [], true);
57
        if (\array_key_exists('class', $inputMetadata) && null === $inputMetadata['class']) {
58
            return;
59
        }
60
61
        $validationGroups = $resourceMetadata->getOperationAttribute($attributes, 'validation_groups', null, true);
62
        $this->validator->validate($event->getControllerResult(), ['groups' => $validationGroups]);
63
    }
64
}
65