Skip to content

Commit 480fa38

Browse files
authored
Merge pull request #757 from Geolim4/master
Fixed inconsistent behavior of "defaultKeyHashFunction" and "defaultFileNameHashFunction" + added tests for them
2 parents 6c6956c + 92c8198 commit 480fa38

File tree

10 files changed

+110
-17
lines changed

10 files changed

+110
-17
lines changed

lib/Phpfastcache/CacheManager.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,9 @@ public static function getInstance(string $driver, ?ConfigurationOptionInterface
177177
$config = self::validateConfig($config);
178178
$driver = self::standardizeDriverName($driver);
179179

180-
$instanceId = $instanceId ?: md5($driver . serialize($config->toArray()));
180+
$instanceId = $instanceId ?: md5($driver . serialize(\array_filter($config->toArray(), static function ($val){
181+
return !\is_callable($val);
182+
})));
181183

182184
if (!isset(self::$instances[$instanceId])) {
183185
self::$badPracticeOmeter[$driver] = 1;

lib/Phpfastcache/Config/ConfigurationOption.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ public function getDefaultKeyHashFunction()
232232
*/
233233
public function setDefaultKeyHashFunction($defaultKeyHashFunction): self
234234
{
235-
if (!\is_callable($defaultKeyHashFunction) && (\is_string($defaultKeyHashFunction) && !\function_exists($defaultKeyHashFunction))) {
235+
if ($defaultKeyHashFunction && !\is_callable($defaultKeyHashFunction) && (\is_string($defaultKeyHashFunction) && !\function_exists($defaultKeyHashFunction))) {
236236
throw new PhpfastcacheInvalidConfigurationException('defaultKeyHashFunction must be a valid function name string');
237237
}
238238
$this->defaultKeyHashFunction = $defaultKeyHashFunction;

lib/Phpfastcache/Core/Item/ExtendedCacheItemInterface.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ interface ExtendedCacheItemInterface extends CacheItemInterface, EventManagerDis
3434

3535
/**
3636
* Returns the encoded key for the current cache item.
37-
* Usually as a MD5 hash
37+
* Is a MD5 (default),SHA1,SHA256 hash if "defaultKeyHashFunction" config option is configured
38+
* Else return the plain cache item key "defaultKeyHashFunction" config option is emptied
3839
*
3940
* @return string
4041
* The encoded key string for this cache item.

lib/Phpfastcache/Core/Item/ItemExtendedTrait.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ public function getEncodedKey(): string
9090
if ($keyHashFunction) {
9191
$this->encodedKey = $keyHashFunction($this->getKey());
9292
} else {
93-
$this->encodedKey = \md5($this->getKey());
93+
$this->encodedKey = $this->getKey();
9494
}
9595
}
9696

lib/Phpfastcache/Core/Pool/DriverBaseTrait.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ public static function getConfigClass(): string
130130
public function driverPreWrap(ExtendedCacheItemInterface $item): array
131131
{
132132
$wrap = [
133+
self::DRIVER_KEY_WRAPPER_INDEX => $item->getKey(), // Stored but not really used, allow you to quickly identify the cache key
133134
self::DRIVER_DATA_WRAPPER_INDEX => $item->get(),
134135
self::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
135136
self::DRIVER_EDATE_WRAPPER_INDEX => $item->getExpirationDate(),

lib/Phpfastcache/Core/Pool/ExtendedCacheItemPoolInterface.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ interface ExtendedCacheItemPoolInterface extends CacheItemPoolInterface, EventMa
4646

4747
public const DRIVER_CONNECT_FAILURE = '%s failed to connect with the following error message: "%s" line %d in %s';
4848

49+
public const DRIVER_KEY_WRAPPER_INDEX = 'k';
50+
4951
public const DRIVER_DATA_WRAPPER_INDEX = 'd';
5052

5153
/**

lib/Phpfastcache/Drivers/Files/Driver.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
* @package phpFastCache\Drivers
3131
* @property Config $config Config object
3232
* @method Config getConfig() Return the config object
33+
*
34+
* Important NOTE:
35+
* We are using getKey instead of getEncodedKey since this backend create filename that are
36+
* managed by defaultFileNameHashFunction and not defaultKeyHashFunction
3337
*/
3438
class Driver implements ExtendedCacheItemPoolInterface, AggregatablePoolInterface
3539
{
@@ -74,7 +78,7 @@ protected function driverRead(CacheItemInterface $item)
7478
* Check for Cross-Driver type confusion
7579
*/
7680
$file_path = $this->getFilePath($item->getKey(), true);
77-
if (!file_exists($file_path)) {
81+
if (!\file_exists($file_path)) {
7882
return null;
7983
}
8084

@@ -122,11 +126,11 @@ protected function driverDelete(CacheItemInterface $item): bool
122126
*/
123127
if ($item instanceof Item) {
124128
$file_path = $this->getFilePath($item->getKey(), true);
125-
if (file_exists($file_path) && @unlink($file_path)) {
126-
clearstatcache(true, $file_path);
127-
$dir = dirname($file_path);
129+
if (\file_exists($file_path) && @\unlink($file_path)) {
130+
\clearstatcache(true, $file_path);
131+
$dir = \dirname($file_path);
128132
if (!(new FilesystemIterator($dir))->valid()) {
129-
rmdir($dir);
133+
\rmdir($dir);
130134
}
131135
return true;
132136
}
@@ -139,6 +143,7 @@ protected function driverDelete(CacheItemInterface $item): bool
139143

140144
/**
141145
* @return bool
146+
* @throws \Phpfastcache\Exceptions\PhpfastcacheIOException
142147
*/
143148
protected function driverClear(): bool
144149
{

lib/Phpfastcache/Drivers/Sqlite/Driver.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -115,21 +115,21 @@ protected function driverConnect(): bool
115115
protected function driverRead(CacheItemInterface $item)
116116
{
117117
try {
118-
$stm = $this->getDb($item->getKey())
118+
$stm = $this->getDb($item->getEncodedKey())
119119
->prepare("SELECT * FROM `caching` WHERE `keyword`=:keyword LIMIT 1");
120120
$stm->execute(
121121
[
122-
':keyword' => $item->getKey(),
122+
':keyword' => $item->getEncodedKey(),
123123
]
124124
);
125125
$row = $stm->fetch(PDO::FETCH_ASSOC);
126126
} catch (PDOException $e) {
127127
try {
128-
$stm = $this->getDb($item->getKey(), true)
128+
$stm = $this->getDb($item->getEncodedKey(), true)
129129
->prepare("SELECT * FROM `caching` WHERE `keyword`=:keyword LIMIT 1");
130130
$stm->execute(
131131
[
132-
':keyword' => $item->getKey(),
132+
':keyword' => $item->getEncodedKey(),
133133
]
134134
);
135135
$row = $stm->fetch(PDO::FETCH_ASSOC);
@@ -301,11 +301,11 @@ protected function driverWrite(CacheItemInterface $item): bool
301301
*/
302302
if ($item instanceof Item) {
303303
try {
304-
$stm = $this->getDb($item->getKey())
304+
$stm = $this->getDb($item->getEncodedKey())
305305
->prepare("INSERT OR REPLACE INTO `caching` (`keyword`,`object`,`exp`) values(:keyword,:object,:exp)");
306306
$stm->execute(
307307
[
308-
':keyword' => $item->getKey(),
308+
':keyword' => $item->getEncodedKey(),
309309
':object' => $this->encode($this->driverPreWrap($item)),
310310
':exp' => $item->getExpirationDate()->getTimestamp(),
311311
]
@@ -332,12 +332,12 @@ protected function driverDelete(CacheItemInterface $item): bool
332332
*/
333333
if ($item instanceof Item) {
334334
try {
335-
$stm = $this->getDb($item->getKey())
335+
$stm = $this->getDb($item->getEncodedKey())
336336
->prepare("DELETE FROM `caching` WHERE (`exp` <= :U) OR (`keyword`=:keyword) ");
337337

338338
return $stm->execute(
339339
[
340-
':keyword' => $item->getKey(),
340+
':keyword' => $item->getEncodedKey(),
341341
':U' => time(),
342342
]
343343
);
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
3+
/**
4+
* @author Khoa Bui (khoaofgod) <[email protected]> https://www.phpfastcache.com
5+
* @author Georges.L (Geolim4) <[email protected]>
6+
*/
7+
8+
use Phpfastcache\CacheManager;
9+
use Phpfastcache\Config\ConfigurationOption;
10+
use Phpfastcache\Core\Pool\ExtendedCacheItemPoolInterface;
11+
use Phpfastcache\Drivers\Files\Driver;
12+
use Phpfastcache\EventManager;
13+
use Phpfastcache\Helper\TestHelper;
14+
15+
chdir(__DIR__);
16+
require_once __DIR__ . '/../vendor/autoload.php';
17+
$testHelper = new TestHelper('Custom filename function');
18+
$driverInstance = CacheManager::getInstance(
19+
'Files',
20+
new ConfigurationOption(
21+
[
22+
'defaultFileNameHashFunction' => static function (string $str) {
23+
return hash('sha256', $str);
24+
}
25+
]
26+
)
27+
);
28+
29+
$testPasses = false;
30+
EventManager::getInstance()->onCacheWriteFileOnDisk(
31+
static function (ExtendedCacheItemPoolInterface $itemPool, $file) use ($driverInstance, &$testPasses) {
32+
/** @var $driverInstance Driver */
33+
$testPasses = strlen(basename($file, '.' . $driverInstance->getConfig()->getCacheFileExtension())) === 64;
34+
}
35+
);
36+
37+
$item = $driverInstance->getItem('TestCustomDefaultFileNameFunction');
38+
$item->set(bin2hex(random_bytes(random_int(10, 100))));
39+
$driverInstance->save($item);
40+
41+
if ($testPasses) {
42+
$testHelper->printPassText('Custom filename function returned expected hash length');
43+
}else{
44+
$testHelper->printFailText('Custom filename function did not returned expected hash length');
45+
}
46+
47+
$testHelper->terminateTest();
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
/**
4+
* @author Khoa Bui (khoaofgod) <[email protected]> https://www.phpfastcache.com
5+
* @author Georges.L (Geolim4) <[email protected]>
6+
*/
7+
8+
use Phpfastcache\CacheManager;
9+
use Phpfastcache\Config\ConfigurationOption;
10+
use Phpfastcache\Helper\TestHelper;
11+
12+
chdir(__DIR__);
13+
require_once __DIR__ . '/../vendor/autoload.php';
14+
$testHelper = new TestHelper('Custom key hash function');
15+
$driverInstance = CacheManager::getInstance(
16+
'sqlite',
17+
new ConfigurationOption(
18+
[
19+
'defaultKeyHashFunction' => static function (string $str) {
20+
return hash('sha256', $str);
21+
}
22+
]
23+
)
24+
);
25+
$item = $driverInstance->getItem('TestCustomDefaultKeyHashFunction');
26+
$item->set(bin2hex(random_bytes(random_int(10, 100))));
27+
$driverInstance->save($item);
28+
29+
if (strlen($item->getEncodedKey()) === 64) {
30+
$testHelper->printPassText('Custom key hash function returned expected hash length');
31+
} else {
32+
$testHelper->printFailText('Custom key hash function did not returned expected hash length');
33+
}
34+
35+
$testHelper->terminateTest();

0 commit comments

Comments
 (0)