Hash::check()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 18
ccs 8
cts 8
cp 1
crap 3
rs 9.9666
1
<?php
2
3
/**
4
 * This file is part of Dimtrovich/Validation.
5
 *
6
 * (c) 2023 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\Validation\Rules;
13
14
use InvalidArgumentException;
15
16
class Hash extends AbstractRule
17
{
18
    /**
19
     * @var array
20
     */
21
    protected $fillableParams = ['algo', 'allowUppercase'];
22
23
    private array $algorithmsLengths = [
24
        'MD5'    => 32,
25
        'SHA1'   => 40,
26
        'SHA256' => 64,
27
        'SHA512' => 128,
28
        'CRC32'  => 8,
29
    ];
30
31
    /**
32
     * Check if the given value is a valid cryptographic hash.
33
     *
34
     * @credit <a href="https://github.com/particle-php/Validator/">particle-php/Validator - Particle\Validator\Rule\Hash</a>
35
     *
36
     * @param mixed $value
37
     */
38
    public function check($value): bool
39
    {
40 2
        $this->requireParameters(['algo']);
41
42 2
        $algo = strtoupper($this->parameter('algo'));
43
44
        if (! isset($this->algorithmsLengths[$algo])) {
45 2
            $algos = array_keys($this->algorithmsLengths);
46
47 2
            throw new InvalidArgumentException('algo parameter must be one of ' . implode('/', $algos));
48
        }
49
50 2
        $this->setParameterText('algorithm', $algo);
51
52 2
        $length        = $this->algorithmsLengths[$algo];
53 2
        $caseSensitive = (bool) ($this->parameter('allowUppercase', false)) ? 'i' : '';
54
55 2
        return preg_match(sprintf('/^[0-9a-f]{%s}$/%s', $length, $caseSensitive), $value) === 1;
56
    }
57
}
58