Browse Source

Merge pull request #14986 from bancer/3.x-memcached-servers

Throw an exception when wrong cache config detected
Mark Story 5 years ago
parent
commit
04d6ee98ab

+ 19 - 1
src/Cache/Engine/MemcachedEngine.php

@@ -145,7 +145,25 @@ class MemcachedEngine extends CacheEngine
         }
         $this->_setOptions();
 
-        if (count($this->_Memcached->getServerList())) {
+        $serverList = $this->_Memcached->getServerList();
+        if (count($serverList)) {
+            if ($this->_config['persistent'] !== false) {
+                $actualServers = [];
+                foreach ($serverList as $server) {
+                    $actualServers[] = $server['host'] . ':' . $server['port'];
+                }
+                unset($server);
+                sort($actualServers);
+                $configuredServers = $this->_config['servers'];
+                sort($configuredServers);
+                if ($actualServers !== $configuredServers) {
+                    $message = "Invalid cache configuration. Multiple persistent cache configurations are detected" .
+                        " with different 'servers' values. 'servers' values for persistent cache configurations" .
+                        " must be the same when using the same persistence id.";
+                    throw new InvalidArgumentException($message);
+                }
+            }
+
             return true;
         }
 

+ 26 - 0
tests/TestCase/Cache/Engine/MemcachedEngineTest.php

@@ -361,6 +361,32 @@ class MemcachedEngineTest extends TestCase
     }
 
     /**
+     * testConfigDifferentPorts method
+     *
+     * @expectedException InvalidArgumentException
+     * @expectedExceptionMessage Invalid cache configuration. Multiple persistent cache configurations are detected with different 'servers' values. 'servers' values for persistent cache configurations must be the same when using the same persistence id.
+     * @return void
+     */
+    public function testConfigDifferentPorts()
+    {
+        $Memcached1 = new MemcachedEngine();
+        $config1 = [
+            'className' => 'Memcached',
+            'servers' => ['127.0.0.1:11211'],
+            'persistent' => true,
+        ];
+        $Memcached1->init($config1);
+
+        $Memcached2 = new MemcachedEngine();
+        $config2 = [
+            'className' => 'Memcached',
+            'servers' => ['127.0.0.1:11212'],
+            'persistent' => true,
+        ];
+        $Memcached2->init($config2);
+    }
+
+    /**
      * testConfig method
      *
      * @return void