Passed
Push — master ( 43a943...86b561 )
by Daniel
12:01
created

PublishableValidator::validate()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 3
nop 2
dl 0
loc 15
ccs 0
cts 9
cp 0
crap 42
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[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 Silverback\ApiComponentsBundle\Validator;
15
16
use ApiPlatform\Core\Validator\ValidatorInterface;
17
use Silverback\ApiComponentsBundle\Helper\Publishable\PublishableStatusChecker;
18
19
/**
20
 * Builds and add validation group for published resources.
21
 *
22
 * @author Vincent Chalamon <[email protected]>
23
 */
24
final class PublishableValidator implements ValidatorInterface
25
{
26
    public const PUBLISHED_KEY = 'published';
27
28
    private ValidatorInterface $decorated;
29
    private PublishableStatusChecker $publishableStatusChecker;
30
31
    public function __construct(ValidatorInterface $decorated, PublishableStatusChecker $publishableStatusChecker)
32
    {
33
        $this->decorated = $decorated;
34
        $this->publishableStatusChecker = $publishableStatusChecker;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function validate($data, array $context = []): void
41
    {
42
        if (
43
            \is_object($data) &&
44
            $this->publishableStatusChecker->getAnnotationReader()->isConfigured($data) &&
45
            ($this->publishableStatusChecker->hasPublicationDate($data) || isset($context[self::PUBLISHED_KEY]))
46
        ) {
47
            $groups = [(new \ReflectionClass(\get_class($data)))->getShortName() . ':published'];
48
            if (!empty($this->publishableStatusChecker->getAnnotationReader()->getConfiguration($data)->validationGroups)) {
49
                $groups = $this->publishableStatusChecker->getAnnotationReader()->getConfiguration($data)->validationGroups;
50
            }
51
            $context['groups'] = array_merge($context['groups'] ?? ['Default'], $groups);
52
        }
53
54
        $this->decorated->validate($data, $context);
55
    }
56
}
57