Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,6 @@ services:
- couchdb
- mongodb

before_script:
- |
if [[ $TRAVIS_PHP_VERSION = "hhv"* ]]; then
cat bin/ci/hhvm_phpfastcache.ini >> /etc/hhvm/php.ini
else
pecl channel-update pecl.php.net;
yes | pecl install -f mongodb-stable;
yes | pecl install -f memcached;
yes | pecl install -f apcu-stable || true;
phpenv config-add bin/ci/php_phpfastcache.ini;
fi
- sleep 15
- mongo pfc_test --eval 'db.createUser({user:"travis",pwd:"test",roles:["readWrite"]});'

php:
- 7.3
- 7.4
Expand All @@ -51,6 +37,21 @@ jobs:
php: 7.3
- dist: bionic
php: 7.4

before_install:
- |
if [[ $TRAVIS_PHP_VERSION = "hhv"* ]]; then
cat bin/ci/hhvm_phpfastcache.ini >> /etc/hhvm/php.ini
else
pecl channel-update pecl.php.net;
yes | pecl install -f mongodb-stable;
yes | pecl install -f memcached;
yes | pecl install -f apcu-stable || true;
phpenv config-add bin/ci/php_phpfastcache.ini;
fi
- sleep 15
- mongo pfc_test --eval 'db.createUser({user:"travis",pwd:"test",roles:["readWrite"]});'

install:
- ./bin/ci/install_dependencies.sh

Expand Down
4 changes: 2 additions & 2 deletions bin/ci/install_dependencies.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env bash

composer self-update;
composer install --ignore-platform-reqs;
composer require "phpfastcache/couchdb:~1.0.0" "phpfastcache/phpssdb:~1.0.0" "predis/predis:~1.1.0" "mongodb/mongodb:^1.1" --ignore-platform-reqs;
composer install;
composer require "phpfastcache/couchdb:~1.0.0" "phpfastcache/phpssdb:~1.0.0" "predis/predis:~1.1.0" "mongodb/mongodb:^1.9";
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
"ext-wincache": "*",
"ext-leveldb": "*",
"ext-couchbase": "*",
"predis/predis": "~1.1.0",
"mongodb/mongodb": "^1.1",
"predis/predis": "^1.1",
"mongodb/mongodb": "^1.9",
"phpfastcache/phpssdb": "~1.0.0",
"phpfastcache/couchdb": "~1.0.0"
},
Expand Down
2 changes: 1 addition & 1 deletion lib/Phpfastcache/Drivers/Couchdb/Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function getStats(): DriverStatistic
$info = $this->instance->getDatabaseInfo();

return (new DriverStatistic())
->setSize($info['sizes']['active'])
->setSize($info['sizes']['active'] ?? 0)
->setRawData($info)
->setData(implode(', ', array_keys($this->itemInstances)))
->setInfo('Couchdb version ' . $this->instance->getVersion() . "\n For more information see RawData.");
Expand Down
4 changes: 2 additions & 2 deletions lib/Phpfastcache/Drivers/Mongodb/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class Config extends ConfigurationOption
/**
* @var string
*/
protected $collectionName = 'Cache';
protected $collectionName = 'phpfastcache';

/**
* @var string
Expand Down Expand Up @@ -273,4 +273,4 @@ public function setProtocol(string $protocol): self
$this->protocol = $protocol;
return $this;
}
}
}
40 changes: 23 additions & 17 deletions lib/Phpfastcache/Drivers/Mongodb/Driver.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
namespace Phpfastcache\Drivers\Mongodb;

use DateTime;
use Exception;
use LogicException;
use MongoClient;
use MongoDB\{BSON\Binary, BSON\UTCDateTime, Client, Collection, Database, DeleteResult, Driver\Command, Driver\Exception\Exception as MongoDBException, Driver\Manager};
Expand Down Expand Up @@ -75,7 +76,7 @@ public function driverCheck(): bool
public function getStats(): DriverStatistic
{
$serverStats = $this->instance->getManager()->executeCommand(
'phpFastCache',
$this->getConfig()->getDatabaseName(),
new Command(
[
'serverStatus' => 1,
Expand All @@ -87,10 +88,10 @@ public function getStats(): DriverStatistic
)->toArray()[0];

$collectionStats = $this->instance->getManager()->executeCommand(
'phpFastCache',
$this->getConfig()->getDatabaseName(),
new Command(
[
'collStats' => (isset($this->getConfig()['collectionName']) ? $this->getConfig()['collectionName'] : 'Cache'),
'collStats' => $this->getConfig()->getCollectionName(),
'verbose' => true,
]
)
Expand Down Expand Up @@ -146,25 +147,19 @@ public function getStats(): DriverStatistic
*/
protected function driverRead(CacheItemInterface $item)
{
$document = $this->getCollection()->findOne(['_id' => $item->getEncodedKey()]);
$document = $this->getCollection()->findOne(['_id' => $this->getMongoDbItemKey($item)]);

if ($document) {
$return = [
self::DRIVER_DATA_WRAPPER_INDEX => $this->decode($document[self::DRIVER_DATA_WRAPPER_INDEX]->getData()),
self::DRIVER_TAGS_WRAPPER_INDEX => $this->decode($document[self::DRIVER_TAGS_WRAPPER_INDEX]->getData()),
self::DRIVER_EDATE_WRAPPER_INDEX => (new DateTime())->setTimestamp($document[self::DRIVER_EDATE_WRAPPER_INDEX]->toDateTime()->getTimestamp()),
self::DRIVER_EDATE_WRAPPER_INDEX => $document[self::DRIVER_EDATE_WRAPPER_INDEX]->toDateTime(),
];

if (!empty($this->getConfig()->isItemDetailedDate())) {
$return += [
self::DRIVER_MDATE_WRAPPER_INDEX => (new DateTime())->setTimestamp(
$document[self::DRIVER_MDATE_WRAPPER_INDEX]->toDateTime()
->getTimestamp()
),
self::DRIVER_CDATE_WRAPPER_INDEX => (new DateTime())->setTimestamp(
$document[self::DRIVER_CDATE_WRAPPER_INDEX]->toDateTime()
->getTimestamp()
),
self::DRIVER_MDATE_WRAPPER_INDEX => $document[self::DRIVER_MDATE_WRAPPER_INDEX]->toDateTime(),
self::DRIVER_CDATE_WRAPPER_INDEX => $document[self::DRIVER_CDATE_WRAPPER_INDEX]->toDateTime(),
];
}

Expand Down Expand Up @@ -196,6 +191,7 @@ protected function driverWrite(CacheItemInterface $item): bool
if ($item instanceof Item) {
try {
$set = [
self::DRIVER_KEY_WRAPPER_INDEX => $item->getKey(),
self::DRIVER_DATA_WRAPPER_INDEX => new Binary($this->encode($item->get()), Binary::TYPE_GENERIC),
self::DRIVER_TAGS_WRAPPER_INDEX => new Binary($this->encode($item->getTags()), Binary::TYPE_GENERIC),
self::DRIVER_EDATE_WRAPPER_INDEX => ($item->getTtl() > 0 ? new UTCDateTime((time() + $item->getTtl()) * 1000) : new UTCDateTime(time() * 1000)),
Expand All @@ -214,7 +210,7 @@ protected function driverWrite(CacheItemInterface $item): bool
];
}
$result = (array)$this->getCollection()->updateOne(
['_id' => $item->getEncodedKey()],
['_id' => $this->getMongoDbItemKey($item)],
[
'$set' => $set,
],
Expand Down Expand Up @@ -244,7 +240,7 @@ protected function driverDelete(CacheItemInterface $item): bool
/**
* @var DeleteResult $deletionResult
*/
$deletionResult = $this->getCollection()->deleteOne(['_id' => $item->getEncodedKey()]);
$deletionResult = $this->getCollection()->deleteOne(['_id' => $this->getMongoDbItemKey($item)]);

return $deletionResult->isAcknowledged();
}
Expand All @@ -257,7 +253,11 @@ protected function driverDelete(CacheItemInterface $item): bool
*/
protected function driverClear(): bool
{
return $this->collection->deleteMany([])->isAcknowledged();
try {
return $this->collection->deleteMany([])->isAcknowledged();
} catch (MongoDBException $e) {
throw new PhpfastcacheDriverException('Got error while trying to empty the collection: ' . $e->getMessage(), 0, $e);
}
}

/**
Expand Down Expand Up @@ -294,8 +294,9 @@ protected function driverConnect(): bool
* @param string $databaseName
* @return string The connection URI.
*/
protected function buildConnectionURI($databaseName = ''): string
protected function buildConnectionURI(string $databaseName): string
{
$databaseName = \urlencode($databaseName);
$servers = $this->getConfig()->getServers();
$options = $this->getConfig()->getOptions();

Expand Down Expand Up @@ -332,6 +333,11 @@ static function ($carry, $data) {
);
}

protected function getMongoDbItemKey(CacheItemInterface $item)
{
return 'pfc_' . $item->getEncodedKey();
}

/********************
*
* PSR-6 Extended Methods
Expand Down
70 changes: 8 additions & 62 deletions tests/Mongodb.test.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,78 +8,24 @@
use Phpfastcache\CacheManager;
use Phpfastcache\Drivers\Mongodb\Config;
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
use Phpfastcache\Exceptions\phpFastCacheDriverException;
use Phpfastcache\Tests\Helper\TestHelper;

chdir(__DIR__);
require_once __DIR__ . '/../vendor/autoload.php';
$testHelper = new TestHelper('Mongodb driver');
$config = new Config();
$config->setItemDetailedDate(true)
->setDatabaseName('pfc_test')
->setCollectionName('pfc_' . str_pad('0', 3, random_int(1, 100)))
->setUsername('travis')
->setPassword('test');

try{
$cacheInstance = CacheManager::getInstance('Mongodb', new Config([
'databaseName' => 'pfc_test',
'username' => 'travis',
'password' => 'test',
]));
$cacheInstance = CacheManager::getInstance('Mongodb', $config);
}catch(PhpfastcacheDriverCheckException $exception){
$testHelper->exceptionHandler($exception);
$testHelper->terminateTest();
}


$cacheKey = str_shuffle(uniqid('pfc', true));
$cacheValue = str_shuffle(uniqid('pfc', true));

try{
$item = $cacheInstance->getItem($cacheKey);
$item->set($cacheValue)->expiresAfter(300);
$cacheInstance->save($item);
$testHelper->assertPass('Successfully saved a new cache item into Mongodb server');
}catch(phpFastCacheDriverException $e){
$testHelper->assertFail('Failed to save a new cache item into Mongodb server with exception: ' . $e->getMessage());
}

try{
unset($item);
$cacheInstance->detachAllItems();
$item = $cacheInstance->getItem($cacheKey);

if($item->get() === $cacheValue){
$testHelper->assertPass('Getter returned expected value: ' . $cacheValue);
}else{
$testHelper->assertFail('Getter returned unexpected value, expecting "' . $cacheValue . '", got "' . $item->get() . '"');
}
}catch(phpFastCacheDriverException $e){
$testHelper->assertFail('Failed to save a new cache item into Mongodb server with exception: ' . $e->getMessage());
}

try{
unset($item);
$cacheInstance->detachAllItems();
$cacheInstance->clear();
$item = $cacheInstance->getItem($cacheKey);

if(!$item->isHit()){
$testHelper->assertPass('Successfully cleared the Mongodb server, no cache item found');
}else{
$testHelper->assertFail('Failed to clear the Mongodb server, a cache item has been found');
}
}catch(phpFastCacheDriverException $e){
$testHelper->assertFail('Failed to clear the Mongodb server with exception: ' . $e->getMessage());
}

try{
$item = $cacheInstance->getItem($cacheKey);
$item->set($cacheValue)->expiresAfter(300);
$cacheInstance->save($item);

if($cacheInstance->deleteItem($item->getKey())){
$testHelper->assertPass('Deleter successfully removed the item from cache');
}else{
$testHelper->assertFail('Deleter failed to remove the item from cache');
}
}catch(phpFastCacheDriverException $e){
$testHelper->assertFail('Failed to remove a cache item from Mongodb server with exception: ' . $e->getMessage());
}

$testHelper->runCRUDTests($cacheInstance);
$testHelper->terminateTest();
Loading