CouchbaseBucketAdapter.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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\Adapter;
  11. use Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  14. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  15. /**
  16. * @author Antonio Jose Cerezo Aranda <aj.cerezo@gmail.com>
  17. */
  18. class CouchbaseBucketAdapter extends AbstractAdapter
  19. {
  20. private const THIRTY_DAYS_IN_SECONDS = 2592000;
  21. private const MAX_KEY_LENGTH = 250;
  22. private const KEY_NOT_FOUND = 13;
  23. private const VALID_DSN_OPTIONS = [
  24. 'operationTimeout',
  25. 'configTimeout',
  26. 'configNodeTimeout',
  27. 'n1qlTimeout',
  28. 'httpTimeout',
  29. 'configDelay',
  30. 'htconfigIdleTimeout',
  31. 'durabilityInterval',
  32. 'durabilityTimeout',
  33. ];
  34. private $bucket;
  35. private $marshaller;
  36. public function __construct(\CouchbaseBucket $bucket, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
  37. {
  38. if (!static::isSupported()) {
  39. throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
  40. }
  41. $this->maxIdLength = static::MAX_KEY_LENGTH;
  42. $this->bucket = $bucket;
  43. parent::__construct($namespace, $defaultLifetime);
  44. $this->enableVersioning();
  45. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  46. }
  47. /**
  48. * @param array|string $servers
  49. */
  50. public static function createConnection($servers, array $options = []): \CouchbaseBucket
  51. {
  52. if (\is_string($servers)) {
  53. $servers = [$servers];
  54. } elseif (!\is_array($servers)) {
  55. throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be array or string, "%s" given.', __METHOD__, get_debug_type($servers)));
  56. }
  57. if (!static::isSupported()) {
  58. throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
  59. }
  60. set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
  61. $dsnPattern = '/^(?<protocol>couchbase(?:s)?)\:\/\/(?:(?<username>[^\:]+)\:(?<password>[^\@]{6,})@)?'
  62. .'(?<host>[^\:]+(?:\:\d+)?)(?:\/(?<bucketName>[^\?]+))(?:\?(?<options>.*))?$/i';
  63. $newServers = [];
  64. $protocol = 'couchbase';
  65. try {
  66. $options = self::initOptions($options);
  67. $username = $options['username'];
  68. $password = $options['password'];
  69. foreach ($servers as $dsn) {
  70. if (0 !== strpos($dsn, 'couchbase:')) {
  71. throw new InvalidArgumentException(sprintf('Invalid Couchbase DSN: "%s" does not start with "couchbase:".', $dsn));
  72. }
  73. preg_match($dsnPattern, $dsn, $matches);
  74. $username = $matches['username'] ?: $username;
  75. $password = $matches['password'] ?: $password;
  76. $protocol = $matches['protocol'] ?: $protocol;
  77. if (isset($matches['options'])) {
  78. $optionsInDsn = self::getOptions($matches['options']);
  79. foreach ($optionsInDsn as $parameter => $value) {
  80. $options[$parameter] = $value;
  81. }
  82. }
  83. $newServers[] = $matches['host'];
  84. }
  85. $connectionString = $protocol.'://'.implode(',', $newServers);
  86. $client = new \CouchbaseCluster($connectionString);
  87. $client->authenticateAs($username, $password);
  88. $bucket = $client->openBucket($matches['bucketName']);
  89. unset($options['username'], $options['password']);
  90. foreach ($options as $option => $value) {
  91. if (!empty($value)) {
  92. $bucket->$option = $value;
  93. }
  94. }
  95. return $bucket;
  96. } finally {
  97. restore_error_handler();
  98. }
  99. }
  100. public static function isSupported(): bool
  101. {
  102. return \extension_loaded('couchbase') && version_compare(phpversion('couchbase'), '2.6.0', '>=') && version_compare(phpversion('couchbase'), '3.0', '<');
  103. }
  104. private static function getOptions(string $options): array
  105. {
  106. $results = [];
  107. $optionsInArray = explode('&', $options);
  108. foreach ($optionsInArray as $option) {
  109. [$key, $value] = explode('=', $option);
  110. if (\in_array($key, static::VALID_DSN_OPTIONS, true)) {
  111. $results[$key] = $value;
  112. }
  113. }
  114. return $results;
  115. }
  116. private static function initOptions(array $options): array
  117. {
  118. $options['username'] = $options['username'] ?? '';
  119. $options['password'] = $options['password'] ?? '';
  120. $options['operationTimeout'] = $options['operationTimeout'] ?? 0;
  121. $options['configTimeout'] = $options['configTimeout'] ?? 0;
  122. $options['configNodeTimeout'] = $options['configNodeTimeout'] ?? 0;
  123. $options['n1qlTimeout'] = $options['n1qlTimeout'] ?? 0;
  124. $options['httpTimeout'] = $options['httpTimeout'] ?? 0;
  125. $options['configDelay'] = $options['configDelay'] ?? 0;
  126. $options['htconfigIdleTimeout'] = $options['htconfigIdleTimeout'] ?? 0;
  127. $options['durabilityInterval'] = $options['durabilityInterval'] ?? 0;
  128. $options['durabilityTimeout'] = $options['durabilityTimeout'] ?? 0;
  129. return $options;
  130. }
  131. /**
  132. * {@inheritdoc}
  133. */
  134. protected function doFetch(array $ids)
  135. {
  136. $resultsCouchbase = $this->bucket->get($ids);
  137. $results = [];
  138. foreach ($resultsCouchbase as $key => $value) {
  139. if (null !== $value->error) {
  140. continue;
  141. }
  142. $results[$key] = $this->marshaller->unmarshall($value->value);
  143. }
  144. return $results;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. protected function doHave(string $id): bool
  150. {
  151. return false !== $this->bucket->get($id);
  152. }
  153. /**
  154. * {@inheritdoc}
  155. */
  156. protected function doClear(string $namespace): bool
  157. {
  158. if ('' === $namespace) {
  159. $this->bucket->manager()->flush();
  160. return true;
  161. }
  162. return false;
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. protected function doDelete(array $ids): bool
  168. {
  169. $results = $this->bucket->remove(array_values($ids));
  170. foreach ($results as $key => $result) {
  171. if (null !== $result->error && static::KEY_NOT_FOUND !== $result->error->getCode()) {
  172. continue;
  173. }
  174. unset($results[$key]);
  175. }
  176. return 0 === \count($results);
  177. }
  178. /**
  179. * {@inheritdoc}
  180. */
  181. protected function doSave(array $values, int $lifetime)
  182. {
  183. if (!$values = $this->marshaller->marshall($values, $failed)) {
  184. return $failed;
  185. }
  186. $lifetime = $this->normalizeExpiry($lifetime);
  187. $ko = [];
  188. foreach ($values as $key => $value) {
  189. $result = $this->bucket->upsert($key, $value, ['expiry' => $lifetime]);
  190. if (null !== $result->error) {
  191. $ko[$key] = $result;
  192. }
  193. }
  194. return [] === $ko ? true : $ko;
  195. }
  196. private function normalizeExpiry(int $expiry): int
  197. {
  198. if ($expiry && $expiry > static::THIRTY_DAYS_IN_SECONDS) {
  199. $expiry += time();
  200. }
  201. return $expiry;
  202. }
  203. }