RepetitiveHashingTrait::repetitiveHashData()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 27
ccs 19
cts 19
cp 1
rs 9.7998
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
/**
4
 * Trait implementation of repetitive/recursive hashing for digestion algorithms.
5
 */
6
7
namespace CryptoManana\Core\Traits\MessageDigestion;
8
9
use CryptoManana\Core\Abstractions\MessageDigestion\AbstractHashAlgorithm as AnyDerivedHashAlgorithm;
10
use CryptoManana\Core\Interfaces\MessageDigestion\RepetitiveHashingInterface as RepetitiveHashingSpecification;
11
12
/**
13
 * Trait RepetitiveHashingTrait - Reusable implementation of `RepetitiveHashingInterface`.
14
 *
15
 * @see \CryptoManana\Core\Interfaces\MessageDigestion\RepetitiveHashingInterface The abstract specification.
16
 *
17
 * @package CryptoManana\Core\Traits\MessageDigestion
18
 *
19
 * @mixin RepetitiveHashingSpecification
20
 * @mixin AnyDerivedHashAlgorithm
21
 */
22
trait RepetitiveHashingTrait
23
{
24
    /**
25
     * Calculates a hash value for the given data.
26
     *
27
     * @param string $data The input string.
28
     *
29
     * @return string The digest.
30
     * @throws \Exception Validation errors.
31
     */
32
    abstract public function hashData($data);
33
34
    /**
35
     * Calculates a hash value for the given data via repetitive/recursive digestion.
36
     *
37
     * @param string $data The input string.
38
     * @param int $iterations The number of internal iterations to perform.
39
     *
40
     * @return string The digest.
41
     * @throws \Exception Validation errors.
42
     */
43 135
    public function repetitiveHashData($data, $iterations = 2)
44
    {
45 135
        $iterations = filter_var(
46 135
            $iterations,
47 135
            FILTER_VALIDATE_INT,
48 135
            [
49 135
                "options" => [
50 135
                    "min_range" => 2,
51 135
                    "max_range" => PHP_INT_MAX,
52 135
                ],
53 135
            ]
54 135
        );
55
56 135
        if ($iterations === false) {
57 45
            throw new \InvalidArgumentException('The repeated hashing times must be a valid integer bigger than 1.');
58
        }
59
60 90
        $oldDigestFormat = $this->digestFormat;
61 90
        $this->digestFormat = self::DIGEST_OUTPUT_RAW;
62
63 90
        for ($i = 1; $i < $iterations; $i++) {
64 90
            $data = $this->hashData($data);
65
        }
66
67 45
        $this->digestFormat = $oldDigestFormat;
68
69 45
        return $this->hashData($data);
70
    }
71
}
72