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

AggregateHashAlgorithm   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 63
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A addAlgorithm() 0 11 2
A initialize() 0 7 1
A digest() 0 7 1
A finalize() 0 11 2
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