8000 [Cache] Allow to configure serializator for cache instances. by palex-fpt · Pull Request #27484 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Cache] Allow to configure serializator for cache 8000 instances. #27484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
8000
Diff view
29 changes: 12 additions & 17 deletions src/Symfony/Component/Cache/Adapter/ArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Psr\Log\LoggerAwareInterface;
use Symfony\Component\Cache\CacheInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Serializer\IdentitySerializer;
use Symfony\Component\Cache\Serializer\PhpSerializer;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ArrayTrait;
use Symfony\Component\Cache\Traits\GetTrait;
Expand All @@ -35,7 +37,7 @@ class ArrayAdapter implements AdapterInterface, CacheInterface, LoggerAwareInter
*/
public function __construct(int $defaultLifetime = 0, bool $storeSerialized = true)
{
$this->storeSerialized = $storeSerialized;
$this->setSerializer($storeSerialized ? new PhpSerializer() : new IdentitySerializer());
$this->createCacheItem = \Closure::bind(
function ($key, $value, $isHit) use ($defaultLifetime) {
$item = new CacheItem();
Expand All @@ -60,13 +62,8 @@ public function getItem($key)
try {
if (!$isHit) {
$this->values[$key] = $value = null;
} elseif (!$this->storeSerialized) {
$value = $this->values[$key];
} elseif ('b:0;' === $value = $this->values[$key]) {
$value = false;
} elseif (false === $value = unserialize($value)) {
$this->values[$key] = $value = null;
$isHit = false;
} else {
$value = $this->unserialize($this->values[$key]);
}
} catch (\Exception $e) {
CacheItem::log($this->logger, 'Failed to unserialize key "{key}"', array('key' => $key, 'exception' => $e));
Expand Down Expand Up @@ -120,15 +117,13 @@ public function save(CacheItemInterface $item)

return true;
}
if ($this->storeSerialized) {
try {
$value = serialize($value);
} catch (\Exception $e) {
$type = is_object($value) ? get_class($value) : gettype($value);
CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e));

return false;
}
try {
$value = $this->serialize($value);
} catch (\Exception $e) {
$type = is_object($value) ? get_class($value) : gettype($value);
CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e));

return false;
}
if (null === $expiry && 0 < $item["\0*\0defaultLifetime"]) {
$expiry = microtime(true) + $item["\0*\0defaultLifetime"];
Expand Down
27 changes: 27 additions & 0 deletions src/Symfony/Component/Cache/Serializer/IdentitySerializer.php
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Serializer;

use Symfony\Component\Cache\SerializerInterface;

class IdentitySerializer implements SerializerInterface
{
public function serialize($data)
{
return $data;
}

public function unserialize($serialized)
{
return $serialized;
}
}
43 changes: 43 additions & 0 deletions src/Symfony/Component/Cache/Serializer/IgbinarySerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Serializer;

use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\SerializerInterface;

class IgbinarySerializer implements SerializerInterface
{
public function serialize($data)
{
return igbinary_serialize($data);
}

public function unserialize($serialized)
{
$unserializeCallbackHandler = ini_set(
'unserialize_callback_func',
PhpSerializer::class.'::handleUnserializeCallback'
);
try {
$value = igbinary_unserialize($serialized);
if (false === $value && igbinary_serialize(false) !== $serialized) {
throw new CacheException('failed to unserialize value');
}

return $value;
} catch (\Error $e) {
throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
} finally {
ini_set('unserialize_callback_func', $unserializeCallbackHandler);
}
}
}
49 changes: 49 additions & 0 deletions src/Symfony/Component/Cache/Serializer/PhpSerializer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Serializer;

use Symfony\Component\Cache\Exception\CacheException;
use Symfony\Component\Cache\SerializerInterface;

class PhpSerializer implements SerializerInterface
{
public function serialize($data)
{
return serialize($data);
}

public function unserialize($serialized)
{
$unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
try {
if ('b:0;' === $serialized) {
return false;
} elseif (false === $value = unserialize($serialized)) {
throw new CacheException('failed to unserialize value');
}

return $value;
} catch (\Error $e) {
throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
} finally {
ini_set('unserialize_callback_func', $unserializeCallbackHandler);
}
}

/**
* @internal
*/
public static function handleUnserializeCallback($class)
{
throw new \DomainException('Class not found: '.$class);
}
}
40 changes: 40 additions & 0 deletions src/Symfony/Component/Cache/SerializerInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache;

use Symfony\Component\Cache\Exception\InvalidArgumentException;

/**
* @author Alexei Prilipko <palex.fpt@gmail.com>
*/
interface SerializerInterface
{
/**
* Generates a storable representation of a value.
*
* @param $data mixed
*
* @return string|mixed serialized value
*
* @throws InvalidArgumentException when $data can not be serialized
*/
public function serialize($data);

/**
* Creates a PHP value from a stored representation.
*
* @param string|mixed $serialized the serialized string
*
* @return mixed Original value
*/
public function unserialize($serialized);
}
22 changes: 11 additions & 11 deletions src/Symfony/Component/Cache/Simple/ArrayCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\Exception\InvalidArgumentException;
use Symfony\Component\Cache\Serializer\IdentitySerializer;
use Symfony\Component\Cache\Serializer\PhpSerializer;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ArrayTrait;

Expand All @@ -37,7 +39,7 @@ class ArrayCache implements CacheInterface, LoggerAwareInterface, ResettableInte
public function __construct(int $defaultLifetime = 0, bool $storeSerialized = true)
{
$this->defaultLifetime = $defaultLifetime;
$this->storeSerialized = $storeSerialized;
$this->setSerializer($storeSerialized ? new PhpSerializer() : new IdentitySerializer());
}

/**
Expand Down Expand Up @@ -109,16 +111,14 @@ public function setMultiple($values, $ttl = null)
if (false === $ttl = $this->normalizeTtl($ttl)) {
return $this->deleteMultiple(array_keys($valuesArray));
}
if ($this->storeSerialized) {
foreach ($valuesArray as $key => $value) {
try {
$valuesArray[$key] = serialize($value);
} catch (\Exception $e) {
$type = is_object($value) ? get_class($value) : gettype($value);
CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e));

return false;
}
foreach ($valuesArray as $key => $value) {
try {
$valuesArray[$key] = $this->serialize($value);
} catch (\Exception $e) {
$type = is_object($value) ? get_class($value) : gettype($value);
CacheItem::log($this->logger, 'Failed to save key "{key}" ({type})', array('key' => $key, 'type' => $type, 'exception' => $e));

return false;
}
}
$expiry = 0 < $ttl ? microtime(true) + $ttl : PHP_INT_MAX;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Tests\Serializer;

use Symfony\Component\Cache\Serializer\IgbinarySerializer;
use Symfony\Component\Cache\SerializerInterface;

class IgbinarySerializerTest extends SerializerTest
{
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
if (!extension_loaded('igbinary')) {
self::markTestSkipped('Extension igbinary is not loaded.');
}
}

protected function createSerializer(): SerializerInterface
{
return new IgbinarySerializer();
}
}
23 changes: 23 additions & 0 deletions src/Symfony/Component/Cache/Tests/Serializer/PhpSerializerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Tests\Serializer;

use Symfony\Component\Cache\Serializer\PhpSerializer;
use Symfony\Component\Cache\SerializerInterface;

class PhpSerializerTest extends SerializerTest
{
protected function createSerializer(): SerializerInterface
{
return new PhpSerializer();
}
}
72 changes: 72 additions & 0 deletions src/Symfony/Component/Cache/Tests/Serializer/SerializerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Cache\Tests\Serializer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\SerializerInterface;

abstract class SerializerTest extends TestCase
{
/** @var SerializerInterface */
private $serializer;

protected function setUp()
{
parent::setUp();

$this->serializer = $this->createSerializer();
}

abstract protected function createSerializer(): SerializerInterface;

/**
* @dataProvider validData
*/
public function testSerializeInvariants($value)
{
$serialized = $this->serializer->serialize($value);
$restored = $this->serializer->unserialize($serialized);
$this->assertEquals($value, $restored);
}

/**
* Data provider for valid data to store.
*
* @return array
*/
public static function validData()
{
return array(
array(false),
array('AbC19_.'),
array(4711),
array(47.11),
array(true),
array(null),
array(array('key' => 'value')),
array(new \stdClass()),
);
}
}

class NotUnserializable implements \Serializable
{
public function serialize()
{
return serialize(123);
}

public function unserialize($ser)
{
throw new \Exception(__CLASS__);
}
}
Loading
0