MemcachedTrait.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Traits;
  11. use Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. /**
  14. * @author Rob Frawley 2nd <rmf@src.run>
  15. * @author Nicolas Grekas <p@tchwork.com>
  16. *
  17. * @internal
  18. */
  19. trait MemcachedTrait
  20. {
  21. private static $defaultClientOptions = [
  22. 'persistent_id' => null,
  23. 'username' => null,
  24. 'password' => null,
  25. 'serializer' => 'php',
  26. ];
  27. private $client;
  28. private $lazyClient;
  29. public static function isSupported()
  30. {
  31. return \extension_loaded('memcached') && version_compare(phpversion('memcached'), '2.2.0', '>=');
  32. }
  33. private function init(\Memcached $client, $namespace, $defaultLifetime)
  34. {
  35. if (!static::isSupported()) {
  36. throw new CacheException('Memcached >= 2.2.0 is required');
  37. }
  38. if ('Memcached' === \get_class($client)) {
  39. $opt = $client->getOption(\Memcached::OPT_SERIALIZER);
  40. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  41. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  42. }
  43. $this->maxIdLength -= \strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
  44. $this->client = $client;
  45. } else {
  46. $this->lazyClient = $client;
  47. }
  48. parent::__construct($namespace, $defaultLifetime);
  49. $this->enableVersioning();
  50. }
  51. /**
  52. * Creates a Memcached instance.
  53. *
  54. * By default, the binary protocol, no block, and libketama compatible options are enabled.
  55. *
  56. * Examples for servers:
  57. * - 'memcached://user:pass@localhost?weight=33'
  58. * - [['localhost', 11211, 33]]
  59. *
  60. * @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs
  61. * @param array $options An array of options
  62. *
  63. * @return \Memcached
  64. *
  65. * @throws \ErrorException When invalid options or servers are provided
  66. */
  67. public static function createConnection($servers, array $options = [])
  68. {
  69. if (\is_string($servers)) {
  70. $servers = [$servers];
  71. } elseif (!\is_array($servers)) {
  72. throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, %s given.', \gettype($servers)));
  73. }
  74. if (!static::isSupported()) {
  75. throw new CacheException('Memcached >= 2.2.0 is required');
  76. }
  77. set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
  78. try {
  79. $options += static::$defaultClientOptions;
  80. $client = new \Memcached($options['persistent_id']);
  81. $username = $options['username'];
  82. $password = $options['password'];
  83. // parse any DSN in $servers
  84. foreach ($servers as $i => $dsn) {
  85. if (\is_array($dsn)) {
  86. continue;
  87. }
  88. if (0 !== strpos($dsn, 'memcached://')) {
  89. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s does not start with "memcached://"', $dsn));
  90. }
  91. $params = preg_replace_callback('#^memcached://(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
  92. if (!empty($m[1])) {
  93. list($username, $password) = explode(':', $m[1], 2) + [1 => null];
  94. }
  95. return 'file://';
  96. }, $dsn);
  97. if (false === $params = parse_url($params)) {
  98. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
  99. }
  100. if (!isset($params['host']) && !isset($params['path'])) {
  101. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
  102. }
  103. if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  104. $params['weight'] = $m[1];
  105. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  106. }
  107. $params += [
  108. 'host' => isset($params['host']) ? $params['host'] : $params['path'],
  109. 'port' => isset($params['host']) ? 11211 : null,
  110. 'weight' => 0,
  111. ];
  112. if (isset($params['query'])) {
  113. parse_str($params['query'], $query);
  114. $params += $query;
  115. $options = $query + $options;
  116. }
  117. $servers[$i] = [$params['host'], $params['port'], $params['weight']];
  118. }
  119. // set client's options
  120. unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']);
  121. $options = array_change_key_case($options, CASE_UPPER);
  122. $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  123. $client->setOption(\Memcached::OPT_NO_BLOCK, true);
  124. $client->setOption(\Memcached::OPT_TCP_NODELAY, true);
  125. if (!array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
  126. $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  127. }
  128. foreach ($options as $name => $value) {
  129. if (\is_int($name)) {
  130. continue;
  131. }
  132. if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
  133. $value = \constant('Memcached::'.$name.'_'.strtoupper($value));
  134. }
  135. $opt = \constant('Memcached::OPT_'.$name);
  136. unset($options[$name]);
  137. $options[$opt] = $value;
  138. }
  139. $client->setOptions($options);
  140. // set client's servers, taking care of persistent connections
  141. if (!$client->isPristine()) {
  142. $oldServers = [];
  143. foreach ($client->getServerList() as $server) {
  144. $oldServers[] = [$server['host'], $server['port']];
  145. }
  146. $newServers = [];
  147. foreach ($servers as $server) {
  148. if (1 < \count($server)) {
  149. $server = array_values($server);
  150. unset($server[2]);
  151. $server[1] = (int) $server[1];
  152. }
  153. $newServers[] = $server;
  154. }
  155. if ($oldServers !== $newServers) {
  156. $client->resetServerList();
  157. $client->addServers($servers);
  158. }
  159. } else {
  160. $client->addServers($servers);
  161. }
  162. if (null !== $username || null !== $password) {
  163. if (!method_exists($client, 'setSaslAuthData')) {
  164. trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.');
  165. }
  166. $client->setSaslAuthData($username, $password);
  167. }
  168. return $client;
  169. } finally {
  170. restore_error_handler();
  171. }
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. protected function doSave(array $values, $lifetime)
  177. {
  178. if ($lifetime && $lifetime > 30 * 86400) {
  179. $lifetime += time();
  180. }
  181. $encodedValues = [];
  182. foreach ($values as $key => $value) {
  183. $encodedValues[rawurlencode($key)] = $value;
  184. }
  185. return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime));
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. protected function doFetch(array $ids)
  191. {
  192. $unserializeCallbackHandler = ini_set('unserialize_callback_func', __CLASS__.'::handleUnserializeCallback');
  193. try {
  194. $encodedIds = array_map('rawurlencode', $ids);
  195. $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds));
  196. $result = [];
  197. foreach ($encodedResult as $key => $value) {
  198. $result[rawurldecode($key)] = $value;
  199. }
  200. return $result;
  201. } catch (\Error $e) {
  202. throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
  203. } finally {
  204. ini_set('unserialize_callback_func', $unserializeCallbackHandler);
  205. }
  206. }
  207. /**
  208. * {@inheritdoc}
  209. */
  210. protected function doHave($id)
  211. {
  212. return false !== $this->getClient()->get(rawurlencode($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
  213. }
  214. /**
  215. * {@inheritdoc}
  216. */
  217. protected function doDelete(array $ids)
  218. {
  219. $ok = true;
  220. $encodedIds = array_map('rawurlencode', $ids);
  221. foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) {
  222. if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) {
  223. $ok = false;
  224. }
  225. }
  226. return $ok;
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. protected function doClear($namespace)
  232. {
  233. return '' === $namespace && $this->getClient()->flush();
  234. }
  235. private function checkResultCode($result)
  236. {
  237. $code = $this->client->getResultCode();
  238. if (\Memcached::RES_SUCCESS === $code || \Memcached::RES_NOTFOUND === $code) {
  239. return $result;
  240. }
  241. throw new CacheException(sprintf('MemcachedAdapter client error: %s.', strtolower($this->client->getResultMessage())));
  242. }
  243. /**
  244. * @return \Memcached
  245. */
  246. private function getClient()
  247. {
  248. if ($this->client) {
  249. return $this->client;
  250. }
  251. $opt = $this->lazyClient->getOption(\Memcached::OPT_SERIALIZER);
  252. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  253. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  254. }
  255. if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) {
  256. throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
  257. }
  258. return $this->client = $this->lazyClient;
  259. }
  260. }