-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCryptoNormalizer.php
More file actions
75 lines (61 loc) · 2.15 KB
/
Copy pathCryptoNormalizer.php
File metadata and controls
75 lines (61 loc) · 2.15 KB
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
<?php
namespace Patchlevel\Hydrator\Cryptography;
use Closure;
use Patchlevel\Hydrator\Cryptography\Cipher\DecryptionFailed;
use Patchlevel\Hydrator\Cryptography\Store\CipherKeyNotExists;
use Patchlevel\Hydrator\Normalizer\ContextAwareNormalizer;
use Patchlevel\Hydrator\Normalizer\InvalidArgument;
use Patchlevel\Hydrator\Normalizer\Normalizer;
final class CryptoNormalizer implements Normalizer, ContextAwareNormalizer
{
public function __construct(
private readonly Cryptographer $cryptographer,
private readonly string $subjectIdName,
private readonly mixed $fallback = null,
private readonly Normalizer|null $normalizer = null,
) {
}
/**
* @param array<string, mixed> $context
*
* @throws InvalidArgument
*/
public function normalize(mixed $value, array $context = []): mixed
{
if ($this->normalizer !== null) {
$value = $this->normalizer->normalize($value, $context);
}
if ($value === null) {
return null;
}
$subjectId = $context[SubjectIds::class]->get($this->subjectIdName);
return ['__enc' => $this->cryptographer->encrypt($subjectId, $value)];
}
/**
* @param array<string, mixed> $context
*
* @throws InvalidArgument
*/
public function denormalize(mixed $value, array $context = []): mixed
{
if (!is_array($value) || !array_key_exists('__enc', $value)) {
if ($this->normalizer === null) {
return $value;
}
return $this->normalizer->denormalize($value, $context);
}
$subjectId = $context[SubjectIds::class]->get($this->subjectIdName);
try {
$data = $this->cryptographer->decrypt($subjectId, $value['__enc']);
} catch (DecryptionFailed|CipherKeyNotExists) {
if ($this->fallback instanceof Closure) {
return ($this->fallback)($subjectId, $value['__enc']);
}
return $this->fallback;
}
if ($this->normalizer === null) {
return $data;
}
return $this->normalizer->denormalize($data, $context);
}
}