Completed
Push — master ( 9039a7...d108e4 )
by Joschi
04:16
created

Antibot::getScopedParameters()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
/**
4
 * antibot
5
 *
6
 * @category   Jkphl
7
 * @package    Jkphl\Antibot
8
 * @subpackage Jkphl\Antibot\Domain
9
 * @author     Joschi Kuphal <[email protected]> / @jkphl
10
 * @copyright  Copyright © 2018 Joschi Kuphal <[email protected]> / @jkphl
11
 * @license    http://opensource.org/licenses/MIT The MIT License (MIT)
12
 */
13
14
/***********************************************************************************
15
 *  The MIT License (MIT)
16
 *
17
 *  Copyright © 2018 Joschi Kuphal <[email protected]>
18
 *
19
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
20
 *  this software and associated documentation files (the "Software"), to deal in
21
 *  the Software without restriction, including without limitation the rights to
22
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
23
 *  the Software, and to permit persons to whom the Software is furnished to do so,
24
 *  subject to the following conditions:
25
 *
26
 *  The above copyright notice and this permission notice shall be included in all
27
 *  copies or substantial portions of the Software.
28
 *
29
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
31
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
32
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
33
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
34
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
35
 ***********************************************************************************/
36
37
namespace Jkphl\Antibot\Domain;
38
39
use Jkphl\Antibot\Domain\Contract\ValidatorInterface;
40
use Jkphl\Antibot\Domain\Exceptions\BlacklistValidationException;
41
use Jkphl\Antibot\Domain\Exceptions\ErrorException;
42
use Jkphl\Antibot\Domain\Exceptions\InvalidArgumentException;
43
use Jkphl\Antibot\Domain\Exceptions\RuntimeException;
44
use Jkphl\Antibot\Domain\Exceptions\SkippedValidationException;
45
use Jkphl\Antibot\Domain\Exceptions\WhitelistValidationException;
46
use Jkphl\Antibot\Domain\Model\ValidationResult;
47
use Jkphl\Antibot\Infrastructure\Model\InputElement;
48
use Psr\Http\Message\ServerRequestInterface;
49
use Psr\Log\LoggerAwareInterface;
50
use Psr\Log\LoggerInterface;
51
use Psr\Log\NullLogger;
52
53
/**
54
 * Antibot core
55
 *
56
 * @package    Jkphl\Antibot
57
 * @subpackage Jkphl\Antibot\Domain
58
 */
59
class Antibot implements LoggerAwareInterface
60
{
61
    /**
62
     * Session persistent, unique token
63
     *
64
     * @var string
65
     */
66
    protected $unique;
67
    /**
68
     * Antibot prefix
69
     *
70
     * @var string
71
     */
72
    protected $prefix;
73
    /**
74
     *
75
     *
76
     * @var array
77
     */
78
    protected $scope = [];
79
    /**
80
     * Unique signature
81
     *
82
     * @var string
83
     */
84
    protected $signature;
85
    /**
86
     * Parameter prefix
87
     *
88
     * @var string
89
     */
90
    protected $parameterPrefix;
91
    /**
92
     * GET & POST data
93
     *
94
     * @var null|array
95
     */
96
    protected $data = null;
97
    /**
98
     * Validators
99
     *
100
     * @var ValidatorInterface[]
101
     */
102
    protected $validators = [];
103
    /**
104
     * Immutable instance
105
     *
106
     * @var bool
107
     */
108
    protected $immutable = false;
109
    /**
110
     * Logger
111
     *
112
     * @var LoggerInterface
113
     */
114
    protected $logger = null;
115
    /**
116
     * Default antibot prefix
117
     *
118
     * @var string
119
     */
120
    const DEFAULT_PREFIX = 'antibot';
121
122
    /**
123
     * Antibot constructor
124
     *
125
     * @param string $unique Session-persistent, unique key
126
     * @param string $prefix Prefix
127
     */
128 20
    public function __construct(string $unique, string $prefix = self::DEFAULT_PREFIX)
129
    {
130 20
        $this->unique = $unique;
131 20
        $this->prefix = $prefix;
132 20
        $this->logger = new NullLogger();
133 20
    }
134
135
    /**
136
     * Return the session persistent, unique token
137
     *
138
     * @return string Session persistent, unique token
139
     */
140 5
    public function getUnique(): string
141
    {
142 5
        return $this->unique;
143
    }
144
145
    /**
146
     * Return the prefix
147
     *
148
     * @return string Prefix
149
     */
150 2
    public function getPrefix(): string
151
    {
152 2
        return $this->prefix;
153
    }
154
155
    /**
156
     * Return the submitted Antibot data
157
     *
158
     * @return string[] Antibot data
159
     */
160 5
    public function getData(): ?array
161
    {
162 5
        $this->checkInitialized();
163
164 4
        return $this->data;
165
    }
166
167
    /**
168
     * Return the parameter prefix
169
     *
170
     * @return string Parameter prefix
171
     * @throws RuntimeException If Antibot needs to be initialized
172
     */
173 14
    public function getParameterPrefix(): string
174
    {
175 14
        $this->checkInitialized();
176
177 13
        return $this->parameterPrefix;
178
    }
179
180
    /**
181
     * Add a validator
182
     *
183
     * @param ValidatorInterface $validator Validator
184
     */
185 12
    public function addValidator(ValidatorInterface $validator): void
186
    {
187 12
        $this->checkImmutable();
188 12
        $this->validators[] = $validator;
189 12
    }
190
191
    /**
192
     * Validate a request
193
     *
194
     * @param ServerRequestInterface $request Request
195
     *
196
     * @return ValidationResult Validation result
197
     */
198 12
    public function validate(ServerRequestInterface $request): ValidationResult
199
    {
200 12
        $this->logger->info('Start validation');
201 12
        $this->initialize($request);
202 12
        $result = new ValidationResult();
203
204
        // Run through all validators (in order)
205
        /** @var ValidatorInterface $validator */
206 12
        foreach ($this->validators as $validator) {
207
            try {
208 11
                if (!$validator->validate($request, $this)) {
209 6
                    $result->setValid(false);
210
                }
211
212
                // If the validator skipped validation
213 9
            } catch (SkippedValidationException $e) {
214 3
                $result->addSkip($e->getMessage());
215
216
                // If the request failed a blacklist test
217 7
            } catch (BlacklistValidationException $e) {
218 1
                $result->addBlacklist($e->getMessage());
219 1
                $result->setValid(false);
220
221
                // If the request passed a whitelist test
222 6
            } catch (WhitelistValidationException $e) {
223 2
                $result->addWhitelist($e->getMessage());
224 2
                break;
225
226
                // If an error occured
227 4
            } catch (ErrorException $e) {
228 4
                $result->addError($e);
229 9
                $result->setValid(false);
230
            }
231
        }
232
233 12
        $this->logger->info('Finished validation');
234
235 12
        return $result;
236
    }
237
238
    /**
239
     * Create and return the raw armor input elements
240
     *
241
     * @param ServerRequestInterface $request Request
242
     *
243
     * @return InputElement[] Armor input elements
244
     */
245 5
    public function armorInputs(ServerRequestInterface $request): array
246
    {
247 5
        $this->initialize($request);
248 5
        $armor = [];
249
250
        // Run through all validators (in order)
251
        /** @var ValidatorInterface $validator */
252 5
        foreach ($this->validators as $validator) {
253 5
            $validatorArmor = $validator->armor($request, $this);
254 5
            if (!empty($validatorArmor)) {
255 5
                $armor = array_merge($armor, $validatorArmor);
256
            }
257
        }
258
259 5
        return $armor;
260
    }
261
262
    /**
263
     * Compare and sort validators
264
     *
265
     * @param ValidatorInterface $validator1 Validator 1
266
     * @param ValidatorInterface $validator2 Validator 2
267
     *
268
     * @return int Sorting
269
     */
270
    protected function sortValidators(ValidatorInterface $validator1, ValidatorInterface $validator2): int
271
    {
272
        $validatorPos1 = $validator1->getPosition();
273
        $validatorPos2 = $validator2->getPosition();
274
        if ($validatorPos1 == $validatorPos2) {
275
            return 0;
276
        }
277
278
        return ($validatorPos1 > $validatorPos2) ? 1 : -1;
279
    }
280
281
    /**
282
     * Pre-validation initialization
283
     *
284
     * @param ServerRequestInterface $request Request
285
     */
286 13
    protected function initialize(ServerRequestInterface $request): void
287
    {
288 13
        if (!$this->immutable) {
289 13
            $this->immutable = true;
290 13
            usort($this->validators, [$this, 'sortValidators']);
291 13
            $this->signature       = $this->calculateSignature();
292 13
            $this->parameterPrefix = $this->prefix.'_'.$this->signature;
293
        }
294 13
        $this->extractData($request);
295 13
    }
296
297
    /**
298
     * Calculate the unique signature
299
     *
300
     * @return string Signature
301
     */
302 13
    protected function calculateSignature(): string
303
    {
304 13
        $params = [$this->prefix, $this->validators];
305
306 13
        return sha1($this->unique.serialize($params));
307
    }
308
309
    /**
310
     * Extract the antibot data from GET and POST parameters
311
     *
312
     * @param ServerRequestInterface $request Request
313
     */
314 13
    protected function extractData(ServerRequestInterface $request): void
315
    {
316 13
        $get        = $this->extractScopedData($request->getQueryParams());
317 13
        $post       = $this->extractScopedData($request->getParsedBody());
0 ignored issues
show
Bug introduced by
It seems like $request->getParsedBody() targeting Psr\Http\Message\ServerR...erface::getParsedBody() can also be of type null or object; however, Jkphl\Antibot\Domain\Antibot::extractScopedData() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
318 13
        $this->data = (($get !== null) || ($post !== null)) ? array_merge((array)$get, (array)$post) : null;
319 13
    }
320
321
    /**
322
     * Extract scoped data
323
     *
324
     * @param array $data Source data
325
     *
326
     * @return array|null Scoped data
327
     */
328 13
    protected function extractScopedData(array $data): ?array
329
    {
330
        // Run through all scope nodes
331 13
        foreach (array_merge($this->scope, [$this->getParameterPrefix()]) as $node) {
332 13
            if (!isset($data[$node])) {
333 13
                return null;
334
            }
335
336 4
            $data = $data[$node];
337
        }
338
339 4
        return $data;
340
    }
341
342
    /**
343
     * Check whether this Antibot instance is immutable
344
     *
345
     * @throws RuntimeException If the Antibot instance is immutable
346
     */
347 12
    protected function checkImmutable(): void
348
    {
349 12
        if ($this->immutable) {
350
            throw new RuntimeException(
351
                RuntimeException::ANTIBOT_IMMUTABLE_STR,
352
                RuntimeException::ANTIBOT_IMMUTABLE
353
            );
354
        }
355 12
    }
356
357
    /**
358
     * Check whether this Antibot instance is already initialized
359
     *
360
     * @throws RuntimeException If the Antibot instance still needs to be initialized
361
     */
362 15
    protected function checkInitialized(): void
363
    {
364
        // If the Antibot instance still needs to be initialized
365 15
        if (!$this->immutable) {
366 2
            throw new RuntimeException(
367 2
                RuntimeException::ANTIBOT_INITIALIZE_STR,
368 2
                RuntimeException::ANTIBOT_INITIALIZE
369
            );
370
        }
371 13
    }
372
373
    /**
374
     * Return the logger
375
     *
376
     * @return LoggerInterface Logger
377
     */
378 6
    public function getLogger(): LoggerInterface
379
    {
380 6
        return $this->logger;
381
    }
382
383
    /**
384
     * Sets a logger instance on the object
385
     *
386
     * @param LoggerInterface $logger Logger
387
     *
388
     * @return void
389
     */
390 12
    public function setLogger(LoggerInterface $logger): void
391
    {
392 12
        $this->logger = $logger;
393 12
    }
394
395
    /**
396
     * Set the parameter scope
397
     *
398
     * @param string[] ...$scope Parameter scope
399
     */
400 1
    public function setParameterScope(...$scope): void
401
    {
402
        // Run through all scope nodes
403 1
        foreach ($scope as $node) {
404 1
            if (!is_string($node) || empty($node)) {
405 1
                throw new InvalidArgumentException(
406 1
                    sprintf(InvalidArgumentException::INVALID_SCOPE_NODE_STR, $node),
407 1
                    InvalidArgumentException::INVALID_SCOPE_NODE
408
                );
409
            }
410
411 1
            $this->scope[] = $node;
412
        }
413 1
    }
414
415
    /**
416
     * Scope a set of parameters
417
     *
418
     * @param array $params Parameters
419
     *
420
     * @return array Scoped parameters
421
     */
422 2
    public function getScopedParameters(array $params): array
423
    {
424 2
        $params = [$this->getParameterPrefix() => $params];
425 2
        $scope  = $this->scope;
426 2
        while ($node = array_pop($scope)) {
427 1
            $params = [$node => $params];
428
        }
429
430 2
        return $params;
431
    }
432
}
433