-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathContext.php
95 lines (79 loc) · 2.24 KB
/
Context.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace Psl\Hash;
use HashContext;
use function hash_final;
use function hash_init;
use function hash_update;
use const HASH_HMAC;
/**
* Incremental hashing context.
*
* Example:
*
* Hash\Context::forAlgorithm('md5')
* ->update('The quick brown fox ')
* ->update('jumped over the lazy dog.')
* ->finalize()
* => Str("5c6ffbdd40d9556b73a21e63c3e0e904")
*
* @psalm-immutable
*/
final class Context
{
private HashContext $internalContext;
private function __construct(HashContext $internal_context)
{
$this->internalContext = $internal_context;
}
/**
* Initialize an incremental hashing context.
*
* @pure
*/
public static function forAlgorithm(Algorithm $algorithm): Context
{
$internal_context = hash_init($algorithm->value);
return new self($internal_context);
}
/**
* Initialize an incremental HMAC hashing context.
*
* @param non-empty-string $key
*
* @pure
*/
public static function hmac(Hmac\Algorithm $algorithm, string $key): Context
{
$internal_context = hash_init($algorithm->value, HASH_HMAC, $key);
return new self($internal_context);
}
/**
* Pump data into an active hashing context.
*
* @psalm-mutation-free
*
* @throws Exception\RuntimeException If unable to pump data into the active hashing context.
*/
public function update(string $data): Context
{
$internal_context = hash_copy($this->internalContext);
// @codeCoverageIgnoreStart
/** @psalm-suppress ImpureFunctionCall - it creates a copy of the context, so we can consider it pure! */
if (!hash_update($internal_context, $data)) {
throw new Exception\RuntimeException('Unable to pump data into the active hashing context.');
}
// @codeCoverageIgnoreEnd
return new self($internal_context);
}
/**
* Finalize an incremental hash and return resulting digest.
*
* @psalm-mutation-free
*/
public function finalize(): string
{
$internal_context = hash_copy($this->internalContext);
return hash_final($internal_context, false);
}
}