Completed
Push — master ( 2a17e7...e610ee )
by Arne
04:45
created

AggregateHashAlgorithm::addAlgorithm()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Storeman\Hash;
4
5
use Storeman\Hash\Algorithm\HashAlgorithmInterface;
6
7
final class AggregateHashAlgorithm
8
{
9
    /**
10
     * @var HashAlgorithmInterface[]
11
     */
12
    protected $algorithms = [];
13
14
    /**
15
     * @param HashAlgorithmInterface[] $algorithms
16
     */
17
    public function __construct(array $algorithms = [])
18
    {
19
        foreach ($algorithms as $algorithm)
20
        {
21
            $this->addAlgorithm($algorithm);
22
        }
23
    }
24
25
    public function addAlgorithm(HashAlgorithmInterface $algorithm): AggregateHashAlgorithm
26
    {
27
        if (array_key_exists($algorithm->getName(), $this->algorithms))
28
        {
29
            throw new \InvalidArgumentException("Trying to re-add hash algorithm named '{$algorithm->getName()}'");
30
        }
31
32
        $this->algorithms[$algorithm->getName()] = $algorithm;
33
34
        return $this;
35
    }
36
37
    public function initialize()
38
    {
39
        array_walk($this->algorithms, function(HashAlgorithmInterface $algorithm) {
40
41
            $algorithm->initialize();
42
        });
43
    }
44
45
    public function digest(string $buffer)
46
    {
47
        array_walk($this->algorithms, function(HashAlgorithmInterface $algorithm) use ($buffer) {
48
49
            $algorithm->digest($buffer);
50
        });
51
    }
52
53
    /**
54
     * Finalizes hash computations and returns hashes as map algorithm->hash.
55
     *
56
     * @return array
57
     */
58
    public function finalize()
59
    {
60
        $hashes = [];
61
62
        foreach ($this->algorithms as $algorithm)
63
        {
64
            $hashes[$algorithm->getName()] = $algorithm->finalize();
65
        }
66
67
        return $hashes;
68
    }
69
}
70