diff --git a/src/Avatar.php b/src/Avatar.php index a8c20f2..4bb7286 100644 --- a/src/Avatar.php +++ b/src/Avatar.php @@ -202,6 +202,8 @@ public function toBase64(): string return $this->image->encodeUsingFormat(Format::PNG)->toDataUri(); } + $this->buildInitial(); + $key = $this->cacheKeyPrefix.$this->cacheKey(); // Check if the image is in the cache diff --git a/tests/AvatarPhpTest.php b/tests/AvatarPhpTest.php index 213adfb..1a2e28f 100644 --- a/tests/AvatarPhpTest.php +++ b/tests/AvatarPhpTest.php @@ -205,6 +205,34 @@ public function it_can_generate_base64_from_cache() $this->assertEquals($cachedAvatar, $result); } + #[Test] + public function it_uses_computed_initials_in_cache_key_for_to_base64() + { + $name = 'John Doe'; + + // Compute the expected cache key by building initials with FooGenerator first + $helperAvatar = new \Laravolt\Avatar\Avatar; + $helperAvatar->setGenerator(new FooGenerator); + $helperAvatar->create($name)->setDimension(5, 5); + $reflection = new \ReflectionClass($helperAvatar); + $buildInitial = $reflection->getMethod('buildInitial'); + $buildInitial->setAccessible(true); + $buildInitial->invoke($helperAvatar); + $cacheKeyMethod = $reflection->getMethod('cacheKey'); + $cacheKeyMethod->setAccessible(true); + $expectedKey = 'avatar_'.$cacheKeyMethod->invoke($helperAvatar); + + // Assert that toBase64() calls cache->get() with the initials-based key, + // confirming buildInitial() runs before cacheKey() in toBase64() + $cache = Mockery::mock('Illuminate\Contracts\Cache\Repository'); + $cache->shouldReceive('get')->with($expectedKey)->once()->andReturn(null); + $cache->shouldReceive('put')->andReturn(true); + + $avatar = new \Laravolt\Avatar\Avatar([], $cache); + $avatar->setGenerator(new FooGenerator); + $avatar->create($name)->setDimension(5, 5)->toBase64(); + } + #[Test] public function it_can_generate_file() {