From 4395ac35b470e30e2f3735e7bb466c3865c41643 Mon Sep 17 00:00:00 2001 From: EriBloo <19932449+EriBloo@users.noreply.github.com> Date: Mon, 14 Oct 2024 19:10:31 +0000 Subject: [PATCH] add encrypted value modifier --- src/ValueObjects/Values/EncryptedModifier.php | 33 +++++++++++++++++++ tests/CacheObjectTest.php | 13 ++++++++ tests/Fixtures/EncryptedCacheObject.php | 32 ++++++++++++++++++ tests/TestCase.php | 5 ++- 4 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 src/ValueObjects/Values/EncryptedModifier.php create mode 100644 tests/Fixtures/EncryptedCacheObject.php diff --git a/src/ValueObjects/Values/EncryptedModifier.php b/src/ValueObjects/Values/EncryptedModifier.php new file mode 100644 index 0000000..f7d1b16 --- /dev/null +++ b/src/ValueObjects/Values/EncryptedModifier.php @@ -0,0 +1,33 @@ + + */ +final readonly class EncryptedModifier implements CacheValueModifier +{ + /** + * @param CacheValueModifier $modifier + */ + public function __construct( + private CacheValueModifier $modifier, + ) {} + + public function onLoad(string $value): mixed + { + return $this->modifier->onLoad(Crypt::decryptString($value)); + } + + public function onSave(mixed $value): string + { + return Crypt::encryptString($this->modifier->onSave($value)); + } +} diff --git a/tests/CacheObjectTest.php b/tests/CacheObjectTest.php index 0e46743..3c0a27f 100644 --- a/tests/CacheObjectTest.php +++ b/tests/CacheObjectTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use EriBloo\CacheObjects\Tests\Fixtures\BasicCacheObject; +use EriBloo\CacheObjects\Tests\Fixtures\EncryptedCacheObject; use EriBloo\CacheObjects\Tests\Fixtures\HashedCacheObject; use function PHPUnit\Framework\assertEquals; @@ -44,3 +45,15 @@ // assert assertNull($obj->retrieve()); }); + +it('encrypts value properly', function () { + // prepare + $obj = new EncryptedCacheObject; + + // execute + $obj->store('test'); + + // assert + assertEquals(serialize('test'), Crypt::decryptString(app('store')->get((string) $obj->key()))); + assertEquals('test', $obj->retrieve()); +}); diff --git a/tests/Fixtures/EncryptedCacheObject.php b/tests/Fixtures/EncryptedCacheObject.php new file mode 100644 index 0000000..de37f84 --- /dev/null +++ b/tests/Fixtures/EncryptedCacheObject.php @@ -0,0 +1,32 @@ +app?->instance('store', $store); $this->app?->instance(CacheObjectDriver::class, new LaravelDriver($store)); - Cache::spy(); + + Config::set('app.key', random_bytes(32)); + Config::set('app.cipher', 'aes-256-cbc'); } protected function getPackageProviders($app)