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