Completed
Push — master ( 7552ea...399762 )
by Alexandr
03:18 queued 37s
created

ConfigValidator::isValid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
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 93
    public static function getInstance()
43
    {
44 93
        if (empty(self::$instance)) {
45 1
            self::$instance = new self();
46 1
        }
47
48 93
        self::$instance->clearErrors();
49
50 93
        return self::$instance;
51
    }
52
53 66
    public function assertValidConfig(AbstractConfig $config)
54
    {
55 66
        if (!$this->isValidConfig($config)) {
56 21
            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 67
    public function isValidConfig(AbstractConfig $config)
61
    {
62 67
        return $this->validate($config->getData(), $this->getConfigFinalRules($config), $config->isExtraFieldsAllowed());
63
    }
64
65 67
    protected function getConfigFinalRules(AbstractConfig $config)
66
    {
67 67
        $rules = $config->getRules();
68 67 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 62
            foreach ($rules as $name => $info) {
70 62
                if (!empty($info['final'])) {
71 62
                    $rules[$name]['required'] = true;
72 62
                }
73 62
            }
74 62
        }
75
76 67
        return $rules;
77
    }
78
79
80 68
    public function validate($data, $rules = [], $extraFieldsAllowed = null)
81
    {
82 68
        if ($extraFieldsAllowed !== null) $this->setExtraFieldsAllowed($extraFieldsAllowed);
83
84 68
        $processedFields = [];
85 68
        foreach ($rules as $fieldName => $fieldRules) {
86 68
            $processedFields[] = $fieldName;
87
88
            /** Custom validation of 'required' property */
89 68
            if (array_key_exists('required', $fieldRules)) {
90 66
                unset($fieldRules['required']);
91
92 66
                if (!array_key_exists($fieldName, $data)) {
93 12
                    $this->addError(new ValidationException(sprintf('Field "%s" is required', $fieldName)));
94
95 12
                    continue;
96
                }
97 68
            } elseif (!array_key_exists($fieldName, $data)) {
98 64
                continue;
99
            }
100 67
            if (!empty($fieldRules['final'])) unset($fieldRules['final']);
101
102
            /** Validation of all other rules*/
103 67
            foreach ($fieldRules as $ruleName => $ruleInfo) {
104 67
                if (!array_key_exists($ruleName, $this->validationRules)) {
105 1
                    $this->addError(new ValidationException(sprintf('Field "%s" has invalid rule "%s"', $fieldName, $ruleInfo)));
106
107 1
                    continue;
108
                }
109
110 67
                if (!$this->validationRules[$ruleName]->validate($data[$fieldName], $ruleInfo)) {
111 13
                    $this->addError(new ValidationException(sprintf('Field "%s" expected to be "%s" but got "%s"', $fieldName, $ruleName, gettype($data[$fieldName]))));
112 13
                }
113 67
            }
114 68
        }
115
116 68
        if (!$this->isExtraFieldsAllowed()) {
117 68
            foreach (array_keys($data) as $fieldName) {
118 68
                if (!in_array($fieldName, $processedFields)) {
119 1
                    $this->addError(new ValidationException(sprintf('Field "%s" is not expected', $fieldName)));
120 1
                }
121 68
            }
122 68
        }
123
124 68
        return $this->isValid();
125
    }
126
127 1
    protected function initializeRules()
128
    {
129 1
        $this->validationRules['type'] = new TypeValidationRule($this);
130 1
    }
131
132
    public function addRule($name, ValidationRuleInterface $rule)
133
    {
134
        $this->validationRules[$name] = $rule;
135
    }
136
137 68
    public function isValid()
138
    {
139 68
        return !$this->hasErrors();
140
    }
141
142
143
    /**
144
     * @return boolean
145
     */
146 68
    public function isExtraFieldsAllowed()
147
    {
148 68
        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