From e6f21f999e7848ab4b3fe601da3955c7812b7ee5 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 9 Feb 2016 09:52:25 +0100 Subject: [PATCH] [Cache] Count cache hits/misses in ProxyAdapter --- .../Component/Cache/Adapter/ProxyAdapter.php | 37 ++++++++++++++++++- .../Cache/Tests/Adapter/ProxyAdapterTest.php | 17 +++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php index 7e5c9aa20393d..eaeb5ba4fbd44 100644 --- a/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/ProxyAdapter.php @@ -22,6 +22,8 @@ class ProxyAdapter implements CacheItemPoolInterface { private $pool; private $createCacheItem; + private $hits = 0; + private $misses = 0; public function __construct(CacheItemPoolInterface $pool) { @@ -47,8 +49,13 @@ public function getItem($key) { $f = $this->createCacheItem; $item = $this->pool->getItem($key); + if ($isHit = $item->isHit()) { + ++$this->hits; + } else { + ++$this->misses; + } - return $f($key, $item->get(), $item->isHit()); + return $f($key, $item->get(), $isHit); } /** @@ -134,7 +141,33 @@ private function generateItems($items) $f = $this->createCacheItem; foreach ($items as $key => $item) { - yield $key => $f($key, $item->get(), $item->isHit()); + if ($isHit = $item->isHit()) { + ++$this->hits; + } else { + ++$this->misses; + } + + yield $key => $f($key, $item->get(), $isHit); } } + + /** + * Returns the number of cache read hits. + * + * @return int + */ + public function getHits() + { + return $this->hits; + } + + /** + * Returns the number of cache read misses. + * + * @return int + */ + public function getMisses() + { + return $this->misses; + } } diff --git a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php index 76606e256eea6..58594b0e1ef0d 100644 --- a/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php +++ b/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php @@ -29,4 +29,21 @@ public function createCachePool() { return new ProxyAdapter(new ArrayAdapter()); } + + public function testGetHitsMisses() + { + $pool = $this->createCachePool(); + + $this->assertSame(0, $pool->getHits()); + $this->assertSame(0, $pool->getMisses()); + + $bar = $pool->getItem('bar'); + $this->assertSame(0, $pool->getHits()); + $this->assertSame(1, $pool->getMisses()); + + $pool->save($bar->set('baz')); + $bar = $pool->getItem('bar'); + $this->assertSame(1, $pool->getHits()); + $this->assertSame(1, $pool->getMisses()); + } }