CouchbaseBucketAdapter.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. trigger_deprecation('symfony/cache', '7.1', 'The "%s" class is deprecated, use "%s" instead.', CouchbaseBucketAdapter::class, CouchbaseCollectionAdapter::class);
  16. /**
  17. * @author Antonio Jose Cerezo Aranda <aj.cerezo@gmail.com>
  18. *
  19. * @deprecated since Symfony 7.1, use {@see CouchbaseCollectionAdapter} instead
  20. */
  21. class CouchbaseBucketAdapter extends AbstractAdapter
  22. {
  23. private const THIRTY_DAYS_IN_SECONDS = 2592000;
  24. private const MAX_KEY_LENGTH = 250;
  25. private const KEY_NOT_FOUND = 13;
  26. private const VALID_DSN_OPTIONS = [
  27. 'operationTimeout',
  28. 'configTimeout',
  29. 'configNodeTimeout',
  30. 'n1qlTimeout',
  31. 'httpTimeout',
  32. 'configDelay',
  33. 'htconfigIdleTimeout',
  34. 'durabilityInterval',
  35. 'durabilityTimeout',
  36. ];
  37. private MarshallerInterface $marshaller;
  38. public function __construct(
  39. private \CouchbaseBucket $bucket,
  40. string $namespace = '',
  41. int $defaultLifetime = 0,
  42. ?MarshallerInterface $marshaller = null,
  43. ) {
  44. if (!static::isSupported()) {
  45. throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
  46. }
  47. $this->maxIdLength = static::MAX_KEY_LENGTH;
  48. parent::__construct($namespace, $defaultLifetime);
  49. $this->enableVersioning();
  50. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  51. }
  52. public static function createConnection(#[\SensitiveParameter] array|string $servers, array $options = []): \CouchbaseBucket
  53. {
  54. if (\is_string($servers)) {
  55. $servers = [$servers];
  56. }
  57. if (!static::isSupported()) {
  58. throw new CacheException('Couchbase >= 2.6.0 < 3.0.0 is required.');
  59. }
  60. set_error_handler(static fn ($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 (!str_starts_with($dsn, 'couchbase:')) {
  71. throw new InvalidArgumentException('Invalid Couchbase DSN: it does not start with "couchbase:".');
  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 ($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'] ??= '';
  119. $options['password'] ??= '';
  120. $options['operationTimeout'] ??= 0;
  121. $options['configTimeout'] ??= 0;
  122. $options['configNodeTimeout'] ??= 0;
  123. $options['n1qlTimeout'] ??= 0;
  124. $options['httpTimeout'] ??= 0;
  125. $options['configDelay'] ??= 0;
  126. $options['htconfigIdleTimeout'] ??= 0;
  127. $options['durabilityInterval'] ??= 0;
  128. $options['durabilityTimeout'] ??= 0;
  129. return $options;
  130. }
  131. protected function doFetch(array $ids): iterable
  132. {
  133. $resultsCouchbase = $this->bucket->get($ids);
  134. $results = [];
  135. foreach ($resultsCouchbase as $key => $value) {
  136. if (null !== $value->error) {
  137. continue;
  138. }
  139. $results[$key] = $this->marshaller->unmarshall($value->value);
  140. }
  141. return $results;
  142. }
  143. protected function doHave(string $id): bool
  144. {
  145. return false !== $this->bucket->get($id);
  146. }
  147. protected function doClear(string $namespace): bool
  148. {
  149. if ('' === $namespace) {
  150. $this->bucket->manager()->flush();
  151. return true;
  152. }
  153. return false;
  154. }
  155. protected function doDelete(array $ids): bool
  156. {
  157. $results = $this->bucket->remove(array_values($ids));
  158. foreach ($results as $key => $result) {
  159. if (null !== $result->error && static::KEY_NOT_FOUND !== $result->error->getCode()) {
  160. continue;
  161. }
  162. unset($results[$key]);
  163. }
  164. return 0 === \count($results);
  165. }
  166. protected function doSave(array $values, int $lifetime): array|bool
  167. {
  168. if (!$values = $this->marshaller->marshall($values, $failed)) {
  169. return $failed;
  170. }
  171. $lifetime = $this->normalizeExpiry($lifetime);
  172. $ko = [];
  173. foreach ($values as $key => $value) {
  174. $result = $this->bucket->upsert($key, $value, ['expiry' => $lifetime]);
  175. if (null !== $result->error) {
  176. $ko[$key] = $result;
  177. }
  178. }
  179. return [] === $ko ? true : $ko;
  180. }
  181. private function normalizeExpiry(int $expiry): int
  182. {
  183. if ($expiry && $expiry > static::THIRTY_DAYS_IN_SECONDS) {
  184. $expiry += time();
  185. }
  186. return $expiry;
  187. }
  188. }