diff --git a/Tests/ProfilerExtension/ProfilerExtensionTest.php b/Tests/ProfilerExtension/ProfilerExtensionTest.php new file mode 100644 index 0000000..ab00a8f --- /dev/null +++ b/Tests/ProfilerExtension/ProfilerExtensionTest.php @@ -0,0 +1,54 @@ +kernel = new AppKernel('TwigCacheExtensionTest', true); + $this->kernel->boot(); + } + + /** + * @covers ::serialize + * @covers ::unserialize + */ + public function testSerialization() + { + $container = $this->kernel->getContainer(); + + $cacheStrategy = $container->get('twig_cache.strategy.generational'); + $extension = new ProfilerExtension($cacheStrategy); + + $extension->addFetchBlock('foo', true); + $extension->addGenerateKey('generation_key', 123); + + $data = $extension->getData(); + + $serializedData = serialize($extension); + + /** @var ProfilerExtension $unserialized */ + $unserialized = unserialize($serializedData); + + $this->assertInstanceOf('EmanueleMinotto\TwigCacheBundle\Twig\ProfilerExtension', $unserialized); + $dataUnserialized = $unserialized->getData(); + + $this->assertEquals($data, $dataUnserialized); + } +} diff --git a/Twig/ProfilerExtension.php b/Twig/ProfilerExtension.php index 43da92b..d1f1be2 100644 --- a/Twig/ProfilerExtension.php +++ b/Twig/ProfilerExtension.php @@ -6,6 +6,7 @@ use Asm89\Twig\CacheExtension\Extension as Asm89_Extension; use EmanueleMinotto\TwigCacheBundle\Strategy\ProfilerStrategy; use Exception; +use Serializable; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; @@ -13,7 +14,7 @@ /** * {@inheritdoc} */ -class ProfilerExtension extends Asm89_Extension implements DataCollectorInterface +class ProfilerExtension extends Asm89_Extension implements DataCollectorInterface, Serializable { /** * Data about fetchBlock requests. @@ -108,4 +109,41 @@ public function getData() 'strategyClass' => $this->strategyClass, ]; } + + /** + * String representation of object. + * + * @link http://php.net/manual/en/serializable.serialize.php + * + * @return string the string representation of the object or null + * + * @since 5.1.0 + */ + public function serialize() + { + return serialize($this->getData()); + } + + /** + * Constructs the object. + * + * @link http://php.net/manual/en/serializable.unserialize.php + * + * @param string $serialized + * + * @return void + * + * @since 5.1.0 + */ + public function unserialize($serialized) + { + $data = unserialize($serialized); + + if (is_array($data)) { + $this->fetchBlock = $data['fetchBlock']; + $this->generateKey = $data['generateKey']; + $this->hits = $data['hits']; + $this->strategyClass = $data['strategyClass']; + } + } }