Skip to content
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

Allow setting serializer for Redis client #297

Closed
wants to merge 2 commits 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
Diff view
1 change: 1 addition & 0 deletions DependencyInjection/Configuration/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ private function addClientsSection(ArrayNodeDefinition $rootNode)
->scalarNode('read_write_timeout')->defaultNull()->end()
->booleanNode('iterable_multibulk')->defaultFalse()->end()
->booleanNode('throw_errors')->defaultTrue()->end()
->scalarNode('serialization')->defaultValue("default")->end()
->scalarNode('profile')->defaultValue('default')
->beforeNormalization()
->ifTrue(function($v) { return false === is_string($v); })
Expand Down
90 changes: 76 additions & 14 deletions DependencyInjection/SncRedisExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@
namespace Snc\RedisBundle\DependencyInjection;

use Snc\RedisBundle\DependencyInjection\Configuration\Configuration;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

/**
* SncRedisExtension
Expand Down Expand Up @@ -60,7 +59,12 @@ public function load(array $configs, ContainerBuilder $container)

if (isset($config['monolog'])) {
if (!empty($config['clients'][$config['monolog']['client']]['logging'])) {
throw new InvalidConfigurationException(sprintf('You have to disable logging for the client "%s" that you have configured under "snc_redis.monolog.client"', $config['monolog']['client']));
throw new InvalidConfigurationException(
sprintf(
'You have to disable logging for the client "%s" that you have configured under "snc_redis.monolog.client"',
$config['monolog']['client']
)
);
}
$this->loadMonolog($config, $container);
}
Expand Down Expand Up @@ -155,7 +159,9 @@ protected function loadPredisClient(array $client, ContainerBuilder $container)

// TODO can be shared between clients?!
$profileId = sprintf('snc_redis.client.%s_profile', $client['alias']);
$profileDef = new Definition(get_class(\Predis\Profile\Factory::get($client['options']['profile']))); // TODO get_class alternative?
$profileDef = new Definition(
get_class(\Predis\Profile\Factory::get($client['options']['profile']))
); // TODO get_class alternative?
$profileDef->setPublic(false);
if (null !== $client['options']['prefix']) {
$processorId = sprintf('snc_redis.client.%s_processor', $client['alias']);
Expand All @@ -175,17 +181,24 @@ protected function loadPredisClient(array $client, ContainerBuilder $container)
$clientDef = new Definition($container->getParameter('snc_redis.client.class'));
$clientDef->addTag('snc_redis.client', array('alias' => $client['alias']));
if (1 === $connectionCount) {
$clientDef->addArgument(new Reference(sprintf('snc_redis.connection.%s_parameters.%s', $connectionAliases[0], $client['alias'])));
$clientDef->addArgument(
new Reference(sprintf('snc_redis.connection.%s_parameters.%s', $connectionAliases[0], $client['alias']))
);
} else {
$connections = array();
foreach ($connectionAliases as $alias) {
$connections[] = new Reference(sprintf('snc_redis.connection.%s_parameters.%s', $alias, $client['alias']));
$connections[] = new Reference(
sprintf('snc_redis.connection.%s_parameters.%s', $alias, $client['alias'])
);
}
$clientDef->addArgument($connections);
}
$clientDef->addArgument(new Reference($optionId));
$container->setDefinition(sprintf('snc_redis.%s', $client['alias']), $clientDef);
$container->setAlias(sprintf('snc_redis.%s_client', $client['alias']), sprintf('snc_redis.%s', $client['alias']));
$container->setAlias(
sprintf('snc_redis.%s_client', $client['alias']),
sprintf('snc_redis.%s', $client['alias'])
);
}

/**
Expand Down Expand Up @@ -221,7 +234,8 @@ protected function loadPhpredisClient(array $client, ContainerBuilder $container
throw new \RuntimeException('Support for RedisArray is not yet implemented.');
}

$dsn = $client['dsns'][0]; /** @var \Snc\RedisBundle\DependencyInjection\Configuration\RedisDsn $dsn */
$dsn = $client['dsns'][0];
/** @var \Snc\RedisBundle\DependencyInjection\Configuration\RedisDsn $dsn */
$phpredisId = sprintf('snc_redis.phpredis.%s', $client['alias']);

$phpredisDef = new Definition($container->getParameter('snc_redis.phpredis_client.class'));
Expand Down Expand Up @@ -256,6 +270,12 @@ protected function loadPhpredisClient(array $client, ContainerBuilder $container
if (null !== $dsn->getDatabase()) {
$phpredisDef->addMethodCall('select', array($dsn->getDatabase()));
}
if ($client['options']['serialization']) {
$phpredisDef->addMethodCall(
'setOption',
array(\Redis::OPT_SERIALIZER, $this->loadSerializationType($client['options']['serialization']))
);
}
$container->setDefinition($phpredisId, $phpredisDef);

$container->setAlias(sprintf('snc_redis.%s', $client['alias']), $phpredisId);
Expand Down Expand Up @@ -357,10 +377,12 @@ protected function loadMonolog(array $config, ContainerBuilder $container)
$ref = new Reference(sprintf('snc_redis.%s', $config['monolog']['client']));
}

$def = new Definition($container->getParameter('snc_redis.monolog_handler.class'), array(
$ref,
$config['monolog']['key']
));
$def = new Definition(
$container->getParameter('snc_redis.monolog_handler.class'), array(
$ref,
$config['monolog']['key']
)
);

$def->setPublic(false);
if (!empty($config['monolog']['formatter'])) {
Expand All @@ -379,12 +401,52 @@ protected function loadSwiftMailer(array $config, ContainerBuilder $container)
{
$def = new Definition($container->getParameter('snc_redis.swiftmailer_spool.class'));
$def->setPublic(false);
$def->addMethodCall('setRedis', array(new Reference(sprintf('snc_redis.%s', $config['swiftmailer']['client']))));
$def->addMethodCall(
'setRedis',
array(new Reference(sprintf('snc_redis.%s', $config['swiftmailer']['client'])))
);
$def->addMethodCall('setKey', array($config['swiftmailer']['key']));
$container->setDefinition('snc_redis.swiftmailer.spool', $def);
$container->setAlias('swiftmailer.spool.redis', 'snc_redis.swiftmailer.spool');
}

/**
* Load the correct serializer for Redis
*
* @param string $type
*
* @return string
* @throws InvalidConfigurationException
*/
public function loadSerializationType($type)
{
// not using constants, because it would fail if phpredis extension is not enabled
$types = array(
"none" => 0, // \Redis::SERIALIZER_NONE,
"php" => 1, // \Redis::SERIALIZER_PHP,
"igbinary" => 2 // \Redis::SERIALIZER_IGBINARY
);

// allow user to pass in default serialization in which case we should automatically decide for them
if ('default' == $type) {
if (defined('HHVM_VERSION')) {
return $types['php'];
}

return defined('Redis::SERIALIZER_IGBINARY') ? $types['igbinary'] : $types['php'];
} elseif (array_key_exists($type, $types)) {
return $types[$type];
}

throw new InvalidConfigurationException(
sprintf(
'%s in not a valid serializer. Valid serializers: %s',
$type,
implode(", ", array_keys($types))
)
);
}

public function getConfiguration(array $config, ContainerBuilder $container)
{
return new Configuration($container->getParameter('kernel.debug'));
Expand Down
10 changes: 10 additions & 0 deletions Resources/config/schema/redis-1.0.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,22 @@
<xsd:attribute name="read-write-timeout" type="xsd:int" />
<xsd:attribute name="iterable-multibulk" type="xsd:boolean" />
<xsd:attribute name="throw-errors" type="xsd:boolean" />
<xsd:attribute name="serialization" type="phpredis-serialization-type" />
<xsd:attribute name="profile" type="client-profile" />
<xsd:attribute name="cluster" type="xsd:string" />
<xsd:attribute name="prefix" type="xsd:string" />
<xsd:attribute name="replication" type="xsd:boolean" />
</xsd:complexType>

<xsd:simpleType name="phpredis-serialization-type">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="default" />
<xsd:enumeration value="none" />
<xsd:enumeration value="php" />
<xsd:enumeration value="igbinary" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="client-profile">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="1.2" />
Expand Down
47 changes: 47 additions & 0 deletions Tests/DependencyInjection/SncRedisExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,13 +309,60 @@ public function testClientReplicationOption()
$this->assertEquals(array('snc_redis.default' => array(array('alias' => 'default'))), $container->findTaggedServiceIds('snc_redis.client'));
}

/**
* Test valid config of the serialization option
*/
public function testClientSerializationOption()
{
$extension = new SncRedisExtension();
$config = $this->parseYaml($this->getSerializationYamlConfig());
$extension->load(array($config), $container = $this->getContainer());
$options = $container->getDefinition('snc_redis.client.default_options')->getArgument(0);
$parameters = $container->getDefinition('snc_redis.default')->getArgument(0);
$masterParameters = $container->getDefinition((string) $parameters[0])->getArgument(0);
$this->assertSame($options['serialization'], $masterParameters['serialization']);
}

public function testLoadSerializationType()
{
$extension = new SncRedisExtension();
$config = $this->parseYaml($this->getSerializationYamlConfig());
$extension->load(array($config), $container = $this->getContainer());
$options = $container->getDefinition('snc_redis.client.default_options')->getArgument(0);
$serializationType = $extension->loadSerializationType($options['serialization']);
$this->assertTrue(is_integer($serializationType));

if (defined('HHVM_VERSION')) {
$defaultType = 1;
} else {
$defaultType = defined('Redis::SERIALIZER_IGBINARY') ? 2 : 1;
}

$this->assertEquals($defaultType, $serializationType);
}

private function parseYaml($yaml)
{
$parser = new Parser();

return $parser->parse($yaml);
}

private function getSerializationYamlConfig()
{
return <<<'EOF'
clients:
default:
type: predis
alias: default
dsn:
- redis://localhost?alias=master
- redis://otherhost
options:
serialization: "default"
EOF;
}

private function getMinimalYamlConfig()
{
return <<<'EOF'
Expand Down