Skip to content

Commit 11dfc86

Browse files
committed
Add new HashKeyGenerator
1 parent 9cfadff commit 11dfc86

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

config/settings.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@
145145
| Supported:
146146
| - \Rawilk\Settings\Support\KeyGenerators\ReadableKeyGenerator
147147
| - \Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator (default)
148+
| - \Rawilk\Settings\Support\KeyGenerators\HashKeyGenerator
148149
|
149150
*/
150151
'key_generator' => \Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator::class,
@@ -194,4 +195,14 @@
194195
\Carbon\CarbonImmutable::class,
195196
\Illuminate\Support\Carbon::class,
196197
],
198+
199+
/*
200+
|--------------------------------------------------------------------------
201+
| Hash Algorithm
202+
|--------------------------------------------------------------------------
203+
|
204+
| The hashing algorithm to use for the HashKeyGenerator.
205+
|
206+
*/
207+
'hash_algorithm' => 'xxh128',
197208
];
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Rawilk\Settings\Support\KeyGenerators;
6+
7+
use Rawilk\Settings\Contracts\ContextSerializer;
8+
use Rawilk\Settings\Contracts\KeyGenerator as KeyGeneratorContract;
9+
use Rawilk\Settings\Support\Context;
10+
use RuntimeException;
11+
12+
class HashKeyGenerator implements KeyGeneratorContract
13+
{
14+
protected ContextSerializer $serializer;
15+
16+
public function generate(string $key, Context $context = null): string
17+
{
18+
return hash(
19+
config('settings.hash_algorithm', 'xxh128'),
20+
$key . $this->serializer->serialize($context),
21+
);
22+
}
23+
24+
public function removeContextFromKey(string $key): string
25+
{
26+
throw new RuntimeException('HashKeyGenerator does not support removing the context from the key.');
27+
}
28+
29+
public function setContextSerializer(ContextSerializer $serializer): static
30+
{
31+
$this->serializer = $serializer;
32+
33+
return $this;
34+
}
35+
36+
public function contextPrefix(): string
37+
{
38+
throw new RuntimeException('HashKeyGenerator does not support a context prefix.');
39+
}
40+
}

0 commit comments

Comments
 (0)