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 (#899)
by Henrique
02:47
created

Factory::appendRulePrefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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
declare(strict_types=1);
13
14
namespace Respect\Validation;
15
16
use function array_map;
17
use function array_merge;
18
use function array_unique;
19
use function class_exists;
20
use function lcfirst;
21
use function Respect\Stringifier\stringify;
0 ignored issues
show
introduced by
The function Respect\Stringifier\stringify was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
22
use ReflectionClass;
23
use ReflectionObject;
24
use Respect\Validation\Exceptions\ComponentException;
25
use Respect\Validation\Exceptions\InvalidClassException;
26
use Respect\Validation\Exceptions\ValidationException;
27
28
/**
29
 * Factory of objects.
30
 *
31
 * @author Henrique Moody <[email protected]>
32
 *
33
 * @since 0.8.0
34
 */
35
final class Factory
36
{
37
    public const DEFAULT_RULES_NAMESPACES = [
38
        'Respect\\Validation\\Rules',
39
        'Respect\\Validation\\Rules\\Locale',
40
        'Respect\\Validation\\Rules\\SubdivisionCode',
41
    ];
42
43
    public const DEFAULT_EXCEPTIONS_NAMESPACES = [
44
        'Respect\\Validation\\Exceptions',
45
        'Respect\\Validation\\Exceptions\\Locale',
46
        'Respect\\Validation\\Exceptions\\SubdivisionCode',
47
    ];
48
49
    /**
50
     * Default instance of the Factory.
51
     *
52
     * @var Factory
53
     */
54
    private static $defaultInstance;
55
56
    /**
57
     * @var string[]
58
     */
59
    private $rulesNamespaces = [];
60
61
    /**
62
     * @var string[]
63
     */
64
    private $exceptionsNamespaces = [];
65
66
    /**
67
     * Initializes the factory with the defined namespaces.
68
     *
69
     * If the default namespace is not in the array, it will be add to the end
70
     * of the array.
71
     *
72
     * @param string[] $rulesNamespaces
73
     * @param string[] $exceptionsNamespaces
74
     */
75 302
    public function __construct(array $rulesNamespaces, array $exceptionsNamespaces)
76
    {
77 302
        $this->rulesNamespaces = $this->filterNamespaces($rulesNamespaces, self::DEFAULT_RULES_NAMESPACES);
78 302
        $this->exceptionsNamespaces = $this->filterNamespaces($exceptionsNamespaces, self::DEFAULT_EXCEPTIONS_NAMESPACES);
79 302
    }
80
81
    /**
82
     * Define the default instance of the Factory.
83
     *
84
     * @param Factory $defaultInstance
85
     */
86 1
    public static function setDefaultInstance(self $defaultInstance): void
87
    {
88 1
        self::$defaultInstance = $defaultInstance;
89 1
    }
90
91
    /**
92
     * Returns the default instance of the Factory.
93
     *
94
     * @return Factory
95
     */
96 293
    public static function getDefaultInstance(): self
97
    {
98 293
        if (null === self::$defaultInstance) {
99 289
            self::$defaultInstance = new self(self::DEFAULT_RULES_NAMESPACES, self::DEFAULT_EXCEPTIONS_NAMESPACES);
100
        }
101
102 293
        return self::$defaultInstance;
103
    }
104
105
    /**
106
     * Creates a rule.
107
     *
108
     * @param string $ruleName
109
     * @param array $arguments
110
     *
111
     * @throws ComponentException
112
     *
113
     * @return Validatable
114
     */
115 297
    public function rule(string $ruleName, array $arguments = []): Validatable
116
    {
117 297
        foreach ($this->rulesNamespaces as $namespace) {
118 297
            $className = sprintf('%s\\%s', $namespace, ucfirst($ruleName));
119 297
            if (!class_exists($className)) {
120 3
                continue;
121
            }
122
123 295
            return $this->createReflectionClass($className, Validatable::class)->newInstanceArgs($arguments);
124
        }
125
126 2
        throw new ComponentException(sprintf('"%s" is not a valid rule name', $ruleName));
127
    }
128
129
    /**
130
     * Creates an exception.
131
     *
132
     *
133
     * @param Validatable $validatable
134
     * @param mixed $input
135
     * @param array $extraParams
136
     *
137
     * @throws ComponentException
138
     *
139
     * @return ValidationException
140
     */
141 223
    public function exception(Validatable $validatable, $input, array $extraParams = []): ValidationException
142
    {
143 223
        $reflection = new ReflectionObject($validatable);
144 223
        $ruleName = $reflection->getShortName();
145 223
        foreach ($this->exceptionsNamespaces as $namespace) {
146 223
            $exceptionName = sprintf('%s\\%sException', $namespace, $ruleName);
147 223
            if (!class_exists($exceptionName)) {
148 6
                continue;
149
            }
150
151 222
            $name = $validatable->getName() ?: stringify($input);
152 222
            $params = ['input' => $input] + $extraParams;
153 222
            foreach ($reflection->getProperties() as $property) {
154 222
                $property->setAccessible(true);
155 222
                $params += [$property->getName() => $property->getValue($validatable)];
156
            }
157
158 222
            return $this->createValidationException($exceptionName, $name, $params);
159
        }
160
161 1
        throw new ComponentException(sprintf('Cannot find exception for "%s" rule', lcfirst($ruleName)));
162
    }
163
164
    /**
165
     * Creates a reflection based on class name.
166
     *
167
     *
168
     * @param string $name
169
     * @param string $parentName
170
     *
171
     * @throws InvalidClassException
172
     *
173
     * @return ReflectionClass
174
     */
175 300
    private function createReflectionClass(string $name, string $parentName): ReflectionClass
176
    {
177 300
        $reflection = new ReflectionClass($name);
178 300
        if (!$reflection->isSubclassOf($parentName)) {
179 1
            throw new InvalidClassException(sprintf('"%s" must be an instance of "%s"', $name, $parentName));
180
        }
181
182 299
        if (!$reflection->isInstantiable()) {
183 1
            throw new InvalidClassException(sprintf('"%s" must be instantiable', $name));
184
        }
185
186 298
        return $reflection;
187
    }
188
189
    /**
190
     * Filters namespaces.
191
     *
192
     * Ensure namespaces are in the right format and contain the default namespaces.
193
     *
194
     * @param array $namespaces
195
     * @param array $defaultNamespaces
196
     *
197
     * @return array
198
     */
199
    private function filterNamespaces(array $namespaces, array $defaultNamespaces): array
200
    {
201 302
        $filter = function (string $namespace): string {
202 302
            return trim($namespace, '\\');
203 302
        };
204
205 302
        return array_unique(
206 302
            array_merge(
207 302
                array_map($filter, $namespaces),
208 302
                array_map($filter, $defaultNamespaces)
209
            )
210
        );
211
    }
212
213
    /**
214
     * Creates a Validation exception.
215
     *
216
     * @param string $exceptionName
217
     * @param mixed $name
218
     * @param array $params
219
     *
220
     * @return ValidationException
221
     */
222 222
    private function createValidationException(string $exceptionName, $name, array $params): ValidationException
223
    {
224 222
        $exception = $this->createReflectionClass($exceptionName, ValidationException::class)->newInstance();
225 222
        $exception->configure($name, $params);
226 222
        if (isset($params['template'])) {
227 5
            $exception->setTemplate($params['template']);
228
        }
229
230 222
        return $exception;
231
    }
232
}
233