Signature::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * @link https://github.com/phpviet/omnipay-onepay
4
 * @copyright (c) PHP Viet
5
 * @license [MIT](http://www.opensource.org/licenses/MIT)
6
 */
7
8
namespace Omnipay\OnePay\Support;
9
10
/**
11
 * @author Vuong Minh <[email protected]>
12
 * @since 1.0.0
13
 */
14
class Signature
15
{
16
    /**
17
     * Khóa bí mật dùng để tạo và kiểm tra chữ ký dữ liệu.
18
     *
19
     * @var string
20
     */
21
    protected $hashKey;
22
23
    /**
24
     * Khởi tạo đối tượng DataSignature.
25
     *
26
     * @param  string  $hashKey
27
     */
28
    public function __construct(string $hashKey)
29
    {
30
        $this->hashKey = pack('H*', $hashKey);
31
    }
32
33
    /**
34
     * Trả về chữ ký dữ liệu của dữ liệu truyền vào.
35
     *
36
     * @param  array  $data
37
     * @return string
38
     */
39
    public function generate(array $data): string
40
    {
41
        ksort($data);
42
        $dataSign = urldecode(http_build_query($data));
43
44
        return strtoupper(hash_hmac('sha256', $dataSign, $this->hashKey));
45
    }
46
47
    /**
48
     * Kiểm tra tính hợp lệ của chữ ký dữ liệu so với dữ liệu truyền vào.
49
     *
50
     * @param  array  $data
51
     * @param  string  $expect
52
     * @return bool
53
     */
54
    public function validate(array $data, string $expect): bool
55
    {
56
        $actual = $this->generate($data);
57
58
        return 0 === strcasecmp($expect, $actual);
59
    }
60
}
61