Просмотр файла vendor/symfony/cache/Adapter/MemcachedAdapter.php

Размер файла: 13.55Kb
  1. <?php
  2.  
  3. /*
  4. * This file is part of the Symfony package.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11.  
  12. namespace Symfony\Component\Cache\Adapter;
  13.  
  14. use Symfony\Component\Cache\Exception\CacheException;
  15. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  16. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  17. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  18.  
  19. /**
  20. * @author Rob Frawley 2nd <rmf@src.run>
  21. * @author Nicolas Grekas <p@tchwork.com>
  22. */
  23. class MemcachedAdapter extends AbstractAdapter
  24. {
  25. /**
  26. * We are replacing characters that are illegal in Memcached keys with reserved characters from
  27. * {@see \Symfony\Contracts\Cache\ItemInterface::RESERVED_CHARACTERS} that are legal in Memcached.
  28. * Note: don’t use {@see \Symfony\Component\Cache\Adapter\AbstractAdapter::NS_SEPARATOR}.
  29. */
  30. private const RESERVED_MEMCACHED = " \n\r\t\v\f\0";
  31. private const RESERVED_PSR6 = '@()\{}/';
  32.  
  33. protected $maxIdLength = 250;
  34.  
  35. private const DEFAULT_CLIENT_OPTIONS = [
  36. 'persistent_id' => null,
  37. 'username' => null,
  38. 'password' => null,
  39. \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP,
  40. ];
  41.  
  42. private $marshaller;
  43. private $client;
  44. private $lazyClient;
  45.  
  46. /**
  47. * Using a MemcachedAdapter with a TagAwareAdapter for storing tags is discouraged.
  48. * Using a RedisAdapter is recommended instead. If you cannot do otherwise, be aware that:
  49. * - the Memcached::OPT_BINARY_PROTOCOL must be enabled
  50. * (that's the default when using MemcachedAdapter::createConnection());
  51. * - tags eviction by Memcached's LRU algorithm will break by-tags invalidation;
  52. * your Memcached memory should be large enough to never trigger LRU.
  53. *
  54. * Using a MemcachedAdapter as a pure items store is fine.
  55. */
  56. public function __construct(\Memcached $client, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
  57. {
  58. if (!static::isSupported()) {
  59. throw new CacheException('Memcached '.(\PHP_VERSION_ID >= 80100 ? '> 3.1.5' : '>= 2.2.0').' is required.');
  60. }
  61. if ('Memcached' === \get_class($client)) {
  62. $opt = $client->getOption(\Memcached::OPT_SERIALIZER);
  63. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  64. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  65. }
  66. $this->maxIdLength -= \strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
  67. $this->client = $client;
  68. } else {
  69. $this->lazyClient = $client;
  70. }
  71.  
  72. parent::__construct($namespace, $defaultLifetime);
  73. $this->enableVersioning();
  74. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  75. }
  76.  
  77. public static function isSupported()
  78. {
  79. return \extension_loaded('memcached') && version_compare(phpversion('memcached'), \PHP_VERSION_ID >= 80100 ? '3.1.6' : '2.2.0', '>=');
  80. }
  81.  
  82. /**
  83. * Creates a Memcached instance.
  84. *
  85. * By default, the binary protocol, no block, and libketama compatible options are enabled.
  86. *
  87. * Examples for servers:
  88. * - 'memcached://user:pass@localhost?weight=33'
  89. * - [['localhost', 11211, 33]]
  90. *
  91. * @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs
  92. *
  93. * @throws \ErrorException When invalid options or servers are provided
  94. */
  95. public static function createConnection(array|string $servers, array $options = []): \Memcached
  96. {
  97. if (\is_string($servers)) {
  98. $servers = [$servers];
  99. } elseif (!\is_array($servers)) {
  100. throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, "%s" given.', get_debug_type($servers)));
  101. }
  102. if (!static::isSupported()) {
  103. throw new CacheException('Memcached '.(\PHP_VERSION_ID >= 80100 ? '> 3.1.5' : '>= 2.2.0').' is required.');
  104. }
  105. set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
  106. try {
  107. $options += static::DEFAULT_CLIENT_OPTIONS;
  108. $client = new \Memcached($options['persistent_id']);
  109. $username = $options['username'];
  110. $password = $options['password'];
  111.  
  112. // parse any DSN in $servers
  113. foreach ($servers as $i => $dsn) {
  114. if (\is_array($dsn)) {
  115. continue;
  116. }
  117. if (!str_starts_with($dsn, 'memcached:')) {
  118. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s" does not start with "memcached:".', $dsn));
  119. }
  120. $params = preg_replace_callback('#^memcached:(//)?(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
  121. if (!empty($m[2])) {
  122. [$username, $password] = explode(':', $m[2], 2) + [1 => null];
  123. }
  124.  
  125. return 'file:'.($m[1] ?? '');
  126. }, $dsn);
  127. if (false === $params = parse_url($params)) {
  128. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn));
  129. }
  130. $query = $hosts = [];
  131. if (isset($params['query'])) {
  132. parse_str($params['query'], $query);
  133.  
  134. if (isset($query['host'])) {
  135. if (!\is_array($hosts = $query['host'])) {
  136. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn));
  137. }
  138. foreach ($hosts as $host => $weight) {
  139. if (false === $port = strrpos($host, ':')) {
  140. $hosts[$host] = [$host, 11211, (int) $weight];
  141. } else {
  142. $hosts[$host] = [substr($host, 0, $port), (int) substr($host, 1 + $port), (int) $weight];
  143. }
  144. }
  145. $hosts = array_values($hosts);
  146. unset($query['host']);
  147. }
  148. if ($hosts && !isset($params['host']) && !isset($params['path'])) {
  149. unset($servers[$i]);
  150. $servers = array_merge($servers, $hosts);
  151. continue;
  152. }
  153. }
  154. if (!isset($params['host']) && !isset($params['path'])) {
  155. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: "%s".', $dsn));
  156. }
  157. if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  158. $params['weight'] = $m[1];
  159. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  160. }
  161. $params += [
  162. 'host' => $params['host'] ?? $params['path'],
  163. 'port' => isset($params['host']) ? 11211 : null,
  164. 'weight' => 0,
  165. ];
  166. if ($query) {
  167. $params += $query;
  168. $options = $query + $options;
  169. }
  170.  
  171. $servers[$i] = [$params['host'], $params['port'], $params['weight']];
  172.  
  173. if ($hosts) {
  174. $servers = array_merge($servers, $hosts);
  175. }
  176. }
  177.  
  178. // set client's options
  179. unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']);
  180. $options = array_change_key_case($options, \CASE_UPPER);
  181. $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  182. $client->setOption(\Memcached::OPT_NO_BLOCK, true);
  183. $client->setOption(\Memcached::OPT_TCP_NODELAY, true);
  184. if (!\array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !\array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
  185. $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  186. }
  187. foreach ($options as $name => $value) {
  188. if (\is_int($name)) {
  189. continue;
  190. }
  191. if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
  192. $value = \constant('Memcached::'.$name.'_'.strtoupper($value));
  193. }
  194. unset($options[$name]);
  195.  
  196. if (\defined('Memcached::OPT_'.$name)) {
  197. $options[\constant('Memcached::OPT_'.$name)] = $value;
  198. }
  199. }
  200. $client->setOptions($options);
  201.  
  202. // set client's servers, taking care of persistent connections
  203. if (!$client->isPristine()) {
  204. $oldServers = [];
  205. foreach ($client->getServerList() as $server) {
  206. $oldServers[] = [$server['host'], $server['port']];
  207. }
  208.  
  209. $newServers = [];
  210. foreach ($servers as $server) {
  211. if (1 < \count($server)) {
  212. $server = array_values($server);
  213. unset($server[2]);
  214. $server[1] = (int) $server[1];
  215. }
  216. $newServers[] = $server;
  217. }
  218.  
  219. if ($oldServers !== $newServers) {
  220. $client->resetServerList();
  221. $client->addServers($servers);
  222. }
  223. } else {
  224. $client->addServers($servers);
  225. }
  226.  
  227. if (null !== $username || null !== $password) {
  228. if (!method_exists($client, 'setSaslAuthData')) {
  229. trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.');
  230. }
  231. $client->setSaslAuthData($username, $password);
  232. }
  233.  
  234. return $client;
  235. } finally {
  236. restore_error_handler();
  237. }
  238. }
  239.  
  240. /**
  241. * {@inheritdoc}
  242. */
  243. protected function doSave(array $values, int $lifetime): array|bool
  244. {
  245. if (!$values = $this->marshaller->marshall($values, $failed)) {
  246. return $failed;
  247. }
  248.  
  249. if ($lifetime && $lifetime > 30 * 86400) {
  250. $lifetime += time();
  251. }
  252.  
  253. $encodedValues = [];
  254. foreach ($values as $key => $value) {
  255. $encodedValues[self::encodeKey($key)] = $value;
  256. }
  257.  
  258. return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime)) ? $failed : false;
  259. }
  260.  
  261. /**
  262. * {@inheritdoc}
  263. */
  264. protected function doFetch(array $ids): iterable
  265. {
  266. try {
  267. $encodedIds = array_map([__CLASS__, 'encodeKey'], $ids);
  268.  
  269. $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds));
  270.  
  271. $result = [];
  272. foreach ($encodedResult as $key => $value) {
  273. $result[self::decodeKey($key)] = $this->marshaller->unmarshall($value);
  274. }
  275.  
  276. return $result;
  277. } catch (\Error $e) {
  278. throw new \ErrorException($e->getMessage(), $e->getCode(), \E_ERROR, $e->getFile(), $e->getLine());
  279. }
  280. }
  281.  
  282. /**
  283. * {@inheritdoc}
  284. */
  285. protected function doHave(string $id): bool
  286. {
  287. return false !== $this->getClient()->get(self::encodeKey($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
  288. }
  289.  
  290. /**
  291. * {@inheritdoc}
  292. */
  293. protected function doDelete(array $ids): bool
  294. {
  295. $ok = true;
  296. $encodedIds = array_map([__CLASS__, 'encodeKey'], $ids);
  297. foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) {
  298. if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) {
  299. $ok = false;
  300. }
  301. }
  302.  
  303. return $ok;
  304. }
  305.  
  306. /**
  307. * {@inheritdoc}
  308. */
  309. protected function doClear(string $namespace): bool
  310. {
  311. return '' === $namespace && $this->getClient()->flush();
  312. }
  313.  
  314. private function checkResultCode(mixed $result)
  315. {
  316. $code = $this->client->getResultCode();
  317.  
  318. if (\Memcached::RES_SUCCESS === $code || \Memcached::RES_NOTFOUND === $code) {
  319. return $result;
  320. }
  321.  
  322. throw new CacheException('MemcachedAdapter client error: '.strtolower($this->client->getResultMessage()));
  323. }
  324.  
  325. private function getClient(): \Memcached
  326. {
  327. if (isset($this->client)) {
  328. return $this->client;
  329. }
  330.  
  331. $opt = $this->lazyClient->getOption(\Memcached::OPT_SERIALIZER);
  332. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  333. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  334. }
  335. if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) {
  336. throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
  337. }
  338.  
  339. return $this->client = $this->lazyClient;
  340. }
  341.  
  342. private static function encodeKey(string $key): string
  343. {
  344. return strtr($key, self::RESERVED_MEMCACHED, self::RESERVED_PSR6);
  345. }
  346.  
  347. private static function decodeKey(string $key): string
  348. {
  349. return strtr($key, self::RESERVED_PSR6, self::RESERVED_MEMCACHED);
  350. }
  351. }