diff --git a/src/CacheQueryServiceProvider.php b/src/CacheQueryServiceProvider.php index 660019f..01b221f 100644 --- a/src/CacheQueryServiceProvider.php +++ b/src/CacheQueryServiceProvider.php @@ -87,12 +87,16 @@ protected function macro(): Closure $this->connection = $this->connection->connection; } + $cache = new Cache(); + + match (true) { + $ttl instanceof Closure => $ttl($cache), + ! $ttl instanceof Cache => $cache->ttl($ttl), + default => $cache = $ttl + }; + // Normalize the TTL argument to a Cache instance. - $this->connection = Proxy::crateNewInstance($this->connection, match (true) { - $ttl instanceof Closure => $ttl(new Cache), - ! $ttl instanceof Cache => (new Cache)->ttl($ttl), - default => $ttl - }); + $this->connection = Proxy::crateNewInstance($this->connection, $cache); return $this; }; diff --git a/tests/ProxyTest.php b/tests/ProxyTest.php index b0f5602..a13faec 100644 --- a/tests/ProxyTest.php +++ b/tests/ProxyTest.php @@ -71,13 +71,6 @@ protected function defineDatabaseMigrations(): void }); } - public function test_passes_through_method_calls(): void - { - $query = $this->app->make('db')->table('users')->cache()->where('id', 1); - - static::assertSame([], $query->getConnection()->getQueryLog()); - } - public function test_caches_base_query_into_default_store(): void { $get = $this->app->make('db')->table('users')->cache()->where('id', 1)->get(); @@ -874,6 +867,10 @@ public function test_pass_through_methods_to_wrapped_connection(): void $connection->setDatabaseName('foo'); static::assertSame('foo', $connection->getDatabaseName()); + + $query = $this->app->make('db')->table('users')->cache()->where('id', 1); + + static::assertSame([], $query->getConnection()->getQueryLog()); } public function test_pass_through_properties_set_and_get(): void @@ -916,6 +913,24 @@ public function test_sets_custom_query_hasher(): void static::assertTrue($this->app->make('cache')->has('cache-query|test_hash')); } + + public function test_base_query_uses_cache_callback(): void + { + $hash = 'cache-query|fj8Xyz4K1Zh0tdAamPbG1A'; + + $repository = $this->mock(Repository::class); + $repository->expects('flexible')->never(); + $repository->expects('put')->with($hash, Mockery::type('array'), [5, 300])->once(); + $repository->expects('getMultiple')->with([$hash, ''])->times(1)->andReturn(['' => null, $hash => null]); + + $this->mock('cache')->expects('store')->with(null)->andReturn($repository); + + $this->app->make('db')->table('users')->where('id', 1)->cache(function ($cache) { + static::assertInstanceOf(Cache::class, $cache); + + $cache->ttl([5, 300]); + })->first(); + } } class User extends Authenticatable