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

Hash::update()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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\Verifier;
16
17
use Assert\Assertion;
18
use KevinGH\Box\Verifier;
19
20
/**
21
 * Uses the PHP hash library to verify a signature.
22
 */
23
final class Hash implements Verifier
24
{
25
    /**
26
     * The hash context.
27
     *
28
     * @var resource
29
     */
30
    private $context;
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function __construct(string $algorithm, string $path)
36
    {
37
        $algorithm = strtolower(
38
            preg_replace(
39
                '/[^A-Za-z0-9]+/',
40
                '',
41
                $algorithm
42
            )
43
        );
44
45
        Assertion::inArray(
46
            $algorithm,
47
            hash_algos(),
48
            'Expected %s to be a known algorithm: "'
49
            .implode('", "', hash_algos())
50
            .'"'
51
        );
52
53
        $this->context = hash_init($algorithm);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function update(string $data): void
60
    {
61
        Assertion::notNull($this->context, 'Expected to be initialised before being updated.');
62
63
        hash_update($this->context, $data);
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function verify(string $signature): bool
70
    {
71
        return $signature === strtoupper(hash_final($this->context));
72
    }
73
}
74