Test Failed
Push — develop ( eeff2c...6435cb )
by Freddie
05:45
created

ActionConstraintValidator::getInvalidActions()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
nc 3
nop 1
dl 0
loc 20
rs 9.9332
c 2
b 0
f 0
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of FlexPHP.
4
 *
5
 * (c) Freddie Gar <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace FlexPHP\Schema\Validators\Constraints;
11
12
use FlexPHP\Schema\Constants\Action;
13
use Symfony\Component\Validator\Constraints\Choice;
14
use Symfony\Component\Validator\Constraints\Count;
15
use Symfony\Component\Validator\Constraints\Type;
16
use Symfony\Component\Validator\ConstraintViolationListInterface;
17
use Symfony\Component\Validator\Validation;
18
19
/**
20
 * @Annotation
21
 */
22
class ActionConstraintValidator
23
{
24
    private const ACTIONS = [
25
        Action::ALL,
26
        Action::INDEX,
27
        Action::CREATE,
28
        Action::READ,
29
        Action::UPDATE,
30
        Action::DELETE,
31
    ];
32
33
    /**
34
     * @param mixed $value
35
     */
36
    public function validate($value): ConstraintViolationListInterface
37
    {
38
        if (($errors = $this->validateType($value))->count()) {
39
            return $errors;
40
        }
41
42
        if (empty($value)) {
43
            $value = Action::ALL;
44
        }
45
46
        $invalid = $this->getInvalidActions($value);
47
48
        $validator = Validation::createValidator();
49
50
        return $validator->validate($invalid, [
51
            new Count([
52
                'max' => 0,
53
                'maxMessage' => 'Allowed values are: ' . \implode(',', self::ACTIONS),
54
            ]),
55
        ]);
56
    }
57
58
    /**
59
     * @param mixed $value
60
     */
61
    private function validateType($value): ConstraintViolationListInterface
62
    {
63
        $validator = Validation::createValidator();
64
65
        return $validator->validate($value, [
66
            new Type([
67
                'type' => 'string',
68
                'message' => 'Logic: [it must be string type]',
69
            ]),
70
        ]);
71
    }
72
73
    private function getInvalidActions(string $value): array
74
    {
75
        $invalid = [];
76
        $actions = \explode(',', $value);
77
78
        $validator = Validation::createValidator();
79
80
        foreach ($actions as $action) {
81
            $errors = $validator->validate($action, [
82
                new Choice([
83
                    'choices' => self::ACTIONS,
84
                ]),
85
            ]);
86
87
            if (\count($errors)) {
88
                $invalid[] = $action;
89
            }
90
        }
91
92
        return $invalid;
93
    }
94
}
95