MacHashCalculator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 13
dl 0
loc 86
rs 10
c 1
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getPrivateKey() 0 3 1
A hashValue() 0 3 1
A validateMac() 0 3 1
A removeDelimiters() 0 3 1
A __construct() 0 3 1
A createMacString() 0 5 1
A calculateMac() 0 5 1
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace SprykerEco\Service\CrefoPayApi\HashCalculator;
9
10
use SprykerEco\Service\CrefoPayApi\CrefoPayApiConfig;
11
12
class MacHashCalculator implements MacHashCalculatorInterface
13
{
14
    /**
15
     * @var string
16
     */
17
    protected const HASHING_ALGORITHM = 'sha1';
18
19
    /**
20
     * @var array
21
     */
22
    protected const CHARS_TO_REPLACE = [' ', "\t", "\s", "\r", "\n"];
23
24
    /**
25
     * @var \SprykerEco\Service\CrefoPayApi\CrefoPayApiConfig
26
     */
27
    protected $config;
28
29
    /**
30
     * @param \SprykerEco\Service\CrefoPayApi\CrefoPayApiConfig $config
31
     */
32
    public function __construct(CrefoPayApiConfig $config)
33
    {
34
        $this->config = $config;
35
    }
36
37
    /**
38
     * @param array $data
39
     *
40
     * @return string
41
     */
42
    public function calculateMac(array $data): string
43
    {
44
        $macString = $this->createMacString($data);
45
46
        return $this->hashValue($macString);
47
    }
48
49
    /**
50
     * @param array $responseData
51
     * @param string $mac
52
     *
53
     * @return bool
54
     */
55
    public function validateMac(array $responseData, string $mac): bool
56
    {
57
        return $this->calculateMac($responseData) === $mac;
58
    }
59
60
    /**
61
     * @param array $data
62
     *
63
     * @return string
64
     */
65
    protected function createMacString(array $data): string
66
    {
67
        ksort($data);
68
69
        return $this->removeDelimiters(implode('', $data));
70
    }
71
72
    /**
73
     * @param string $value
74
     *
75
     * @return string
76
     */
77
    protected function hashValue(string $value): string
78
    {
79
        return hash_hmac(static::HASHING_ALGORITHM, $value, $this->getPrivateKey());
80
    }
81
82
    /**
83
     * @param string $macString
84
     *
85
     * @return string
86
     */
87
    protected function removeDelimiters(string $macString): string
88
    {
89
        return str_replace(static::CHARS_TO_REPLACE, '', $macString);
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    protected function getPrivateKey(): string
96
    {
97
        return $this->config->getPrivateKey();
98
    }
99
}
100