Completed
Push — master ( b89557...66fcea )
by Vuong
02:09
created

HmacDataSignature::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 10
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * @link https://github.com/yiiviet/yii2-payment
4
 * @copyright Copyright (c) 2017 Yii Viet
5
 * @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
6
 */
7
8
namespace yiiviet\payment;
9
10
use yii\base\InvalidConfigException;
11
12
/**
13
 * Lớp HmacDataSignature dùng cho việc tạo và kiểm tra chữ ký theo chuẩn HMAC.
14
 *
15
 * @author Vuong Minh <[email protected]>
16
 * @since 1.0
17
 */
18
class HmacDataSignature extends DataSignature
19
{
20
21
    /**
22
     * Tên loại mã hóa. Ví dụ: md5, sha1, sha256...
23
     *
24
     * @var string
25
     */
26
    public $hmacAlgo;
27
28
    /**
29
     * Khóa mã hóa. Độ phức tạp càng cao thì dữ liệu càng được an toàn.
30
     *
31
     * @var string
32
     */
33
    public $key;
34
35
    /**
36
     * @var bool phân biệt ký tự hoa thường khi xác minh chữ ký.
37
     * @since 1.0.3
38
     */
39
    public $caseSensitive = true;
40
41
    /**
42
     * @inheritdoc
43
     * @throws InvalidConfigException
44
     */
45 13
    public function init()
46
    {
47 13
        if ($this->key === null) {
48
            throw new InvalidConfigException('Property `key` must be set for generate signature!');
49 13
        } elseif ($this->hmacAlgo === null) {
50
            throw new InvalidConfigException('Property `hmacAlgo` must be set for generate signature!');
51
        }
52
53 13
        parent::init();
54 13
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59 13
    public function generate(): string
60
    {
61 13
        return hash_hmac($this->hmacAlgo, $this->getData(), $this->key);
62
    }
63
64
    /**
65
     * @inheritdoc
66
     * @throws InvalidConfigException
67
     */
68 5 View Code Duplication
    public function validate(string $expect): bool
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
69
    {
70 5
        $actual = $this->generate();
71
72 5
        if ($this->caseSensitive) {
73 4
            return strcmp($expect, $actual) === 0;
74
        } else {
75 1
            return strcasecmp($expect, $actual) === 0;
76
        }
77
    }
78
79
}
80