Passed
Pull Request — master (#22)
by Théo
02:53
created

Hash::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Signature;
16
17
use Assert\Assertion;
18
19
/**
20
 * Uses the PHP hash library to verify a signature.
21
 */
22
final class Hash implements Verifier
23
{
24
    /**
25
     * The hash context.
26
     *
27
     * @var resource
28
     */
29
    private $context;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function __construct(string $algorithm, string $path)
35
    {
36
        $algorithm = strtolower(
37
            preg_replace(
38
                '/[^A-Za-z0-9]+/',
39
                '',
40
                $algorithm
41
            )
42
        );
43
44
        Assertion::inArray(
45
            $algorithm,
46
            hash_algos(),
47
            'Expected %s to be a known algorithm: "'
48
            .implode('", "', hash_algos())
49
            .'"'
50
        );
51
52
        $this->context = hash_init($algorithm);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function update(string $data): void
59
    {
60
        Assertion::notNull($this->context, 'Expected to be initialised before being updated.');
61
62
        hash_update($this->context, $data);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function verify(string $signature): bool
69
    {
70
        return $signature === strtoupper(hash_final($this->context));
71
    }
72
}
73