Completed
Branch master (97b1c8)
by Tony Karavasilev (Тони
02:50
created

RepetitiveHashingTrait::repetitiveHashData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
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 14
cts 14
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\Interfaces\MessageDigestion\RepetitiveHashingInterface as RepetitiveHashingSpecification;
10
use \CryptoManana\Core\Abstractions\MessageDigestion\AbstractHashAlgorithm as AnyDerivedHashAlgorithm;
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 198
    public function repetitiveHashData($data, $iterations = 2)
44
    {
45 198
        $iterations = filter_var(
46 198
            $iterations,
47 198
            FILTER_VALIDATE_INT,
48
            [
49
                "options" => [
50 198
                    "min_range" => 2,
51 198
                    "max_range" => PHP_INT_MAX,
52
                ],
53
            ]
54
        );
55
56 198
        if ($iterations === false) {
57 66
            throw new \InvalidArgumentException('The repeated hashing times must be a valid integer bigger than 1.');
58
        }
59
60 132
        $oldDigestFormat = $this->digestFormat;
61 132
        $this->digestFormat = self::DIGEST_OUTPUT_RAW;
62
63 132
        for ($i = 1; $i < $iterations; $i++) {
64 132
            $data = $this->hashData($data);
65
        }
66
67 66
        $this->digestFormat = $oldDigestFormat;
68
69 66
        return $this->hashData($data);
70
    }
71
}
72