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

HashContainer   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 0
dl 0
loc 80
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A addHash() 0 11 3
A hasHash() 0 4 1
A getHash() 0 4 2
A equals() 0 9 2
A count() 0 4 1
A getIterator() 0 4 1
A serialize() 0 4 1
A unserialize() 0 6 1
1
<?php
2
3
namespace Storeman\Hash;
4
5
final class HashContainer implements \Countable, \IteratorAggregate, \Serializable
6
{
7
    /**
8
     * @var array
9
     */
10
    protected $map = [];
11
12
    public function addHash(string $algorithm, string $hash): HashContainer
13
    {
14
        if (array_key_exists($algorithm, $this->map) && $this->map[$algorithm] !== $hash)
15
        {
16
            throw new \LogicException("Trying to update existing hash with different hash for the algorithm '{$algorithm}'");
17
        }
18
19
        $this->map[$algorithm] = $hash;
20
21
        return $this;
22
    }
23
24
    public function hasHash(string $algorithm): bool
25
    {
26
        return array_key_exists($algorithm, $this->map);
27
    }
28
29
    public function getHash(string $algorithm): ?string
30
    {
31
        return array_key_exists($algorithm, $this->map) ? $this->map[$algorithm] : null;
32
    }
33
34
    /**
35
     * Compares the given instance to this instance.
36
     * They are called equal if the intersection of known hash values is equal.
37
     *
38
     * @param HashContainer $other
39
     * @return bool
40
     */
41
    public function equals(?HashContainer $other): bool
42
    {
43
        if ($other === null)
44
        {
45
            return false;
46
        }
47
48
        return array_intersect_key($this->map, $other->map) == array_intersect_key($other->map, $this->map);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function count(): int
55
    {
56
        return count($this->map);
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function getIterator(): \Iterator
63
    {
64
        return new \ArrayIterator($this->map);
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70
    public function serialize(): string
71
    {
72
        return serialize($this->map);
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function unserialize($serialized): HashContainer
79
    {
80
        $this->map = unserialize($serialized);
81
82
        return $this;
83
    }
84
}
85