Completed
Push — master ( 3474c6...7552ea )
by Alexandr
02:54
created

ConfigValidator::isValidConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/*
3
* This file is a part of graphql-youshido project.
4
*
5
* @author Alexandr Viniychuk <[email protected]>
6
* created: 11/28/15 2:25 AM
7
*/
8
9
namespace Youshido\GraphQL\Validator\ConfigValidator;
10
11
12
use Youshido\GraphQL\Config\AbstractConfig;
13
use Youshido\GraphQL\Validator\ConfigValidator\Rules\TypeValidationRule;
14
use Youshido\GraphQL\Validator\ConfigValidator\Rules\ValidationRuleInterface;
15
use Youshido\GraphQL\Validator\ErrorContainer\ErrorContainerTrait;
16
use Youshido\GraphQL\Validator\Exception\ConfigurationException;
17
use Youshido\GraphQL\Validator\Exception\ValidationException;
18
19
class ConfigValidator implements ConfigValidatorInterface
20
{
21
22
    use ErrorContainerTrait;
23
24
    protected $rules = [];
25
26
    protected $extraFieldsAllowed = false;
27
28
    /** @var ValidationRuleInterface[] */
29
    protected $validationRules = [];
30
31
    /** @var  ConfigValidator */
32
    protected static $instance;
33
34 1
    private function __construct()
35
    {
36 1
        $this->initializeRules();
37 1
    }
38
39
    /**
40
     * @return ConfigValidator
41
     */
42 92
    public static function getInstance()
43
    {
44 92
        if (empty(self::$instance)) {
45 1
            self::$instance = new self();
46 1
        }
47
48 92
        self::$instance->clearErrors();
49
50 92
        return self::$instance;
51
    }
52
53 65
    public function assertValidConfig(AbstractConfig $config)
54
    {
55 65
        if (!$this->isValidConfig($config)) {
56 20
            throw new ConfigurationException('Config is not valid for ' . ($config->getContextObject() ? get_class($config->getContextObject()) : null) . "\n" . implode("\n", $this->getErrorsArray(false)));
57
        }
58 45
    }
59
60 65
    public function isValidConfig(AbstractConfig $config)
61
    {
62 65
        return $this->validate($config->getData(), $this->getConfigFinalRules($config), $config->isExtraFieldsAllowed());
63 65
    }
64 60
65 60
    protected function getConfigFinalRules(AbstractConfig $config)
66 60
    {
67 60
        $rules = $config->getRules();
68 60 View Code Duplication
        if ($config->isFinalClass()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69 60
            foreach ($rules as $name => $info) {
70
                if (!empty($info['final'])) {
71 65
                    $rules[$name]['required'] = true;
72
                }
73
            }
74
        }
75 66
76
        return $rules;
77 66
    }
78
79 66
80 66
    public function validate($data, $rules = [], $extraFieldsAllowed = null)
81 66
    {
82
        if ($extraFieldsAllowed !== null) $this->setExtraFieldsAllowed($extraFieldsAllowed);
83
84 66
        $processedFields = [];
85 64
        foreach ($rules as $fieldName => $fieldRules) {
86
            $processedFields[] = $fieldName;
87 64
88 12
            /** Custom validation of 'required' property */
89
            if (array_key_exists('required', $fieldRules)) {
90 12
                unset($fieldRules['required']);
91
92 66
                if (!array_key_exists($fieldName, $data)) {
93 62
                    $this->addError(new ValidationException(sprintf('Field "%s" is required', $fieldName)));
94
95 65
                    continue;
96
                }
97
            } elseif (!array_key_exists($fieldName, $data)) {
98 65
                continue;
99 65
            }
100 1
            if (!empty($fieldRules['final'])) unset($fieldRules['final']);
101
102 1
            /** Validation of all other rules*/
103
            foreach ($fieldRules as $ruleName => $ruleInfo) {
104
                if (!array_key_exists($ruleName, $this->validationRules)) {
105 65
                    $this->addError(new ValidationException(sprintf('Field "%s" has invalid rule "%s"', $fieldName, $ruleInfo)));
106 12
107 12
                    continue;
108 65
                }
109 66
110
                if (!$this->validationRules[$ruleName]->validate($data[$fieldName], $ruleInfo)) {
111 66
                    $this->addError(new ValidationException(sprintf('Field "%s" expected to be "%s" but got "%s"', $fieldName, $ruleName, gettype($data[$fieldName]))));
112 66
                }
113 66
            }
114 1
        }
115 1
116 66
        if (!$this->isExtraFieldsAllowed()) {
117 66
            foreach (array_keys($data) as $fieldName) {
118
                if (!in_array($fieldName, $processedFields)) {
119 66
                    $this->addError(new ValidationException(sprintf('Field "%s" is not expected', $fieldName)));
120
                }
121
            }
122 1
        }
123
124 1
        return $this->isValid();
125 1
    }
126
127
    protected function initializeRules()
128
    {
129
        $this->validationRules['type'] = new TypeValidationRule($this);
130
    }
131
132 66
    public function addRule($name, ValidationRuleInterface $rule)
133
    {
134 66
        $this->validationRules[$name] = $rule;
135
    }
136
137
    public function isValid()
138
    {
139
        return !$this->hasErrors();
140
    }
141 66
142
143 66
    /**
144
     * @return boolean
145
     */
146
    public function isExtraFieldsAllowed()
147
    {
148
        return $this->extraFieldsAllowed;
149
    }
150
151
    /**
152
     * @param boolean $extraFieldsAllowed
153
     *
154
     * @return ConfigValidator
155
     */
156
    public function setExtraFieldsAllowed($extraFieldsAllowed)
157
    {
158
        $this->extraFieldsAllowed = $extraFieldsAllowed;
159
160
        return $this;
161
    }
162
163
}
164