CouchbaseBucketAdapter.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. public static function createConnection(array|string $servers, array $options = []): \CouchbaseBucket
  48. {
  49. if (\is_string($servers)) {
  50. $servers = [$servers];
  51. }
  52. if (!static::isSupported()) {
  53. throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
  54. }
  55. set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
  56. $dsnPattern = '/^(?<protocol>couchbase(?:s)?)\:\/\/(?:(?<username>[^\:]+)\:(?<password>[^\@]{6,})@)?'
  57. .'(?<host>[^\:]+(?:\:\d+)?)(?:\/(?<bucketName>[^\?]+))(?:\?(?<options>.*))?$/i';
  58. $newServers = [];
  59. $protocol = 'couchbase';
  60. try {
  61. $options = self::initOptions($options);
  62. $username = $options['username'];
  63. $password = $options['password'];
  64. foreach ($servers as $dsn) {
  65. if (0 !== strpos($dsn, 'couchbase:')) {
  66. throw new InvalidArgumentException(sprintf('Invalid Couchbase DSN: "%s" does not start with "couchbase:".', $dsn));
  67. }
  68. preg_match($dsnPattern, $dsn, $matches);
  69. $username = $matches['username'] ?: $username;
  70. $password = $matches['password'] ?: $password;
  71. $protocol = $matches['protocol'] ?: $protocol;
  72. if (isset($matches['options'])) {
  73. $optionsInDsn = self::getOptions($matches['options']);
  74. foreach ($optionsInDsn as $parameter => $value) {
  75. $options[$parameter] = $value;
  76. }
  77. }
  78. $newServers[] = $matches['host'];
  79. }
  80. $connectionString = $protocol.'://'.implode(',', $newServers);
  81. $client = new \CouchbaseCluster($connectionString);
  82. $client->authenticateAs($username, $password);
  83. $bucket = $client->openBucket($matches['bucketName']);
  84. unset($options['username'], $options['password']);
  85. foreach ($options as $option => $value) {
  86. if (!empty($value)) {
  87. $bucket->$option = $value;
  88. }
  89. }
  90. return $bucket;
  91. } finally {
  92. restore_error_handler();
  93. }
  94. }
  95. public static function isSupported(): bool
  96. {
  97. return \extension_loaded('couchbase') && version_compare(phpversion('couchbase'), '2.6.0', '>=') && version_compare(phpversion('couchbase'), '3.0', '<');
  98. }
  99. private static function getOptions(string $options): array
  100. {
  101. $results = [];
  102. $optionsInArray = explode('&', $options);
  103. foreach ($optionsInArray as $option) {
  104. [$key, $value] = explode('=', $option);
  105. if (\in_array($key, static::VALID_DSN_OPTIONS, true)) {
  106. $results[$key] = $value;
  107. }
  108. }
  109. return $results;
  110. }
  111. private static function initOptions(array $options): array
  112. {
  113. $options['username'] = $options['username'] ?? '';
  114. $options['password'] = $options['password'] ?? '';
  115. $options['operationTimeout'] = $options['operationTimeout'] ?? 0;
  116. $options['configTimeout'] = $options['configTimeout'] ?? 0;
  117. $options['configNodeTimeout'] = $options['configNodeTimeout'] ?? 0;
  118. $options['n1qlTimeout'] = $options['n1qlTimeout'] ?? 0;
  119. $options['httpTimeout'] = $options['httpTimeout'] ?? 0;
  120. $options['configDelay'] = $options['configDelay'] ?? 0;
  121. $options['htconfigIdleTimeout'] = $options['htconfigIdleTimeout'] ?? 0;
  122. $options['durabilityInterval'] = $options['durabilityInterval'] ?? 0;
  123. $options['durabilityTimeout'] = $options['durabilityTimeout'] ?? 0;
  124. return $options;
  125. }
  126. /**
  127. * {@inheritdoc}
  128. */
  129. protected function doFetch(array $ids): iterable
  130. {
  131. $resultsCouchbase = $this->bucket->get($ids);
  132. $results = [];
  133. foreach ($resultsCouchbase as $key => $value) {
  134. if (null !== $value->error) {
  135. continue;
  136. }
  137. $results[$key] = $this->marshaller->unmarshall($value->value);
  138. }
  139. return $results;
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. protected function doHave(string $id): bool
  145. {
  146. return false !== $this->bucket->get($id);
  147. }
  148. /**
  149. * {@inheritdoc}
  150. */
  151. protected function doClear(string $namespace): bool
  152. {
  153. if ('' === $namespace) {
  154. $this->bucket->manager()->flush();
  155. return true;
  156. }
  157. return false;
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. protected function doDelete(array $ids): bool
  163. {
  164. $results = $this->bucket->remove(array_values($ids));
  165. foreach ($results as $key => $result) {
  166. if (null !== $result->error && static::KEY_NOT_FOUND !== $result->error->getCode()) {
  167. continue;
  168. }
  169. unset($results[$key]);
  170. }
  171. return 0 === \count($results);
  172. }
  173. /**
  174. * {@inheritdoc}
  175. */
  176. protected function doSave(array $values, int $lifetime): array|bool
  177. {
  178. if (!$values = $this->marshaller->marshall($values, $failed)) {
  179. return $failed;
  180. }
  181. $lifetime = $this->normalizeExpiry($lifetime);
  182. $ko = [];
  183. foreach ($values as $key => $value) {
  184. $result = $this->bucket->upsert($key, $value, ['expiry' => $lifetime]);
  185. if (null !== $result->error) {
  186. $ko[$key] = $result;
  187. }
  188. }
  189. return [] === $ko ? true : $ko;
  190. }
  191. private function normalizeExpiry(int $expiry): int
  192. {
  193. if ($expiry && $expiry > static::THIRTY_DAYS_IN_SECONDS) {
  194. $expiry += time();
  195. }
  196. return $expiry;
  197. }
  198. }