From 67602baaebac63a2bb5e15c3154fd1998f9ef144 Mon Sep 17 00:00:00 2001 From: Georges Date: Sun, 7 Jan 2024 09:54:54 +0100 Subject: [PATCH] Moved Mongodb and Solr to their own extensions --- .../ISSUE_TEMPLATE/bug-report-extension.yml | 6 +- .github/workflows/testsv2.yml | 1 + .scrutinizer.yml | 2 +- .travis.yml | 5 - CHANGELOG.md | 7 +- EXTENSIONS.MD | 1 + README.md | 35 +- bin/ci/scripts/install_dependencies.sh | 2 +- bin/ci/scripts/install_solr.sh | 55 --- bin/ci/scripts/setup_mongodb.sh | 4 - composer.json | 3 +- docs/EVENTS.md | 10 +- lib/Phpfastcache/Drivers/Mongodb/Config.php | 259 ----------- lib/Phpfastcache/Drivers/Mongodb/Driver.php | 411 ------------------ lib/Phpfastcache/Drivers/Mongodb/Item.php | 30 -- lib/Phpfastcache/Drivers/Solr/Config.php | 210 --------- lib/Phpfastcache/Drivers/Solr/Driver.php | 360 --------------- lib/Phpfastcache/Drivers/Solr/Event.php | 8 - lib/Phpfastcache/Drivers/Solr/Item.php | 30 -- phpstan.neon | 4 - tests/cases/Solr.test.php | 68 --- 21 files changed, 34 insertions(+), 1477 deletions(-) delete mode 100755 bin/ci/scripts/install_solr.sh delete mode 100755 bin/ci/scripts/setup_mongodb.sh delete mode 100644 lib/Phpfastcache/Drivers/Mongodb/Config.php delete mode 100644 lib/Phpfastcache/Drivers/Mongodb/Driver.php delete mode 100644 lib/Phpfastcache/Drivers/Mongodb/Item.php delete mode 100644 lib/Phpfastcache/Drivers/Solr/Config.php delete mode 100644 lib/Phpfastcache/Drivers/Solr/Driver.php delete mode 100644 lib/Phpfastcache/Drivers/Solr/Event.php delete mode 100644 lib/Phpfastcache/Drivers/Solr/Item.php delete mode 100644 tests/cases/Solr.test.php diff --git a/.github/ISSUE_TEMPLATE/bug-report-extension.yml b/.github/ISSUE_TEMPLATE/bug-report-extension.yml index 578c9a36..01d97524 100644 --- a/.github/ISSUE_TEMPLATE/bug-report-extension.yml +++ b/.github/ISSUE_TEMPLATE/bug-report-extension.yml @@ -28,7 +28,11 @@ body: attributes: label: Which extension is this issue about ? options: + - Arangodb - Couchbasev4 + - Couchdb + - Mongodb + - Solr validations: required: true - type: dropdown @@ -68,7 +72,7 @@ body: The connector and/or SDK version + the database version if applicable, ex: - Couchbase 7.1.0 + PECL Extension 3.2.2 - Redis 7.0.0 + PECL Extension 5.3.7 - - MongoDB 5.0.2 Community + mongodb/mongodb + - MongoDB 5.0.2 Community + mongodb/mongodb version x.x.x - etc **Be as much detailed as you can be !** diff --git a/.github/workflows/testsv2.yml b/.github/workflows/testsv2.yml index 87a53354..3fa925d1 100644 --- a/.github/workflows/testsv2.yml +++ b/.github/workflows/testsv2.yml @@ -2,6 +2,7 @@ name: Phpfastcache Tests on: [push, pull_request] jobs: run: + environment: github-ci runs-on: ${{ matrix.operating-system }} timeout-minutes: 60 strategy: diff --git a/.scrutinizer.yml b/.scrutinizer.yml index a073e90c..4b455bec 100644 --- a/.scrutinizer.yml +++ b/.scrutinizer.yml @@ -12,7 +12,7 @@ build: dependencies: override: - - "composer require -W --ignore-platform-reqs phpfastcache/phpssdb:~1.1 predis/predis:~1.1 mongodb/mongodb:~1.9 aws/aws-sdk-php:~3.2 google/cloud-firestore:~1.20 solarium/solarium:~6.1" + - "composer require -W --ignore-platform-reqs phpfastcache/phpssdb:~1.1 predis/predis:~1.1 aws/aws-sdk-php:~3.2 google/cloud-firestore:~1.20 solarium/solarium:~6.1" nodes: analysis: project_setup: diff --git a/.travis.yml b/.travis.yml index f19ba413..bdfb141a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,8 +15,6 @@ language: php services: - memcached - redis - - mongodb - - docker cache: directories: - $HOME/pecl_cache @@ -40,15 +38,12 @@ before_install: - phpenv config-rm xdebug.ini - composer install - composer require phwoolcon/ci-pecl-cacher -n - - "./bin/ci/scripts/install_solr.sh || echo \"Solr install failed\"" - "./bin/ci/scripts/install_ssdb.sh || echo \"SSDB install failed\"" - "./bin/ci/scripts/install_couchbase.sh || echo \"Couchbase install failed\"" - - "./bin/ci/scripts/setup_mongodb.sh || echo \"Setup Mongodb failed\"" - "./bin/ci/scripts/setup_gcp.sh || echo \"GCP setup failed\"" - "pecl channel-update pecl.php.net || echo \"PECL Channel update failed\"" # - yes | pecl install -f grpc-stable | grep -v --line-buffered "/tmp/pear/install/grpc"; # This pecl install is partially muted due to too much output written - "yes | ./vendor/bin/ci-pecl-install grpc | grep -v --line-buffered \"/tmp/pear/install/grpc\" || echo \"PECL GRPC install failed\"" - #- "yes | (./vendor/bin/ci-pecl-install mongodb) || echo \"PECL Mongodb install failed\"" # Mongodb seems to be provided In Bionic: https://docs.travis-ci.com/user/reference/bionic/#php-support # - "yes | ./vendor/bin/ci-pecl-install apcu || echo \"PECL Apcu install failed\"" # Apcu seems to be provided In Bionic: https://docs.travis-ci.com/user/reference/bionic/#php-support - "yes | ./vendor/bin/ci-pecl-install memcache || echo \"PECL Memcache install failed\"" - "yes | ./vendor/bin/ci-pecl-install memcached || echo \"PECL Memcached install failed\"" diff --git a/CHANGELOG.md b/CHANGELOG.md index 31f6507e..99c9c629 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,9 +3,10 @@ - __API__ - Upgraded Phpfastcache API to `4.3.0` ([see changes](CHANGELOG_API.md)) - __Extensions__ (💡 New in 9.2) - - Created an extension mechanism to allow future driver to be loaded independently, see [README.md](README.md) - - Created first extension for `Couchbasev4` support which will be moved to a [sub-repository](https://github.com/PHPSocialNetwork/couchbasev4-extension). - - **IMPORTANT**: *AS OF V10* the following drivers will be **MOVED** to their own sub-repositories as a standalone extension: `Arangodb`, `Couchdb`, `Cassandra`, `Dynamodb`, `Firestore`, `Mongodb`, `Solr`. However `Couchbasev3` will stay in the core for compatibility reasons but will be deprecated. + - Created an extension mechanism to allow some drivers to be loaded independently, see [README.md](README.md) + - Created extension for `Couchbasev4` support to its own [sub-repository](https://github.com/PHPSocialNetwork/couchbasev4-extension). + - **IMPORTANT**: *AS OF v9.2* the following drivers has been **MOVED** to their own sub-repositories as a standalone extension: `Arangodb`, `Couchdb`, `Cassandra`, `Dynamodb`, `Firestore`, `Mongodb`, `Solr`. However `Couchbasev3` will stay in the core for compatibility reasons but will be deprecated. + - **IMPORTANT**: *AS OF v10* extensions will have their namespaces permanently moved from `Phpfastcache\Drivers\EXT_NAME\{Config, Driver, Event, Item}` to `Phpfastcache\Extensions\Drivers\EXT_NAME\{Config, Driver, Event, Item}`. For now an alias is ensuring compatibility. - __Events__ - EventManager is now scoped to its own poll if retrieved through `ExtendedCacheItemPoolTrait::->getEventManager()`. Global EventManager `EventManager::getInstance()` remains unchanged, see [EVENTS.md](./docs/EVENTS.md). - `EventManagerInterface::on()` now also accepts a single `string $events`. diff --git a/EXTENSIONS.MD b/EXTENSIONS.MD index baea0dd5..b7450c52 100644 --- a/EXTENSIONS.MD +++ b/EXTENSIONS.MD @@ -11,6 +11,7 @@ The 9.2 make the beginning of a new external extensions: - `Dynamodb` - `Firestore` - `Mongodb` +- `Solr` There's only 2 steps: diff --git a/README.md b/README.md index aa6af99d..67bf2e99 100644 --- a/README.md +++ b/README.md @@ -15,27 +15,28 @@ The simplicity of abstraction: One class for many backend cache. You don't need ### Supported drivers at this day * :bulb: Feel free to propose a driver by making a new **[Pull Request](https://github.com/PHPSocialNetwork/phpfastcache/compare)**, they are welcome ! -| Regular drivers | High performances drivers | Development drivers | Cluster-Aggregated drivers | -|------------------------------------------------------------------------|------------------------------------------------------------------------------------------|--------------------------------------------|---------------------------------| -| `Apcu`
_(APC support removed)_ | `Arangodb` | `Devnull` | `FullReplicationCluster` | -| `Dynamodb` (AWS) | `Cassandra` | `Devrandom` | `SemiReplicationCluster` | -| `Files` | `CouchBasev3`
_(Will be deprecated as of v10)_ | `Memory`
(Previously named `Memstatic`) | `MasterSlaveReplicationCluster` | -| `Firestore` (GCP) | `CouchBasev4` _([Extension](https://github.com/PHPSocialNetwork/couchbasev4-extension))_ | | `RandomReplicationCluster` | -| `Leveldb` | `Couchdb` | | | -| `Memcache(d)` | `Mongodb` | | | -| `Solr` _(Via [Solarium 6.x](https://github.com/solariumphp/solarium))_ | `Predis` | | | -| `Sqlite` | `Redis`/`RedisCluster` | | | -| `Wincache`
(Deprecated as of v9.2, will be removed as of v10) | `Ssdb` | | | -| `Zend Disk Cache` | `Zend Memory Cache` | | | -| | | | | | | | | +| Regular drivers | High performances drivers | Development drivers _(Core)_ | Cluster-Aggregated drivers _(Core)_ | +|---------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|--------------------------------------------|---------------------------------------| +| `Apcu` _(Core)_
_(APC support removed)_ | `Arangodb` _([Extension](https://github.com/PHPSocialNetwork/arangodb-extension))_ | `Devnull` | `FullReplicationCluster` | +| `Dynamodb` (AWS) | `Cassandra` | `Devrandom` | `SemiReplicationCluster` | +| `Files` _(Core)_ | `CouchBasev3` _(Core)_
_(Will be deprecated as of v10)_ | `Memory`
(Previously named `Memstatic`) | `MasterSlaveReplicationCluster` | +| `Firestore` (GCP) | `CouchBasev4` _([Extension](https://github.com/PHPSocialNetwork/couchbasev4-extension))_ | | `RandomReplicationCluster` | +| `Leveldb` _(Core)_ | `Couchdb` _([Extension](https://github.com/PHPSocialNetwork/couchdb-extension))_ | | | +| `Memcache(d)` _(Core)_ | `Mongodb` _([Extension](https://github.com/PHPSocialNetwork/mongodb-extension))_ | | | +| `Solr` _([Extension](https://github.com/PHPSocialNetwork/solr-extension))_ | `Predis` _(Core)_ | | | +| `Sqlite` _(Core)_ | `Redis`/`RedisCluster` _(Core)_ | | | +| `Wincache` _(Core)_
(**Deprecated** as of v9.2, will be removed as of v10) | `Ssdb` _(Core)_ | | | +| `Zend Disk Cache` _(Core)_ | `Zend Memory Cache` _(Core)_ | | | +| | | | | \* Driver descriptions available in [DOCS/DRIVERS.md](./docs/DRIVERS.md) -:new: As of v9.2 the first extension has been released: [Couchbasev4](https://github.com/PHPSocialNetwork/couchbasev4-extension) +:new: As of v9.2 a new Couchbase extension has been released: [Couchbasev4](https://github.com/PHPSocialNetwork/couchbasev4-extension) -This new extension **is the beginning of a new era** for Phpfastcache:\ -As of the v10 many drivers will be moved from the core to their own sub-repository as a standalone extension: `Arangodb`, `Couchdb`, `Cassandra`, `Dynamodb`, `Firestore`, `Mongodb`, `Solr`.\ -However `Couchbasev3` will stay in the core for compatibility reasons but will be deprecated. +This new extension **is the beginning of a new era** for Phpfastcache along with some others:\ +Many drivers has been moved from the core to their own sub-repository as a standalone extension: `Arangodb`, `Couchdb`, `Cassandra`, `Dynamodb`, `Firestore`, `Mongodb`, `Solr`.\ +They can be easily added through composer, ex: `composer install phpfastcache/couchbasev4-extension` +However `Couchbasev3` **will stay in the core** for compatibility reasons but will be deprecated. --------------------------- Because caching does not mean weaken your code diff --git a/bin/ci/scripts/install_dependencies.sh b/bin/ci/scripts/install_dependencies.sh index cf19e6bc..4839e4c9 100755 --- a/bin/ci/scripts/install_dependencies.sh +++ b/bin/ci/scripts/install_dependencies.sh @@ -6,4 +6,4 @@ composer install ##### # Travis CI have php mongodb extension locked to 1.10, so we must set the mongodb/mongodb minimum version to 1.9 :( ##### -composer require -W phpfastcache/phpssdb:~1.2 predis/predis:~1.1 mongodb/mongodb:~1.9 triagens/arangodb:~3.8 aws/aws-sdk-php:~3.2 google/cloud-firestore:~1.39 solarium/solarium:~6.1 +composer require -W phpfastcache/phpssdb:~1.2 predis/predis:~1.1 mongodb/mongodb:~1.9 aws/aws-sdk-php:~3.2 google/cloud-firestore:~1.39 diff --git a/bin/ci/scripts/install_solr.sh b/bin/ci/scripts/install_solr.sh deleted file mode 100755 index 9ac16b04..00000000 --- a/bin/ci/scripts/install_solr.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/bash - -set -e - -export SOLR_PORT=8983 -export SOLR_HOST=127.0.0.1 -export SOLR_VERSION=8.11.1 -export SOLR_CORE=phpfastcache - -download() { - FILE="$2.tgz" - if [ -f $FILE ]; - then - echo "File $FILE exists." - tar -zxf $FILE - else - echo "File $FILE does not exist. Downloading solr from $1..." - curl -O $1 - tar -zxf $FILE - fi - echo "Downloaded!" -} - -is_solr_up(){ - echo "Checking if solr is up on http://localhost:$SOLR_PORT/solr/admin/cores" - http_code=`echo $(curl -s -o /dev/null -w "%{http_code}" "http://localhost:$SOLR_PORT/solr/admin/cores")` - return `test $http_code = "200"` -} - -wait_for_solr(){ - while ! is_solr_up; do - sleep 3 - done -} - -run_solr() { - dir_name=$1 - ./$dir_name/bin/solr -p $SOLR_PORT -h $SOLR_HOST - wait_for_solr - ./$dir_name/bin/solr create_core -c $SOLR_CORE -p $SOLR_PORT - echo "Started" -} - -download_and_run() { - version=$1 - url="http://archive.apache.org/dist/lucene/solr/${version}/solr-${version}.tgz" - dir_name="solr-${version}" - download $url $dir_name - - run_solr $dir_name -} - - - -download_and_run $SOLR_VERSION diff --git a/bin/ci/scripts/setup_mongodb.sh b/bin/ci/scripts/setup_mongodb.sh deleted file mode 100755 index a66c28e0..00000000 --- a/bin/ci/scripts/setup_mongodb.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash - -echo "# Setting up Mongodb database and user" -mongo pfc_test --eval 'db.createUser({user:"travis",pwd:"test",roles:["readWrite"]});' diff --git a/composer.json b/composer.json index 0626a1eb..6d7299bb 100644 --- a/composer.json +++ b/composer.json @@ -63,7 +63,8 @@ "google/cloud-firestore": "^1.20", "aws/aws-sdk-php": "~3.0", "phpfastcache/arangodb-extension": "^9.2", - "phpfastcache/couchdb-extension": "^9.2" + "phpfastcache/couchdb-extension": "^9.2", + "phpfastcache/solr-extension": "^9.2" }, "conflict": { "solarium/solarium": "<6.1" diff --git a/docs/EVENTS.md b/docs/EVENTS.md index a3912164..f2efb2e1 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -328,12 +328,4 @@ See [Couchdb extension event documentation](https://github.com/PHPSocialNetwork/ - **Risky Circular Methods**: None #### Solr -- onSolrBuildEndpoint(*Callable* **$callback**) - - **Callback arguments** - - *ExtendedCacheItemPoolInterface* **$itemPool** - - *EventReferenceParameter($params)* **$endpoints** _via EventReferenceParameter object_ **(type modification forbidden)** - - **Scope** - - Solr Driver - - **Description** - - Allow you to alter the endpoints built used to connect to Solr server - - **Risky Circular Methods**: None +See [Solr extension event documentation](https://github.com/PHPSocialNetwork/solr-extension#events). diff --git a/lib/Phpfastcache/Drivers/Mongodb/Config.php b/lib/Phpfastcache/Drivers/Mongodb/Config.php deleted file mode 100644 index fe919fa3..00000000 --- a/lib/Phpfastcache/Drivers/Mongodb/Config.php +++ /dev/null @@ -1,259 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Mongodb; - -use Phpfastcache\Config\ConfigurationOption; -use Phpfastcache\Exceptions\PhpfastcacheLogicException; - -class Config extends ConfigurationOption -{ - protected string $host = '127.0.0.1'; - protected int $port = 27017; - protected int $timeout = 3; - protected string $username = ''; - protected string $password = ''; - protected string $collectionName = 'phpfastcache'; - protected string $databaseName = Driver::MONGODB_DEFAULT_DB_NAME; - protected string $protocol = 'mongodb'; - protected string $documentPrefix = 'pfc_'; - - /** @var array */ - protected array $servers = []; - - /** @var array */ - protected array $options = []; - - /** @var array */ - protected array $driverOptions = []; - - /** - * @return string - */ - public function getHost(): string - { - return $this->host; - } - - /** - * @param string $host - * @return self - * @throws PhpfastcacheLogicException - */ - public function setHost(string $host): static - { - return $this->setProperty('host', $host); - } - - /** - * @return int - */ - public function getPort(): int - { - return $this->port; - } - - /** - * @param int $port - * @return self - * @throws PhpfastcacheLogicException - */ - public function setPort(int $port): static - { - return $this->setProperty('port', $port); - } - - /** - * @return int - */ - public function getTimeout(): int - { - return $this->timeout; - } - - /** - * @param int $timeout - * @return self - * @throws PhpfastcacheLogicException - */ - public function setTimeout(int $timeout): static - { - return $this->setProperty('timeout', $timeout); - } - - /** - * @return string - */ - public function getUsername(): string - { - return $this->username; - } - - /** - * @param string $username - * @return self - * @throws PhpfastcacheLogicException - */ - public function setUsername(string $username): static - { - return $this->setProperty('username', $username); - } - - /** - * @return string - */ - public function getPassword(): string - { - return $this->password; - } - - /** - * @param string $password - * @return self - * @throws PhpfastcacheLogicException - */ - public function setPassword(string $password): static - { - return $this->setProperty('password', $password); - } - - /** - * @return array - */ - public function getServers(): array - { - return $this->servers; - } - - /** - * @param array $servers - * @return self - * @throws PhpfastcacheLogicException - */ - public function setServers(array $servers): static - { - return $this->setProperty('servers', $servers); - } - - /** - * @return string - */ - public function getCollectionName(): string - { - return $this->collectionName; - } - - /** - * @param string $collectionName - * @return self - * @throws PhpfastcacheLogicException - */ - public function setCollectionName(string $collectionName): static - { - return $this->setProperty('collectionName', $collectionName); - } - - /** - * @return string - */ - public function getDatabaseName(): string - { - return $this->databaseName; - } - - /** - * @param string $databaseName - * @return self - * @throws PhpfastcacheLogicException - */ - public function setDatabaseName(string $databaseName): static - { - return $this->setProperty('databaseName', $databaseName); - } - - /** - * @return array - */ - public function getOptions(): array - { - return $this->options; - } - - /** - * @see https://docs.mongodb.com/manual/reference/connection-string/#connections-connection-options - * @param array $options - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setOptions(array $options): static - { - return $this->setProperty('options', $options); - } - - /** - * @return array - */ - public function getDriverOptions(): array - { - return $this->driverOptions; - } - - /** - * @param array $driverOptions - * @return self - * @throws PhpfastcacheLogicException - */ - public function setDriverOptions(array $driverOptions): static - { - return $this->setProperty('driverOptions', $driverOptions); - } - - /** - * @return string - */ - public function getProtocol(): string - { - return $this->protocol; - } - - /** - * @param string $protocol - * @return self - * @throws PhpfastcacheLogicException - */ - public function setProtocol(string $protocol): static - { - return $this->setProperty('protocol', $protocol); - } - - /** - * @return string - */ - public function getDocumentPrefix(): string - { - return $this->documentPrefix; - } - - /** - * @param string $documentPrefix - * @return self - * @throws PhpfastcacheLogicException - */ - public function setDocumentPrefix(string $documentPrefix): static - { - return $this->setProperty('documentPrefix', $documentPrefix); - } -} diff --git a/lib/Phpfastcache/Drivers/Mongodb/Driver.php b/lib/Phpfastcache/Drivers/Mongodb/Driver.php deleted file mode 100644 index cd9fb738..00000000 --- a/lib/Phpfastcache/Drivers/Mongodb/Driver.php +++ /dev/null @@ -1,411 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Mongodb; - -use LogicException; -use MongoClient; -use MongoDB\BSON\Binary; -use MongoDB\BSON\UTCDateTime; -use MongoDB\Client; -use MongoDB\Collection; -use MongoDB\Database; -use MongoDB\DeleteResult; -use MongoDB\Driver\Command; -use MongoDB\Driver\Exception\Exception as MongoDBException; -use MongoDB\Driver\Manager; -use Phpfastcache\Cluster\AggregatablePoolInterface; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait; -use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Entities\DriverStatistic; -use Phpfastcache\Exceptions\PhpfastcacheDriverException; -use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; -use Phpfastcache\Exceptions\PhpfastcacheLogicException; - -/** - * @property Client $instance Instance of driver service - * @method Config getConfig() - */ -class Driver implements AggregatablePoolInterface -{ - use TaggableCacheItemPoolTrait; - - public const MONGODB_DEFAULT_DB_NAME = 'phpfastcache'; // Public because used in config - - public const MONGODB_INDEX_KEY = '_id'; - - /** - * @var Collection - */ - public $collection; - - /** - * @var Database - */ - public $database; - - protected string $documentPrefix; - - /** - * @return bool - */ - public function driverCheck(): bool - { - $mongoExtensionExists = class_exists(Manager::class); - - if (!$mongoExtensionExists && class_exists(MongoClient::class)) { - trigger_error( - 'This driver is used to support the pecl MongoDb extension with mongo-php-library. - For MongoDb with Mongo PECL support use Mongo Driver.', - E_USER_ERROR - ); - } - - return $mongoExtensionExists && class_exists(Collection::class); - } - - /** - * @return bool - * @throws MongodbException - * @throws LogicException - */ - protected function driverConnect(): bool - { - $this->documentPrefix = $this->getConfig()->getDocumentPrefix(); - $timeout = $this->getConfig()->getTimeout() * 1000; - $collectionName = $this->getConfig()->getCollectionName(); - $databaseName = $this->getConfig()->getDatabaseName(); - $driverOptions = $this->getConfig()->getDriverOptions(); - - $this->instance = new Client($this->buildConnectionURI($databaseName), ['connectTimeoutMS' => $timeout], $driverOptions); - $this->database = $this->instance->selectDatabase($databaseName); - - if (!$this->collectionExists($collectionName)) { - $this->database->createCollection($collectionName); - $this->database->selectCollection($collectionName) - ->createIndex( - [self::DRIVER_KEY_WRAPPER_INDEX => 1], - ['unique' => true, 'name' => 'unique_key_index'] - ); - $this->database->selectCollection($collectionName) - ->createIndex( - [self::DRIVER_EDATE_WRAPPER_INDEX => 1], - ['expireAfterSeconds' => 0, 'name' => 'auto_expire_index'] - ); - } - - $this->collection = $this->database->selectCollection($collectionName); - - return true; - } - - /** - * @param ExtendedCacheItemInterface $item - * @return ?array - */ - protected function driverRead(ExtendedCacheItemInterface $item): ?array - { - $document = $this->getCollection()->findOne([self::MONGODB_INDEX_KEY => $this->getMongoDbItemKey($item)]); - - if ($document) { - $return = [ - self::DRIVER_DATA_WRAPPER_INDEX => $this->unserialize($document[self::DRIVER_DATA_WRAPPER_INDEX]->getData()), - self::DRIVER_TAGS_WRAPPER_INDEX => $document[self::DRIVER_TAGS_WRAPPER_INDEX]->jsonSerialize(), - self::DRIVER_EDATE_WRAPPER_INDEX => $document[self::DRIVER_EDATE_WRAPPER_INDEX]->toDateTime(), - ]; - - if ($this->getConfig()->isItemDetailedDate()) { - $return += [ - self::DRIVER_MDATE_WRAPPER_INDEX => isset($document[self::DRIVER_MDATE_WRAPPER_INDEX]) - ? $document[self::DRIVER_MDATE_WRAPPER_INDEX]->toDateTime() - : new \DateTime(), - self::DRIVER_CDATE_WRAPPER_INDEX => isset($document[self::DRIVER_CDATE_WRAPPER_INDEX]) - ? $document[self::DRIVER_CDATE_WRAPPER_INDEX]->toDateTime() - : new \DateTime(), - ]; - } - - return $return; - } - - return null; - } - - /** - * @param ExtendedCacheItemInterface ...$items - * @return array> - */ - protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array - { - $driverArrays = []; - $keys = array_map(fn(ExtendedCacheItemInterface $item) => $this->getMongoDbItemKey($item), $items); - $documents = $this->getCollection()->find([self::MONGODB_INDEX_KEY => ['$in' => array_values($keys)]]); - - foreach ($documents as $document) { - $driverArray = [ - self::DRIVER_DATA_WRAPPER_INDEX => $this->unserialize($document[self::DRIVER_DATA_WRAPPER_INDEX]->getData()), - self::DRIVER_TAGS_WRAPPER_INDEX => $document[self::DRIVER_TAGS_WRAPPER_INDEX]->jsonSerialize(), - self::DRIVER_EDATE_WRAPPER_INDEX => $document[self::DRIVER_EDATE_WRAPPER_INDEX]->toDateTime(), - ]; - if ($this->getConfig()->isItemDetailedDate()) { - $driverArray[self::DRIVER_MDATE_WRAPPER_INDEX] = isset($document[self::DRIVER_MDATE_WRAPPER_INDEX]) - ? $document[self::DRIVER_MDATE_WRAPPER_INDEX]->toDateTime() - : new \DateTime(); - $driverArray[self::DRIVER_CDATE_WRAPPER_INDEX] = isset($document[self::DRIVER_CDATE_WRAPPER_INDEX]) - ? $document[self::DRIVER_MDATE_WRAPPER_INDEX]->toDateTime() - : new \DateTime(); - } - $driverArrays[$document[self::DRIVER_KEY_WRAPPER_INDEX]] = $driverArray; - } - return $driverArrays; - } - - /** - * @return array - */ - protected function driverReadAllKeys(string $pattern = ''): iterable - { - $filters = ($pattern !== '' ? [self::DRIVER_KEY_WRAPPER_INDEX => ['$regex' => str_replace('*', '(.*)', $pattern)]] : []); - $documents = $this->getCollection()->find( - $filters, - [ - 'limit' => ExtendedCacheItemPoolInterface::MAX_ALL_KEYS_COUNT, - 'typeMap' => [ - 'document' => 'array', - 'root' => 'array' - ], - 'projection' => [ - self::MONGODB_INDEX_KEY => 0, - self::DRIVER_KEY_WRAPPER_INDEX => 1, - ] - ] - )->toArray(); - - return array_column($documents, self::DRIVER_KEY_WRAPPER_INDEX); - } - - /** - * @param ExtendedCacheItemInterface $item - * @return mixed - * @throws PhpfastcacheDriverException - * @throws PhpfastcacheInvalidArgumentException - * @throws PhpfastcacheLogicException - */ - protected function driverWrite(ExtendedCacheItemInterface $item): bool - { - - try { - $set = [ - self::DRIVER_KEY_WRAPPER_INDEX => $item->getKey(), - self::DRIVER_DATA_WRAPPER_INDEX => new Binary($this->encode($item->_getData()), Binary::TYPE_GENERIC), - self::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(), - self::DRIVER_EDATE_WRAPPER_INDEX => new UTCDateTime($item->getExpirationDate()), - ]; - - if (!empty($this->getConfig()->isItemDetailedDate())) { - $set += [ - self::DRIVER_MDATE_WRAPPER_INDEX => new UTCDateTime($item->getModificationDate()), - self::DRIVER_CDATE_WRAPPER_INDEX => new UTCDateTime($item->getCreationDate()), - ]; - } - $result = $this->getCollection()->updateOne( - [self::MONGODB_INDEX_KEY => $this->getMongoDbItemKey($item)], - [ - '$set' => $set, - ], - ['upsert' => true, 'multiple' => false] - ); - } catch (MongoDBException $e) { - throw new PhpfastcacheDriverException('Got an exception while trying to write data to MongoDB server: ' . $e->getMessage(), 0, $e); - } - - return $result->isAcknowledged(); - } - - /** - * @param string $key - * @param string $encodedKey - * @return bool - */ - protected function driverDelete(string $key, string $encodedKey): bool - { - $deletionResult = $this->getCollection()->deleteOne([self::MONGODB_INDEX_KEY => $this->getMongoDbKey($encodedKey)]); - - return $deletionResult->isAcknowledged(); - } - - /** - * @return bool - * @throws PhpfastcacheDriverException - */ - protected function driverClear(): bool - { - try { - return $this->collection->deleteMany([])->isAcknowledged(); - } catch (MongoDBException $e) { - throw new PhpfastcacheDriverException('Got error while trying to empty the collection: ' . $e->getMessage(), 0, $e); - } - } - - /** - * @return DriverStatistic - * @throws MongoDBException - */ - public function getStats(): DriverStatistic - { - $serverStats = $this->instance->getManager()->executeCommand( - $this->getConfig()->getDatabaseName(), - new Command( - [ - 'serverStatus' => 1, - 'recordStats' => 0, - 'repl' => 0, - 'metrics' => 0, - ] - ) - )->toArray()[0]; - - $collectionStats = $this->instance->getManager()->executeCommand( - $this->getConfig()->getDatabaseName(), - new Command( - [ - 'collStats' => $this->getConfig()->getCollectionName(), - 'verbose' => true, - ] - ) - )->toArray()[0]; - - $arrayFilterRecursive = static function ($array, callable $callback = null) use (&$arrayFilterRecursive) { - $array = $callback($array); - - if (\is_object($array) || \is_array($array)) { - foreach ($array as &$value) { - $value = $arrayFilterRecursive($value, $callback); - } - } - - return $array; - }; - - $callback = static function ($item) { - /** - * Remove unserializable properties - */ - if ($item instanceof UTCDateTime) { - return (string)$item; - } - return $item; - }; - - $serverStats = $arrayFilterRecursive($serverStats, $callback); - $collectionStats = $arrayFilterRecursive($collectionStats, $callback); - - return (new DriverStatistic()) - ->setInfo( - 'MongoDB version ' . $serverStats->version . ', Uptime (in days): ' . round( - $serverStats->uptime / 86400, - 1 - ) . "\n For more information see RawData." - ) - ->setSize($collectionStats->size) - ->setData(implode(', ', array_keys($this->itemInstances))) - ->setRawData( - [ - 'serverStatus' => $serverStats, - 'collStats' => $collectionStats, - ] - ); - } - - /** - * @return Collection - */ - protected function getCollection(): Collection - { - return $this->collection; - } - - /** - * Builds the connection URI from the given parameters. - * - * @param string $databaseName - * @return string The connection URI. - */ - protected function buildConnectionURI(string $databaseName): string - { - $databaseName = \urlencode($databaseName); - $servers = $this->getConfig()->getServers(); - $options = $this->getConfig()->getOptions(); - - $protocol = $this->getConfig()->getProtocol(); - $host = $this->getConfig()->getHost(); - $port = $this->getConfig()->getPort(); - $username = $this->getConfig()->getUsername(); - $password = $this->getConfig()->getPassword(); - - if (count($servers) > 0) { - $host = array_reduce( - $servers, - static fn ($carry, $data) => $carry . ($carry === '' ? '' : ',') . $data['host'] . ':' . $data['port'], - '' - ); - $port = false; - } - - return implode( - '', - [ - "{$protocol}://", - $username ?: '', - $password ? ":{$password}" : '', - $username ? '@' : '', - $host, - $port !== 27017 && $port !== false ? ":{$port}" : '', - $databaseName ? "/{$databaseName}" : '', - count($options) > 0 ? '?' . http_build_query($options) : '', - ] - ); - } - - protected function getMongoDbItemKey(ExtendedCacheItemInterface $item): string - { - return $this->getMongoDbKey($item->getEncodedKey()); - } - - protected function getMongoDbKey(string $encodedKey): string - { - return $this->documentPrefix . $encodedKey; - } - - /** - * Checks if a collection name exists on the Mongo database. - * - * @param string $collectionName The collection name to check. - * - * @return bool True if the collection exists, false if not. - */ - protected function collectionExists(string $collectionName): bool - { - foreach ($this->database->listCollections() as $collection) { - if ($collection->getName() === $collectionName) { - return true; - } - } - - return false; - } -} diff --git a/lib/Phpfastcache/Drivers/Mongodb/Item.php b/lib/Phpfastcache/Drivers/Mongodb/Item.php deleted file mode 100644 index 6b590124..00000000 --- a/lib/Phpfastcache/Drivers/Mongodb/Item.php +++ /dev/null @@ -1,30 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Mongodb; - -use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Core\Item\TaggableCacheItemTrait; - -class Item implements ExtendedCacheItemInterface -{ - use TaggableCacheItemTrait; - - protected function getDriverClass(): string - { - return Driver::class; - } -} diff --git a/lib/Phpfastcache/Drivers/Solr/Config.php b/lib/Phpfastcache/Drivers/Solr/Config.php deleted file mode 100644 index 3a1ed786..00000000 --- a/lib/Phpfastcache/Drivers/Solr/Config.php +++ /dev/null @@ -1,210 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Solr; - -use Phpfastcache\Config\ConfigurationOption; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Core\Pool\TaggableCacheItemPoolInterface; -use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException; -use Phpfastcache\Exceptions\PhpfastcacheLogicException; -use Psr\EventDispatcher\EventDispatcherInterface; -use Solarium\Core\Client\Adapter\AdapterInterface; - -class Config extends ConfigurationOption -{ - public const DEFAULT_MAPPING_SCHEMA = [ - Driver::SOLR_DEFAULT_ID_FIELD => Driver::SOLR_DEFAULT_ID_FIELD, - Driver::SOLR_DISCRIMINATOR_FIELD => Driver::SOLR_DISCRIMINATOR_FIELD . '_s', - ExtendedCacheItemPoolInterface::DRIVER_KEY_WRAPPER_INDEX => ExtendedCacheItemPoolInterface::DRIVER_KEY_WRAPPER_INDEX . '_s', - ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX => ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX . '_s', - ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX => ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX . '_s', - ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX => ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX . '_s', - ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX => ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX . '_s', - TaggableCacheItemPoolInterface::DRIVER_TAGS_WRAPPER_INDEX => TaggableCacheItemPoolInterface::DRIVER_TAGS_WRAPPER_INDEX . '_ss', - ]; - protected string $host = '127.0.0.1'; - protected int $port = 8983; - protected string $coreName = 'phpfastcache'; - protected string $endpointName = 'phpfastcache'; - protected string $scheme = 'http'; - protected EventDispatcherInterface $eventDispatcher; - protected string $path = '/'; - protected ?AdapterInterface $adapter = null; - - /** @var array */ - protected array $mappingSchema = self::DEFAULT_MAPPING_SCHEMA; - - public function __construct(array $parameters = []) - { - $this->eventDispatcher = $this->getDefaultEventDispatcher(); - parent::__construct($parameters); - } - - /** - * @return string - */ - public function getHost(): string - { - return $this->host; - } - - /** - * @param string $host - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setHost(string $host): Config - { - return $this->setProperty('host', $host); - } - - /** - * @return int - */ - public function getPort(): int - { - return $this->port; - } - - /** - * @param int $port - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setPort(int $port): Config - { - return $this->setProperty('port', $port); - } - - /** - * @return string - */ - public function getCoreName(): string - { - return $this->coreName; - } - - /** - * @param string $coreName - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setCoreName(string $coreName): Config - { - return $this->setProperty('coreName', $coreName); - } - - /** - * @return string - */ - public function getScheme(): string - { - return $this->scheme; - } - - /** - * @param string $scheme - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setScheme(string $scheme): Config - { - return $this->setProperty('scheme', $scheme); - } - - /** - * @return EventDispatcherInterface - */ - public function getEventDispatcher(): EventDispatcherInterface - { - return $this->eventDispatcher; - } - - /** - * @return EventDispatcherInterface - */ - protected function getDefaultEventDispatcher(): EventDispatcherInterface - { - return new class implements EventDispatcherInterface { - public function dispatch(object $event): object - { - return $event; - } - }; - } - - /** - * @param EventDispatcherInterface $eventDispatcher - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setEventDispatcher(EventDispatcherInterface $eventDispatcher): Config - { - return $this->setProperty('eventDispatcher', $eventDispatcher); - } - - /** - * @return string[] - */ - public function getMappingSchema(): array - { - return $this->mappingSchema; - } - - /** - * @param string[] $mappingSchema - * @return Config - * @throws PhpfastcacheLogicException - * @throws PhpfastcacheInvalidArgumentException - */ - public function setMappingSchema(array $mappingSchema): Config - { - $diff = array_diff(array_keys(self::DEFAULT_MAPPING_SCHEMA), array_keys($mappingSchema)); - if ($diff) { - throw new PhpfastcacheInvalidArgumentException('Missing keys for the solr mapping schema: ' . \implode(', ', $diff)); - } - return $this->setProperty('mappingSchema', $mappingSchema); - } - - /** - * @return string - */ - public function getEndpointName(): string - { - return $this->endpointName; - } - - /** - * @param string $endpointName - * @return Config - * @throws PhpfastcacheLogicException - */ - public function setEndpointName(string $endpointName): Config - { - return $this->setProperty('endpointName', $endpointName); - } - - public function getAdapter(): ?AdapterInterface - { - return $this->adapter; - } - - public function setAdapter(?AdapterInterface $adapter): Config - { - return $this->setProperty('adapter', $adapter); - } -} diff --git a/lib/Phpfastcache/Drivers/Solr/Driver.php b/lib/Phpfastcache/Drivers/Solr/Driver.php deleted file mode 100644 index 3da4df2d..00000000 --- a/lib/Phpfastcache/Drivers/Solr/Driver.php +++ /dev/null @@ -1,360 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Solr; - -use Phpfastcache\Cluster\AggregatablePoolInterface; -use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Core\Pool\TaggableCacheItemPoolTrait; -use Phpfastcache\Entities\DriverStatistic; -use Phpfastcache\Event\EventReferenceParameter; -use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException; -use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException; -use Phpfastcache\Exceptions\PhpfastcacheDriverException; -use Phpfastcache\Exceptions\PhpfastcacheInvalidTypeException; -use Phpfastcache\Exceptions\PhpfastcacheLogicException; -use Solarium\Client as SolariumClient; -use Solarium\Core\Client\Adapter\Curl as SolariumCurlAdapter; -use Solarium\Exception\ExceptionInterface as SolariumExceptionInterface; -use Solarium\QueryType\Select\Result\Document as SolariumDocument; - -/** - * Class Driver - * @property SolariumClient $instance - * @method Config getConfig() - */ -class Driver implements AggregatablePoolInterface -{ - use TaggableCacheItemPoolTrait; - - public const MINIMUM_SOLARIUM_VERSION = '6.1.0'; - - public const SOLR_DEFAULT_ID_FIELD = 'id'; - - public const SOLR_DISCRIMINATOR_FIELD = 'type'; - - public const SOLR_DISCRIMINATOR_VALUE = '_pfc_'; - - /** - * Copy of configuration entry for performance optimization - * @var string[] - */ - protected array $mappingSchema = []; - - /** - * @return bool - * @throws PhpfastcacheDriverCheckException - */ - public function driverCheck(): bool - { - if (!\class_exists(SolariumClient::class)) { - throw new PhpfastcacheDriverCheckException( - \sprintf( - 'Phpfastcache needs Solarium %s or greater to be installed', - self::MINIMUM_SOLARIUM_VERSION - ) - ); - } - - return true; - } - - /** - * @return bool - * @throws PhpfastcacheDriverConnectException - */ - protected function driverConnect(): bool - { - $this->mappingSchema = $this->getConfig()->getMappingSchema(); - - $endpoint = [ - 'endpoint' => [ - $this->getConfig()->getEndpointName() => [ - 'scheme' => $this->getConfig()->getScheme(), - 'host' => $this->getConfig()->getHost(), - 'port' => $this->getConfig()->getPort(), - 'path' => $this->getConfig()->getPath(), - 'core' => $this->getConfig()->getCoreName(), - ] - ] - ]; - - $this->eventManager->dispatch(Event::SOLR_BUILD_ENDPOINT, $this, new EventReferenceParameter($endpoint)); - - $this->instance = new SolariumClient( - $this->getConfig()->getAdapter() ?: new SolariumCurlAdapter(), - $this->getConfig()->getEventDispatcher(), - $endpoint - ); - - try { - return $this->instance->ping($this->instance->createPing())->getStatus() === 0; - } catch (SolariumExceptionInterface $e) { - throw new PhpfastcacheDriverConnectException($e->getMessage(), 0, $e); - } - } - - /** - * @param ExtendedCacheItemInterface $item - * @return bool - * @throws PhpfastcacheLogicException - */ - protected function driverWrite(ExtendedCacheItemInterface $item): bool - { - $update = $this->instance->createUpdate(); - - $doc = $update->createDocument(); - $doc->{$this->getSolrField(self::SOLR_DEFAULT_ID_FIELD)} = $item->getEncodedKey(); - $doc->{$this->getSolrField(self::SOLR_DISCRIMINATOR_FIELD)} = self::SOLR_DISCRIMINATOR_VALUE; - $doc->{$this->getSolrField(self::DRIVER_KEY_WRAPPER_INDEX)} = $item->getKey(); - $doc->{$this->getSolrField(self::DRIVER_DATA_WRAPPER_INDEX)} = $this->encode($item->_getData()); - $doc->{$this->getSolrField(self::DRIVER_TAGS_WRAPPER_INDEX)} = $item->getTags(); - $doc->{$this->getSolrField(self::DRIVER_EDATE_WRAPPER_INDEX)} = $item->getExpirationDate()->format(\DateTimeInterface::ATOM); - - if ($this->getConfig()->isItemDetailedDate()) { - $doc->{$this->getSolrField(self::DRIVER_MDATE_WRAPPER_INDEX)} = $item->getModificationDate()->format(\DateTimeInterface::ATOM); - $doc->{$this->getSolrField(self::DRIVER_CDATE_WRAPPER_INDEX)} = $item->getCreationDate()->format(\DateTimeInterface::ATOM); - } - - $update->addDocument($doc, true); - $update->addCommit(); - - return $this->instance->update($update)->getStatus() === 0; - } - - /** - * @param ExtendedCacheItemInterface $item - * @return ?array - * @throws \Exception - */ - protected function driverRead(ExtendedCacheItemInterface $item): ?array - { - $query = $this->instance->createSelect() - ->setQuery($this->getSolrField(self::SOLR_DEFAULT_ID_FIELD) . ':' . $item->getEncodedKey()) - ->setRows(1); - - $results = $this->instance->execute($query); - - if ($results instanceof \IteratorAggregate) { - $document = $results->getIterator()[0] ?? null; - - if ($document instanceof SolariumDocument) { - return $this->decodeDocument($document); - } - } - - return null; - } - - /** - * @param ExtendedCacheItemInterface ...$items - * @return array> - * @throws \Exception - */ - protected function driverReadMultiple(ExtendedCacheItemInterface ...$items): array - { - $query = $this->instance->createSelect() - ->setQuery( - implode( - ' OR ', - array_map( - fn($key) => "{$this->getSolrField($this::SOLR_DEFAULT_ID_FIELD)}:{$key}", - $this->getKeys($items, true) - ) - ) - ) - ->setRows(count($items)); - - $results = $this->instance->execute($query); - - if ($results instanceof \IteratorAggregate) { - $driverArrays = []; - foreach ($results->getIterator() as $document) { - $driverArrays[$document->getFields()[$this->getSolrField(self::DRIVER_KEY_WRAPPER_INDEX)]] = $this->decodeDocument($document); - } - - return $driverArrays; - } - - return []; - } - - /** - * @return array - * @throws PhpfastcacheInvalidTypeException - */ - protected function driverReadAllKeys(string $pattern = ''): iterable - { - $query = $this->instance->createSelect() - ->setQuery( - sprintf( - '%s:%s AND %s:%s', - $this->getSolrField(self::DRIVER_KEY_WRAPPER_INDEX), - $pattern === '' ? '*' : $pattern, - $this->getSolrField($this::SOLR_DISCRIMINATOR_FIELD), - $this::SOLR_DISCRIMINATOR_VALUE - ) - ) - ->setRows(ExtendedCacheItemPoolInterface::MAX_ALL_KEYS_COUNT); - - /** @var \Solarium\QueryType\Select\Result\Result $results */ - $results = $this->instance->execute($query); - - return array_map( - fn(SolariumDocument $document) => $document->getFields()[$this->getSolrField(self::DRIVER_KEY_WRAPPER_INDEX)], - $results->getIterator()->getArrayCopy() - ); - } - - - /** - * @param SolariumDocument $document - * @return array - * @throws \Exception - */ - protected function decodeDocument(SolariumDocument $document): array - { - $fields = $document->getFields(); - $key = $fields[$this->getSolrField(self::DRIVER_KEY_WRAPPER_INDEX)]; - - if (\is_array($key)) { - throw new PhpfastcacheInvalidTypeException( - 'Your Solr core seems to be misconfigured, please check the Phpfastcache wiki to setup the expected schema: - https://github.com/PHPSocialNetwork/phpfastcache/wiki/%5BV9.1%CB%96%5D-Configuring-a-Solr-driver' - ); - } - - $value = [ - self::DRIVER_KEY_WRAPPER_INDEX => $key, - self::DRIVER_TAGS_WRAPPER_INDEX => $fields[$this->getSolrField(self::DRIVER_TAGS_WRAPPER_INDEX)] ?? [], - self::DRIVER_DATA_WRAPPER_INDEX => $this->unserialize( - $fields[$this->getSolrField(self::DRIVER_DATA_WRAPPER_INDEX)], - ), - ]; - - $eDate = $fields[$this->getSolrField(self::DRIVER_EDATE_WRAPPER_INDEX)]; - - $value[ExtendedCacheItemPoolInterface::DRIVER_EDATE_WRAPPER_INDEX] = new \DateTime($eDate); - - if ($this->getConfig()->isItemDetailedDate()) { - $cDate = $fields[$this->getSolrField(self::DRIVER_CDATE_WRAPPER_INDEX)]; - if (!empty($cDate)) { - $value[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = new \DateTime($cDate); - } - - $mDate = $fields[$this->getSolrField(self::DRIVER_MDATE_WRAPPER_INDEX)]; - if (!empty($mDate)) { - $value[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = new \DateTime($mDate); - } - } - - return $value; - } - - - /** - * @param string $key - * @param string $encodedKey - * @return bool - */ - protected function driverDelete(string $key, string $encodedKey): bool - { - $update = $this->instance->createUpdate(); - - $update->addDeleteQuery($this->getSolrField(self::SOLR_DEFAULT_ID_FIELD) . ':' . $encodedKey); - $update->addDeleteQuery($this->getSolrField(self::SOLR_DISCRIMINATOR_FIELD) . ':' . self::SOLR_DISCRIMINATOR_VALUE); - $update->addCommit(); - - return $this->instance->update($update)->getStatus() === 0; - } - - /** - * @return bool - * @throws PhpfastcacheDriverException - */ - protected function driverClear(): bool - { - // get an update query instance - $update = $this->instance->createUpdate(); - $update->addDeleteQuery($this->getSolrField(self::SOLR_DISCRIMINATOR_FIELD) . ':' . self::SOLR_DISCRIMINATOR_VALUE); - $update->addCommit(); - - return $this->instance->update($update)->getStatus() === 0; - } - - /** - * @param string $pfcField - * @return string - */ - protected function getSolrField(string $pfcField): string - { - return $this->mappingSchema[$pfcField]; - } - - public function getStats(): DriverStatistic - { - /** - * Solr "phpfastcache" core info - */ - $coreAdminQuery = $this->instance->createCoreAdmin(); - $statusAction = $coreAdminQuery->createStatus(); - $coreAdminQuery->setAction($statusAction); - $response = $this->instance->coreAdmin($coreAdminQuery); - $coreServerInfo = $response->getData()['status'][$this->getConfig()->getCoreName()]; - - /** - * Unfortunately Solarium does not offer - * an API to query the admin info system :( - */ - $adminSystemInfoUrl = $this->getConfig()->getScheme() - . '://' - . $this->getConfig()->getHost() - . ':' - . $this->getConfig()->getPort() - . rtrim($this->getConfig()->getPath(), '/') - . '/solr/admin/info/system'; - - if (($content = @\file_get_contents($adminSystemInfoUrl)) !== false) { - try { - $serverSystemInfo = \json_decode($content, true, 512, \JSON_THROW_ON_ERROR); - } catch (\JsonException) { - $serverSystemInfo = []; - } - } - - $version = 'Unknown version'; - if (method_exists($this->instance, 'getVersion')) { - $version = $this->instance::getVersion(); - } elseif (defined($this->instance::class . '::VERSION')) { - $version = constant($this->instance::class . '::VERSION'); - } - - return (new DriverStatistic()) - ->setData(implode(', ', array_keys($this->itemInstances))) - ->setInfo(sprintf( - 'Solarium %s and Solr %s for %s %s. %d document(s) stored in the "%s" core', - $version, - $serverSystemInfo['lucene']['solr-spec-version'] ?? '[unknown SOLR version]', - $serverSystemInfo['system']['name'] ?? '[unknown OS]', - $serverSystemInfo['system']['version'] ?? '[unknown OS version]', - $coreServerInfo['index']['numDocs'] ?? 0, - $this->getConfig()->getCoreName() - )) - ->setRawData($coreServerInfo) - ->setSize($coreServerInfo['index']['sizeInBytes'] ?? 0); - } -} diff --git a/lib/Phpfastcache/Drivers/Solr/Event.php b/lib/Phpfastcache/Drivers/Solr/Event.php deleted file mode 100644 index d7247d27..00000000 --- a/lib/Phpfastcache/Drivers/Solr/Event.php +++ /dev/null @@ -1,8 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -declare(strict_types=1); - -namespace Phpfastcache\Drivers\Solr; - -use Phpfastcache\Core\Item\ExtendedCacheItemInterface; -use Phpfastcache\Core\Item\TaggableCacheItemTrait; - -class Item implements ExtendedCacheItemInterface -{ - use TaggableCacheItemTrait; - - protected function getDriverClass(): string - { - return Driver::class; - } -} diff --git a/phpstan.neon b/phpstan.neon index bd391790..e1ea2a7d 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -16,10 +16,6 @@ parameters: - message: '#Cannot call method getPayload\(\) on int#' path: lib/Phpfastcache/Drivers/Predis/Driver.php - # Issue in arangodb/arangodb-php => https://github.com/arangodb/arangodb-php/issues/293 - - - message: '#Cannot assign offset (.*) to string|Offset (.*) on string#' - path: lib/Phpfastcache/Drivers/Arangodb/Driver.php # See https://github.com/phpstan/phpstan/issues/10315 - message: '#Dead catch - Phpfastcache\\Exceptions\\PhpfastcacheUnsupportedMethodException is never thrown in the try block.#' diff --git a/tests/cases/Solr.test.php b/tests/cases/Solr.test.php deleted file mode 100644 index 059fc430..00000000 --- a/tests/cases/Solr.test.php +++ /dev/null @@ -1,68 +0,0 @@ - - * @author Contributors https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors - */ - -use Phpfastcache\CacheManager; -use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface; -use Phpfastcache\Event\EventReferenceParameter; -use Phpfastcache\EventManager; -use Phpfastcache\Tests\Helper\TestHelper; -use Phpfastcache\Drivers\Solr\Config as SolrConfig; - -chdir(__DIR__); -require_once __DIR__ . '/../../vendor/autoload.php'; -$testHelper = new TestHelper('Solr driver'); - -/** @var SolrConfig $solrConfig */ -$solrConfig = $testHelper->preConfigure(new SolrConfig()); -$solrConfig->setCoreName('phpfastcache'); // Optional: Default value -$solrConfig->setPort(8983); // Optional: Default value -$solrConfig->setHost('127.0.0.1'); // Optional: Default value -$solrConfig->setPath('/'); // Optional: Default value -$solrConfig->setScheme('http'); // Optional: Default value - - -/** - * Optional: - * - * You can change the mapping schema used by Phpfastcache. - * The keys are the Phpfastcache internal index. All required. - * The values are the name of your Solr schema. - */ -$solrConfig->setMappingSchema($solrConfig::DEFAULT_MAPPING_SCHEMA); - -/** - * Optional: - * - * You can change the PSR-14 event dispatcher service used (and required) by solarium, by your own one. - */ -// $solrConfig->setEventDispatcher($yourEventDispatcher); - -/** - * Test of custom events - */ -$onSolrBuildEndpointCalled = false; -EventManager::getInstance()->onSolrBuildEndpoint(static function () use (&$onSolrBuildEndpointCalled, $testHelper){ - $testHelper->assertPass('Event "onSolrBuildEndpoint" has been called.'); - $onSolrBuildEndpointCalled = true; -}); - -$cacheInstance = CacheManager::getInstance('Solr', $solrConfig); - -if(!$onSolrBuildEndpointCalled) { - $testHelper->assertFail('Event "onSolrBuildEndpoint" has NOT been called.'); -} - -$testHelper->runCRUDTests($cacheInstance); - -$testHelper->terminateTest();