Skip to content

Commit

Permalink
Add new HashKeyGenerator
Browse files Browse the repository at this point in the history
  • Loading branch information
rawilk committed Oct 16, 2024
1 parent 9cfadff commit 11dfc86
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
11 changes: 11 additions & 0 deletions config/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
| Supported:
| - \Rawilk\Settings\Support\KeyGenerators\ReadableKeyGenerator
| - \Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator (default)
| - \Rawilk\Settings\Support\KeyGenerators\HashKeyGenerator
|
*/
'key_generator' => \Rawilk\Settings\Support\KeyGenerators\Md5KeyGenerator::class,
Expand Down Expand Up @@ -194,4 +195,14 @@
\Carbon\CarbonImmutable::class,
\Illuminate\Support\Carbon::class,
],

/*
|--------------------------------------------------------------------------
| Hash Algorithm
|--------------------------------------------------------------------------
|
| The hashing algorithm to use for the HashKeyGenerator.
|
*/
'hash_algorithm' => 'xxh128',
];
40 changes: 40 additions & 0 deletions src/Support/KeyGenerators/HashKeyGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Rawilk\Settings\Support\KeyGenerators;

use Rawilk\Settings\Contracts\ContextSerializer;
use Rawilk\Settings\Contracts\KeyGenerator as KeyGeneratorContract;
use Rawilk\Settings\Support\Context;
use RuntimeException;

class HashKeyGenerator implements KeyGeneratorContract
{
protected ContextSerializer $serializer;

public function generate(string $key, Context $context = null): string
{
return hash(
config('settings.hash_algorithm', 'xxh128'),
$key . $this->serializer->serialize($context),
);
}

public function removeContextFromKey(string $key): string
{
throw new RuntimeException('HashKeyGenerator does not support removing the context from the key.');
}

public function setContextSerializer(ContextSerializer $serializer): static
{
$this->serializer = $serializer;

return $this;
}

public function contextPrefix(): string
{
throw new RuntimeException('HashKeyGenerator does not support a context prefix.');
}
}

0 comments on commit 11dfc86

Please sign in to comment.