Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

Completed
Pull Request — master (#678)
by Henrique
03:10
created

Factory::exception()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 9
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 1
crap 20
1
<?php
2
3
/*
4
 * This file is part of Respect/Validation.
5
 *
6
 * (c) Alexandre Gomes Gaigalas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the "LICENSE.md"
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Respect\Validation;
13
14
use Doctrine\Common\Annotations\Reader;
15
use Doctrine\Common\Annotations\SimpleAnnotationReader;
16
use ReflectionClass;
17
use Respect\Validation\Annotations\Template;
18
use Respect\Validation\Annotations\Templates;
19
use Respect\Validation\Exceptions\ComponentException;
20
use Respect\Validation\Exceptions\InvalidRuleException;
21
use Respect\Validation\Exceptions\RuleNotFoundException;
22
use Respect\Validation\Exceptions\ValidationException;
23
24
/**
25
 * Factory to create rules.
26
 *
27
 * @author Henrique Moody <[email protected]>
28
 *
29
 * @since 0.8.0
30
 */
31
final class Factory
32
{
33
    /**
34
     * @var string[]
35
     */
36
    private $namespaces;
37
38
    /**
39
     * @var ReflectionClass[]
40
     */
41
    private $reflections;
42
43
    /**
44
     * @var Reader
45
     */
46
    private $annotationReader;
47
48
    /**
49
     * @var self
50
     */
51
    private static $defaultInstance;
52
53
    /**
54
     * Initializes the rule with the defined namespaces.
55
     *
56
     * If the default namespace is not in the array, it will be add to the end
57
     * of the array.
58
     *
59
     * @param array $namespaces
60
     */
61 11
    public function __construct(array $namespaces = [])
62
    {
63 11
        if (!in_array(__NAMESPACE__, $namespaces)) {
64 9
            $namespaces[] = __NAMESPACE__;
65
        }
66
67 11
        $this->namespaces = $namespaces;
68 11
        $this->annotationReader = new SimpleAnnotationReader();
69 11
        foreach ($namespaces as $namespace) {
70 11
            $this->annotationReader->addNamespace(rtrim($namespace, '\\').'\\Annotations');
71
        }
72 11
    }
73
74
    /**
75
     * Defines the default instance of the factory.
76
     *
77
     * @param Factory $factory
78
     */
79 1
    public static function setDefaultInstance(self $factory)
80
    {
81 1
        self::$defaultInstance = $factory;
0 ignored issues
show
Documentation Bug introduced by
It seems like $factory of type object<self> is incompatible with the declared type object<Respect\Validation\Factory> of property $defaultInstance.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
82 1
    }
83
84
    /**
85
     * Returns the default instance of the factory.
86
     *
87
     * @return self
88
     */
89 2
    public static function getDefaultInstance(): self
90
    {
91 2
        if (!self::$defaultInstance instanceof self) {
92 1
            self::$defaultInstance = new self();
93
        }
94
95 2
        return self::$defaultInstance;
96
    }
97
98
    /**
99
     * Returns a list of namespaces.
100
     *
101
     * @return array
102
     */
103 9
    public function getNamespaces(): array
104
    {
105 9
        return $this->namespaces;
106
    }
107
108
    /**
109
     * Creates a rule based on its name with the defined arguments.
110
     *
111
     * @param string $ruleName
112
     * @param array  $arguments
113
     *
114
     * @throws ComponentException When the rule cannot be created
115
     *
116
     * @return Rule
117
     */
118 6
    public function rule(string $ruleName, array $arguments = []): Rule
119
    {
120 6
        foreach ($this->getNamespaces() as $namespace) {
121 6
            $className = rtrim($namespace, '\\').'\\Rules\\'.ucfirst($ruleName);
122 6
            if (!class_exists($className)) {
123 1
                continue;
124
            }
125
126 5
            $reflection = $this->getReflection($className);
127
128 5
            if (!$reflection->isSubclassOf(Rule::class)) {
129 1
                throw new InvalidRuleException(sprintf('"%s" is not a valid rule', $className));
130
            }
131
132 4
            if (!$reflection->isInstantiable()) {
133 1
                throw new InvalidRuleException(sprintf('"%s" is not instantiable', $className));
134
            }
135
136 3
            return $reflection->newInstanceArgs($arguments);
137
        }
138
139 1
        throw new RuleNotFoundException(sprintf('Could not find "%s" rule', $ruleName));
140
    }
141
142
    public function message(Result $result): Message
143
    {
144
        $reflection = $this->getExceptionReflection($result->getRule());
145
146
        /* @var Templates $templates */
147
        $templates = $this->annotationReader->getClassAnnotation($reflection, Templates::class);
148
149
        /* @var Template $template */
150
        $template = $this->chooseTemplate(
151
            $templates,
152
            $result->isInverted(),
153
            $result->getProperties()['templateId'] ?? Template::STANDARD_ID
154
        );
155
156
        return new Message($template->message, $result->getInput(), $result->getProperties(), $templates->isIgnorable);
157
    }
158
159
    public function exception(Result $result): ValidationException
160
    {
161
        $reflection = $this->getExceptionReflection($result->getRule());
162
        $message = $this->message($result);
163
        if ($message->isIgnorable()) {
164
            foreach ($result->getChildren() as $childResult) {
165
                $message = $this->message($result);
166
                if (!$message->isIgnorable()) {
167
                    break;
168
                }
169
            }
170
        }
171
172
        return $reflection->newInstance($message->__toString());
173
    }
174
175
    private function chooseTemplate(Templates $templates, bool $isInverted, string $templateId): Template
176
    {
177
        $templatesList = $templates->regular;
178
        if ($isInverted) {
179
            $templatesList = $templates->inverted;
180
        }
181
182
        foreach ($templatesList as $template) {
183
            if ($template->id != $templateId) {
184
                continue;
185
            }
186
187
            return $template;
188
        }
189
190
        return current($templateLists);
0 ignored issues
show
Bug introduced by
The variable $templateLists does not exist. Did you mean $templatesList?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
191
    }
192
193
    private function getExceptionReflection(Rule $rule): ReflectionClass
194
    {
195
        $exceptionName = str_replace('Rule', 'Exception', get_class($rule)).'Exception';
196
197
        return $this->getReflection($exceptionName);
198
    }
199
200
    /**
201
     * Creates a ReflectionClass object based on a class name.
202
     *
203
     * This method always return the same object for a given class name in order
204
     * to improve performance.
205
     *
206
     * @param string $className
207
     *
208
     * @return ReflectionClass
209
     */
210 5
    private function getReflection(string $className): ReflectionClass
211
    {
212 5
        if (!isset($this->reflections[$className])) {
213 5
            $this->reflections[$className] = new ReflectionClass($className);
214
        }
215
216 5
        return $this->reflections[$className];
217
    }
218
}
219