Skip to content

Commit

Permalink
add option to hash key
Browse files Browse the repository at this point in the history
  • Loading branch information
EriBloo committed Oct 11, 2024
1 parent 3c5e2c3 commit f2d5423
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/Contracts/HashedKey.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace EriBloo\CacheObjects\Contracts;

interface HashedKey
{
public function hashAlgo(): string;
}
9 changes: 8 additions & 1 deletion src/Drivers/LaravelDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use EriBloo\CacheObjects\Contracts\CacheObject;
use EriBloo\CacheObjects\Contracts\CacheObjectDriver;
use EriBloo\CacheObjects\Contracts\HashedKey;
use Illuminate\Contracts\Cache\Store;

final class LaravelDriver implements CacheObjectDriver
Expand Down Expand Up @@ -53,7 +54,13 @@ public function delete(CacheObject $cacheObject): bool
*/
private function prepareKey(CacheObject $cacheObject): string
{
return $cacheObject->key();
$key = $cacheObject->key();

if ($cacheObject instanceof HashedKey) {
return hash($cacheObject->hashAlgo(), $key);
}

return $key;
}

private function prepareValue(mixed $value): string
Expand Down
13 changes: 13 additions & 0 deletions tests/CacheObjectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
declare(strict_types=1);

use EriBloo\CacheObjects\Tests\Fixtures\BasicCacheObject;
use EriBloo\CacheObjects\Tests\Fixtures\HashedCacheObject;

use function PHPUnit\Framework\assertEquals;

Expand All @@ -16,3 +17,15 @@
// assert
assertEquals('test', $obj->retrieve());
});

it('hashes key while storing', function () {
// prepare
$obj = new HashedCacheObject;

// execute
$key = $obj->store('test');

// assert
assertEquals(hash($obj->hashAlgo(), $obj->key()), $key);
assertEquals('test', $obj->retrieve());
});
33 changes: 33 additions & 0 deletions tests/Fixtures/HashedCacheObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace EriBloo\CacheObjects\Tests\Fixtures;

use Carbon\CarbonInterval;
use EriBloo\CacheObjects\Concerns\CacheObjectActions;
use EriBloo\CacheObjects\Contracts\CacheObject;
use EriBloo\CacheObjects\Contracts\HashedKey;

/**
* @implements CacheObject<string>
*/
final readonly class HashedCacheObject implements CacheObject, HashedKey
{
use CacheObjectActions;

public function key(): string
{
return 'hashed-cache-object';
}

public function ttl(): CarbonInterval
{
return CarbonInterval::seconds(0);
}

public function hashAlgo(): string
{
return 'sha256';
}
}

0 comments on commit f2d5423

Please sign in to comment.