Completed
Pull Request — master (#45)
by Daniel
04:14
created

ConfigValidator   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 140
Duplicated Lines 5 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 89.29%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 28
lcom 2
cbo 6
dl 7
loc 140
ccs 50
cts 56
cp 0.8929
rs 10
c 1
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
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 assertValidateConfig() 0 6 3
A __construct() 0 4 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\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 79
    public static function getInstance()
43
    {
44 79
        if (empty(self::$instance)) {
45 1
            self::$instance = new self();
46
        }
47
48 79
        self::$instance->clearErrors();
49
50 79
        return self::$instance;
51
    }
52
53 52
    public function assertValidateConfig(AbstractConfig $config)
54
    {
55 52
        if (!$this->validate($config->getData(), $this->getConfigFinalRules($config), $config->isExtraFieldsAllowed())) {
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 32
    }
59
60 52
    protected function getConfigFinalRules(AbstractConfig $config)
61
    {
62 52
        $rules = $config->getRules();
63 52 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...
64 47
            foreach ($rules as $name => $info) {
65 47
                if (!empty($info['final'])) {
66 47
                    $rules[$name]['required'] = true;
67
                }
68
            }
69
        }
70
71 52
        return $rules;
72
    }
73
74
75 53
    public function validate($data, $rules = [], $extraFieldsAllowed = null)
76
    {
77 53
        if ($extraFieldsAllowed !== null) $this->setExtraFieldsAllowed($extraFieldsAllowed);
78
79 53
        $processedFields = [];
80 53
        foreach ($rules as $fieldName => $fieldRules) {
81 53
            $processedFields[] = $fieldName;
82
83
            /** Custom validation of 'required' property */
84 53
            if (array_key_exists('required', $fieldRules)) {
85 51
                unset($fieldRules['required']);
86
87 51
                if (!array_key_exists($fieldName, $data)) {
88 12
                    $this->addError(new ValidationException(sprintf('Field "%s" is required', $fieldName)));
89
90 51
                    continue;
91
                }
92 52
            } elseif (!array_key_exists($fieldName, $data)) {
93 49
                continue;
94
            }
95 52
            if (!empty($fieldRules['final'])) unset($fieldRules['final']);
96
97
            /** Validation of all other rules*/
98 52
            foreach ($fieldRules as $ruleName => $ruleInfo) {
99 52
                if (!array_key_exists($ruleName, $this->validationRules)) {
100 1
                    $this->addError(new ValidationException(sprintf('Field "%s" has invalid rule "%s"', $fieldName, $ruleInfo)));
101
102 1
                    continue;
103
                }
104
105 52
                if (!$this->validationRules[$ruleName]->validate($data[$fieldName], $ruleInfo)) {
106 52
                    $this->addError(new ValidationException(sprintf('Field "%s" expected to be "%s" but got "%s"', $fieldName, $ruleName, gettype($data[$fieldName]))));
107
                }
108
            }
109
        }
110
111 53
        if (!$this->isExtraFieldsAllowed()) {
112 53
            foreach (array_keys($data) as $fieldName) {
113 53
                if (!in_array($fieldName, $processedFields)) {
114 53
                    $this->addError(new ValidationException(sprintf('Field "%s" is not expected', $fieldName)));
115
                }
116
            }
117
        }
118
119 53
        return $this->isValid();
120
    }
121
122 1
    protected function initializeRules()
123
    {
124 1
        $this->validationRules['type'] = new TypeValidationRule($this);
125 1
    }
126
127
    public function addRule($name, ValidationRuleInterface $rule)
128
    {
129
        $this->validationRules[$name] = $rule;
130
    }
131
132 53
    public function isValid()
133
    {
134 53
        return !$this->hasErrors();
135
    }
136
137
138
    /**
139
     * @return boolean
140
     */
141 53
    public function isExtraFieldsAllowed()
142
    {
143 53
        return $this->extraFieldsAllowed;
144
    }
145
146
    /**
147
     * @param boolean $extraFieldsAllowed
148
     *
149
     * @return ConfigValidator
150
     */
151
    public function setExtraFieldsAllowed($extraFieldsAllowed)
152
    {
153
        $this->extraFieldsAllowed = $extraFieldsAllowed;
154
155
        return $this;
156
    }
157
158
}
159