ConfigValidator   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 145
Duplicated Lines 4.83 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 91.18%

Importance

Changes 0
Metric Value
wmc 29
lcom 2
cbo 6
dl 7
loc 145
ccs 62
cts 68
cp 0.9118
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A assertValidConfig() 0 6 3
A isValidConfig() 0 4 1
A initializeRules() 0 4 1
A addRule() 0 4 1
A isValid() 0 4 1
A isExtraFieldsAllowed() 0 4 1
A setExtraFieldsAllowed() 0 6 1
A getInstance() 0 10 2
A getConfigFinalRules() 7 13 4
C validate() 0 46 13

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Exception\ConfigurationException;
14
use Youshido\GraphQL\Exception\ValidationException;
15
use Youshido\GraphQL\Validator\ConfigValidator\Rules\TypeValidationRule;
16
use Youshido\GraphQL\Validator\ConfigValidator\Rules\ValidationRuleInterface;
17
use Youshido\GraphQL\Validator\ErrorContainer\ErrorContainerTrait;
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 125
    public static function getInstance()
43
    {
44 125
        if (empty(self::$instance)) {
45 1
            self::$instance = new self();
46 1
        }
47
48 125
        self::$instance->clearErrors();
49
50 125
        return self::$instance;
51
    }
52
53 98
    public function assertValidConfig(AbstractConfig $config)
54
    {
55 98
        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 77
    }
59
60 99
    public function isValidConfig(AbstractConfig $config)
61
    {
62 99
        return $this->validate($config->getData(), $this->getConfigFinalRules($config), $config->isExtraFieldsAllowed());
63
    }
64
65 99
    protected function getConfigFinalRules(AbstractConfig $config)
66
    {
67 99
        $rules = $config->getRules();
68 99 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 94
            foreach ($rules as $name => $info) {
70 94
                if (!empty($info['final'])) {
71 94
                    $rules[$name]['required'] = true;
72 94
                }
73 94
            }
74 94
        }
75
76 99
        return $rules;
77
    }
78
79
80 100
    public function validate($data, $rules = [], $extraFieldsAllowed = null)
81
    {
82 100
        if ($extraFieldsAllowed !== null) $this->setExtraFieldsAllowed($extraFieldsAllowed);
83
84 100
        $processedFields = [];
85 100
        foreach ($rules as $fieldName => $fieldRules) {
86 100
            $processedFields[] = $fieldName;
87
88
            /** Custom validation of 'required' property */
89 100
            if (array_key_exists('required', $fieldRules)) {
90 98
                unset($fieldRules['required']);
91
92 98
                if (!array_key_exists($fieldName, $data)) {
93 12
                    $this->addError(new ValidationException(sprintf('Field "%s" is required', $fieldName)));
94
95 12
                    continue;
96
                }
97 100
            } elseif (!array_key_exists($fieldName, $data)) {
98 96
                continue;
99
            }
100 99
            if (!empty($fieldRules['final'])) unset($fieldRules['final']);
101
102
            /** Validation of all other rules*/
103 99
            foreach ($fieldRules as $ruleName => $ruleInfo) {
104 99
                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 99
                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 99
            }
114 100
        }
115
116 100
        if (!$this->isExtraFieldsAllowed()) {
117 100
            foreach (array_keys($data) as $fieldName) {
118 100
                if (!in_array($fieldName, $processedFields)) {
119 1
                    $this->addError(new ValidationException(sprintf('Field "%s" is not expected', $fieldName)));
120 1
                }
121 100
            }
122 100
        }
123
124 100
        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 100
    public function isValid()
138
    {
139 100
        return !$this->hasErrors();
140
    }
141
142
143
    /**
144
     * @return boolean
145
     */
146 100
    public function isExtraFieldsAllowed()
147
    {
148 100
        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