Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 537c496

Browse filesBrowse files
committed
minor #24366 [Lock] Use cache connection factories in lock (jderusse)
This PR was merged into the 3.4 branch. Discussion ---------- [Lock] Use cache connection factories in lock | Q | A | ------------- | --- | Branch? | 3.4 | Bug fix? | no | New feature? | no (feature removal) | BC breaks? | no (if merged in 3.4) | Deprecations? | no | Tests pass? | yes | Fixed tickets | | License | MIT | Doc PR | An alternative to #24267 to share code between cache and lock. Commits ------- 95358ac Share connection factories between cache and lock
2 parents c7f664c + 95358ac commit 537c496
Copy full SHA for 537c496

File tree

5 files changed

+2
-316
lines changed
Filter options

5 files changed

+2
-316
lines changed

‎src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
2424
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
2525
use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader;
26+
use Symfony\Component\Cache\Adapter\AbstractAdapter;
2627
use Symfony\Component\Cache\Adapter\AdapterInterface;
2728
use Symfony\Component\Cache\Adapter\ArrayAdapter;
2829
use Symfony\Component\Cache\ResettableInterface;
@@ -1706,7 +1707,7 @@ private function registerLockConfiguration(array $config, ContainerBuilder $cont
17061707
if (!$container->hasDefinition($connectionDefinitionId = $container->hash($storeDsn))) {
17071708
$connectionDefinition = new Definition(\stdClass::class);
17081709
$connectionDefinition->setPublic(false);
1709-
$connectionDefinition->setFactory(array(StoreFactory::class, 'createConnection'));
1710+
$connectionDefinition->setFactory(array(AbstractAdapter::class, 'createConnection'));
17101711
$connectionDefinition->setArguments(array($storeDsn));
17111712
$container->setDefinition($connectionDefinitionId, $connectionDefinition);
17121713
}

‎src/Symfony/Component/Lock/Store/MemcachedStore.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Lock/Store/MemcachedStore.php
-122Lines changed: 0 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -58,128 +58,6 @@ public function __construct(\Memcached $memcached, $initialTtl = 300)
5858
$this->initialTtl = $initialTtl;
5959
}
6060

61-
/**
62-
* Creates a Memcached instance.
63-
*
64-
* By default, the binary protocol, block, and libketama compatible options are enabled.
65-
*
66-
* Example DSN:
67-
* - 'memcached://user:pass@localhost?weight=33'
68-
* - array(array('localhost', 11211, 33))
69-
*
70-
* @param string $dsn A server or A DSN
71-
* @param array $options An array of options
72-
*
73-
* @return \Memcached
74-
*
75-
* @throws \ErrorEception When invalid options or server are provided
76-
*/
77-
public static function createConnection($server, array $options = array())
78-
{
79-
if (!static::isSupported()) {
80-
throw new InvalidArgumentException('Memcached extension is required');
81-
}
82-
set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
83-
try {
84-
$options += static::$defaultClientOptions;
85-
$client = new \Memcached($options['persistent_id']);
86-
$username = $options['username'];
87-
$password = $options['password'];
88-
89-
// parse any DSN in $server
90-
if (is_string($server)) {
91-
if (0 !== strpos($server, 'memcached://')) {
92-
throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s does not start with "memcached://"', $server));
93-
}
94-
$params = preg_replace_callback('#^memcached://(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
95-
if (!empty($m[1])) {
96-
list($username, $password) = explode(':', $m[1], 2) + array(1 => null);
97-
}
98-
99-
return 'file://';
100-
}, $server);
101-
if (false === $params = parse_url($params)) {
102-
throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $server));
103-
}
104-
if (!isset($params['host']) && !isset($params['path'])) {
105-
throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $server));
106-
}
107-
if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
108-
$params['weight'] = $m[1];
109-
$params['path'] = substr($params['path'], 0, -strlen($m[0]));
110-
}
111-
$params += array(
112-
'host' => isset($params['host']) ? $params['host'] : $params['path'],
113-
'port' => isset($params['host']) ? 11211 : null,
114-
'weight' => 0,
115-
);
116-
if (isset($params['query'])) {
117-
parse_str($params['query'], $query);
118-
$params += $query;
119-
$options = $query + $options;
120-
}
121-
122-
$server = array($params['host'], $params['port'], $params['weight']);
123-
}
124-
125-
// set client's options
126-
unset($options['persistent_id'], $options['username'], $options['password'], $options['weight']);
127-
$options = array_change_key_case($options, CASE_UPPER);
128-
$client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
129-
$client->setOption(\Memcached::OPT_NO_BLOCK, false);
130-
if (!array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
131-
$client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
132-
}
133-
foreach ($options as $name => $value) {
134-
if (is_int($name)) {
135-
continue;
136-
}
137-
if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
138-
$value = constant('Memcached::'.$name.'_'.strtoupper($value));
139-
}
140-
$opt = constant('Memcached::OPT_'.$name);
141-
142-
unset($options[$name]);
143-
$options[$opt] = $value;
144-
}
145-
$client->setOptions($options);
146-
147-
// set client's servers, taking care of persistent connections
148-
if (!$client->isPristine()) {
149-
$oldServers = array();
150-
foreach ($client->getServerList() as $server) {
151-
$oldServers[] = array($server['host'], $server['port']);
152-
}
153-
154-
$newServers = array();
155-
if (1 < count($server)) {
156-
$server = array_values($server);
157-
unset($server[2]);
158-
$server[1] = (int) $server[1];
159-
}
160-
$newServers[] = $server;
161-
162-
if ($oldServers !== $newServers) {
163-
// before resetting, ensure $servers is valid
164-
$client->addServers(array($server));
165-
$client->resetServerList();
166-
}
167-
}
168-
$client->addServers(array($server));
169-
170-
if (null !== $username || null !== $password) {
171-
if (!method_exists($client, 'setSaslAuthData')) {
172-
trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.');
173-
}
174-
$client->setSaslAuthData($username, $password);
175-
}
176-
177-
return $client;
178-
} finally {
179-
restore_error_handler();
180-
}
181-
}
182-
18361
/**
18462
* {@inheritdoc}
18563
*/

‎src/Symfony/Component/Lock/Store/RedisStore.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Lock/Store/RedisStore.php
-82Lines changed: 0 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -53,88 +53,6 @@ public function __construct($redisClient, $initialTtl = 300.0)
5353
$this->initialTtl = $initialTtl;
5454
}
5555

56-
/**
57-
* Creates a Redis connection using a DSN configuration.
58-
*
59-
* Example DSN:
60-
* - redis://localhost
61-
* - redis://example.com:1234
62-
* - redis://secret@example.com/13
63-
* - redis:///var/run/redis.sock
64-
* - redis://secret@/var/run/redis.sock/13
65-
*
66-
* @param string $dsn
67-
* @param array $options See self::$defaultConnectionOptions
68-
*
69-
* @throws InvalidArgumentException When the DSN is invalid
70-
*
71-
* @return \Redis|\Predis\Client According to the "class" option
72-
*/
73-
public static function createConnection($dsn, array $options = array())
74-
{
75-
if (0 !== strpos($dsn, 'redis://')) {
76-
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s does not start with "redis://"', $dsn));
77-
}
78-
$params = preg_replace_callback('#^redis://(?:(?:[^:@]*+:)?([^@]*+)@)?#', function ($m) use (&$auth) {
79-
if (isset($m[1])) {
80-
$auth = $m[1];
81-
}
82-
83-
return 'file://';
84-
}, $dsn);
85-
if (false === $params = parse_url($params)) {
86-
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
87-
}
88-
if (!isset($params['host']) && !isset($params['path'])) {
89-
throw new InvalidArgumentException(sprintf('Invalid Redis DSN: %s', $dsn));
90-
}
91-
if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
92-
$params['dbindex'] = $m[1];
93-
$params['path'] = substr($params['path'], 0, -strlen($m[0]));
94-
}
95-
$params += array(
96-
'host' => isset($params['host']) ? $params['host'] : $params['path'],
97-
'port' => isset($params['host']) ? 6379 : null,
98-
'dbindex' => 0,
99-
);
100-
if (isset($params['query'])) {
101-
parse_str($params['query'], $query);
102-
$params += $query;
103-
}
104-
$params += $options + self::$defaultConnectionOptions;
105-
$class = null === $params['class'] ? (extension_loaded('redis') ? \Redis::class : \Predis\Client::class) : $params['class'];
106-
107-
if (is_a($class, \Redis::class, true)) {
108-
$connect = $params['persistent'] || $params['persistent_id'] ? 'pconnect' : 'connect';
109-
$redis = new $class();
110-
@$redis->{$connect}($params['host'], $params['port'], $params['timeout'], $params['persistent_id'], $params['retry_interval']);
111-
112-
if (@!$redis->isConnected()) {
113-
$e = ($e = error_get_last()) && preg_match('/^Redis::p?connect\(\): (.*)/', $e['message'], $e) ? sprintf(' (%s)', $e[1]) : '';
114-
throw new InvalidArgumentException(sprintf('Redis connection failed%s: %s', $e, $dsn));
115-
}
116-
117-
if ((null !== $auth && !$redis->auth($auth))
118-
|| ($params['dbindex'] && !$redis->select($params['dbindex']))
119-
|| ($params['read_timeout'] && !$redis->setOption(\Redis::OPT_READ_TIMEOUT, $params['read_timeout']))
120-
) {
121-
$e = preg_replace('/^ERR /', '', $redis->getLastError());
122-
throw new InvalidArgumentException(sprintf('Redis connection failed (%s): %s', $e, $dsn));
123-
}
124-
} elseif (is_a($class, \Predis\Client::class, true)) {
125-
$params['scheme'] = isset($params['host']) ? 'tcp' : 'unix';
126-
$params['database'] = $params['dbindex'] ?: null;
127-
$params['password'] = $auth;
128-
$redis = new $class((new Factory())->create($params));
129-
} elseif (class_exists($class, false)) {
130-
throw new InvalidArgumentException(sprintf('"%s" is not a subclass of "Redis" or "Predis\Client"', $class));
131-
} else {
132-
throw new InvalidArgumentException(sprintf('Class "%s" does not exist', $class));
133-
}
134-
135-
return $redis;
136-
}
137-
13856
/**
13957
* {@inheritdoc}
14058
*/

‎src/Symfony/Component/Lock/Store/StoreFactory.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Lock/Store/StoreFactory.php
-15Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,21 +20,6 @@
2020
*/
2121
class StoreFactory
2222
{
23-
public static function createConnection($dsn, array $options = array())
24-
{
25-
if (!is_string($dsn)) {
26-
throw new InvalidArgumentException(sprintf('The %s() method expects argument #1 to be string, %s given.', __METHOD__, gettype($dsn)));
27-
}
28-
if (0 === strpos($dsn, 'redis://')) {
29-
return RedisStore::createConnection($dsn, $options);
30-
}
31-
if (0 === strpos($dsn, 'memcached://')) {
32-
return MemcachedStore::createConnection($dsn, $options);
33-
}
34-
35-
throw new InvalidArgumentException(sprintf('Unsupported DSN: %s.', $dsn));
36-
}
37-
3823
/**
3924
* @param \Redis|\RedisArray|\RedisCluster|\Predis\Client|\Memcached $connection
4025
*

‎src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php
-96Lines changed: 0 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -54,100 +54,4 @@ public function testAbortAfterExpiration()
5454
{
5555
$this->markTestSkipped('Memcached expects a TTL greater than 1 sec. Simulating a slow network is too hard');
5656
}
57-
58-
public function testDefaultOptions()
59-
{
60-
$this->assertTrue(MemcachedStore::isSupported());
61-
62-
$client = MemcachedStore::createConnection('memcached://127.0.0.1');
63-
64-
$this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION));
65-
$this->assertSame(1, $client->getOption(\Memcached::OPT_BINARY_PROTOCOL));
66-
$this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE));
67-
}
68-
69-
/**
70-
* @dataProvider provideServersSetting
71-
*/
72-
public function testServersSetting($dsn, $host, $port)
73-
{
74-
$client1 = MemcachedStore::createConnection($dsn);
75-
$client3 = MemcachedStore::createConnection(array($host, $port));
76-
$expect = array(
77-
'host' => $host,
78-
'port' => $port,
79-
);
80-
81-
$f = function ($s) { return array('host' => $s['host'], 'port' => $s['port']); };
82-
$this->assertSame(array($expect), array_map($f, $client1->getServerList()));
83-
$this->assertSame(array($expect), array_map($f, $client3->getServerList()));
84-
}
85-
86-
public function provideServersSetting()
87-
{
88-
yield array(
89-
'memcached://127.0.0.1/50',
90-
'127.0.0.1',
91-
11211,
92-
);
93-
yield array(
94-
'memcached://localhost:11222?weight=25',
95-
'localhost',
96-
11222,
97-
);
98-
if (ini_get('memcached.use_sasl')) {
99-
yield array(
100-
'memcached://user:password@127.0.0.1?weight=50',
101-
'127.0.0.1',
102-
11211,
103-
);
104-
}
105-
yield array(
106-
'memcached:///var/run/memcached.sock?weight=25',
107-
'/var/run/memcached.sock',
108-
0,
109-
);
110-
yield array(
111-
'memcached:///var/local/run/memcached.socket?weight=25',
112-
'/var/local/run/memcached.socket',
113-
0,
114-
);
115-
if (ini_get('memcached.use_sasl')) {
116-
yield array(
117-
'memcached://user:password@/var/local/run/memcached.socket?weight=25',
118-
'/var/local/run/memcached.socket',
119-
0,
120-
);
121-
}
122-
}
123-
124-
/**
125-
* @dataProvider provideDsnWithOptions
126-
*/
127-
public function testDsnWithOptions($dsn, array $options, array $expectedOptions)
128-
{
129-
$client = MemcachedStore::createConnection($dsn, $options);
130-
131-
foreach ($expectedOptions as $option => $expect) {
132-
$this->assertSame($expect, $client->getOption($option));
133-
}
134-
}
135-
136-
public function provideDsnWithOptions()
137-
{
138-
if (!class_exists('\Memcached')) {
139-
self::markTestSkipped('Extension memcached required.');
140-
}
141-
142-
yield array(
143-
'memcached://localhost:11222?retry_timeout=10',
144-
array(\Memcached::OPT_RETRY_TIMEOUT => 8),
145-
array(\Memcached::OPT_RETRY_TIMEOUT => 10),
146-
);
147-
yield array(
148-
'memcached://localhost:11222?socket_recv_size=1&socket_send_size=2',
149-
array(\Memcached::OPT_RETRY_TIMEOUT => 8),
150-
array(\Memcached::OPT_SOCKET_RECV_SIZE => 1, \Memcached::OPT_SOCKET_SEND_SIZE => 2, \Memcached::OPT_RETRY_TIMEOUT => 8),
151-
);
152-
}
15357
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.