Skip to content

Commit 488ace9

Browse files
authored
refactor: fix various phpstan errors in Cache (#9610)
1 parent 764cd55 commit 488ace9

34 files changed

+346
-637
lines changed

app/Config/Cache.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ class Cache extends BaseConfig
7878
* Your file storage preferences can be specified below, if you are using
7979
* the File driver.
8080
*
81-
* @var array<string, int|string|null>
81+
* @var array{storePath?: string, mode?: int}
8282
*/
8383
public array $file = [
8484
'storePath' => WRITEPATH . 'cache/',
@@ -95,7 +95,7 @@ class Cache extends BaseConfig
9595
*
9696
* @see https://codeigniter.com/user_guide/libraries/caching.html#memcached
9797
*
98-
* @var array<string, bool|int|string>
98+
* @var array{host?: string, port?: int, weight?: int, raw?: bool}
9999
*/
100100
public array $memcached = [
101101
'host' => '127.0.0.1',
@@ -112,7 +112,7 @@ class Cache extends BaseConfig
112112
* Your Redis server can be specified below, if you are using
113113
* the Redis or Predis drivers.
114114
*
115-
* @var array<string, int|string|null>
115+
* @var array{host?: string, password?: string|null, port?: int, timeout?: int, database?: int}
116116
*/
117117
public array $redis = [
118118
'host' => '127.0.0.1',

system/Cache/CacheFactory.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public static function getHandler(Cache $config, ?string $handler = null, ?strin
7575
}
7676
}
7777

78-
// If $adapter->initialization throws a CriticalError exception, we will attempt to
78+
// If $adapter->initialize() throws a CriticalError exception, we will attempt to
7979
// use the $backup handler, if that also fails, we resort to the dummy handler.
8080
try {
8181
$adapter->initialize();

system/Cache/CacheInterface.php

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,6 @@
1313

1414
namespace CodeIgniter\Cache;
1515

16-
/**
17-
* Cache interface
18-
*/
1916
interface CacheInterface
2017
{
2118
/**
@@ -30,16 +27,16 @@ public function initialize();
3027
*
3128
* @param string $key Cache item name
3229
*
33-
* @return array|bool|float|int|object|string|null
30+
* @return mixed
3431
*/
3532
public function get(string $key);
3633

3734
/**
3835
* Saves an item to the cache store.
3936
*
40-
* @param string $key Cache item name
41-
* @param array|bool|float|int|object|string|null $value The data to save
42-
* @param int $ttl Time To Live, in seconds (default 60)
37+
* @param string $key Cache item name
38+
* @param mixed $value The data to save
39+
* @param int $ttl Time To Live, in seconds (default 60)
4340
*
4441
* @return bool Success or failure
4542
*/
@@ -87,7 +84,7 @@ public function clean();
8784
* The information returned and the structure of the data
8885
* varies depending on the handler.
8986
*
90-
* @return array|false|object|null
87+
* @return array<array-key, mixed>|false|object|null
9188
*/
9289
public function getCacheInfo();
9390

@@ -96,10 +93,9 @@ public function getCacheInfo();
9693
*
9794
* @param string $key Cache item name.
9895
*
99-
* @return array|false|null
100-
* Returns null if the item does not exist, otherwise array<string, mixed>
101-
* with at least the 'expire' key for absolute epoch expiry (or null).
102-
* Some handlers may return false when an item does not exist, which is deprecated.
96+
* @return array<string, mixed>|false|null Returns null if the item does not exist, otherwise array<string, mixed>
97+
* with at least the 'expire' key for absolute epoch expiry (or null).
98+
* Some handlers may return false when an item does not exist, which is deprecated.
10399
*/
104100
public function getMetaData(string $key);
105101

system/Cache/Exceptions/CacheException.php

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,14 @@
1616
use CodeIgniter\Exceptions\DebugTraceableTrait;
1717
use CodeIgniter\Exceptions\RuntimeException;
1818

19-
/**
20-
* CacheException
21-
*/
2219
class CacheException extends RuntimeException
2320
{
2421
use DebugTraceableTrait;
2522

2623
/**
2724
* Thrown when handler has no permission to write cache.
2825
*
29-
* @return CacheException
26+
* @return static
3027
*/
3128
public static function forUnableToWrite(string $path)
3229
{
@@ -36,7 +33,7 @@ public static function forUnableToWrite(string $path)
3633
/**
3734
* Thrown when an unrecognized handler is used.
3835
*
39-
* @return CacheException
36+
* @return static
4037
*/
4138
public static function forInvalidHandlers()
4239
{
@@ -46,7 +43,7 @@ public static function forInvalidHandlers()
4643
/**
4744
* Thrown when no backup handler is setup in config.
4845
*
49-
* @return CacheException
46+
* @return static
5047
*/
5148
public static function forNoBackup()
5249
{
@@ -56,7 +53,7 @@ public static function forNoBackup()
5653
/**
5754
* Thrown when specified handler was not found.
5855
*
59-
* @return CacheException
56+
* @return static
6057
*/
6158
public static function forHandlerNotFound()
6259
{

system/Cache/FactoriesCache.php

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,9 @@
1818

1919
final class FactoriesCache
2020
{
21-
/**
22-
* @var CacheInterface|FileVarExportHandler
23-
*/
24-
private $cache;
25-
26-
/**
27-
* @param CacheInterface|FileVarExportHandler|null $cache
28-
*/
29-
public function __construct($cache = null)
21+
private readonly CacheInterface|FileVarExportHandler $cache;
22+
23+
public function __construct(CacheInterface|FileVarExportHandler|null $cache = null)
3024
{
3125
$this->cache = $cache ?? new FileVarExportHandler();
3226
}
@@ -51,7 +45,9 @@ public function load(string $component): bool
5145
{
5246
$key = $this->getCacheKey($component);
5347

54-
if (! $data = $this->cache->get($key)) {
48+
$data = $this->cache->get($key);
49+
50+
if (! is_array($data) || $data === []) {
5551
return false;
5652
}
5753

system/Cache/FactoriesCache/FileVarExportHandler.php

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,7 @@ final class FileVarExportHandler
1717
{
1818
private string $path = WRITEPATH . 'cache';
1919

20-
/**
21-
* @param array|bool|float|int|object|string|null $val
22-
*/
23-
public function save(string $key, $val): void
20+
public function save(string $key, mixed $val): void
2421
{
2522
$val = var_export($val, true);
2623

@@ -36,10 +33,7 @@ public function delete(string $key): void
3633
@unlink($this->path . "/{$key}");
3734
}
3835

39-
/**
40-
* @return array|bool|float|int|object|string|null
41-
*/
42-
public function get(string $key)
36+
public function get(string $key): mixed
4337
{
4438
return @include $this->path . "/{$key}";
4539
}

system/Cache/Handlers/BaseHandler.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ abstract class BaseHandler implements CacheInterface
5353
* Keys that exceed MAX_KEY_LENGTH are hashed.
5454
* From https://github.com/symfony/cache/blob/7b024c6726af21fd4984ac8d1eae2b9f3d90de88/CacheItem.php#L158
5555
*
56-
* @param string $key The key to validate
56+
* @param mixed $key The key to validate
5757
* @param string $prefix Optional prefix to include in length calculations
5858
*
5959
* @throws InvalidArgumentException When $key is not valid
@@ -67,7 +67,8 @@ public static function validateKey($key, $prefix = ''): string
6767
throw new InvalidArgumentException('Cache key cannot be empty.');
6868
}
6969

70-
$reserved = config(Cache::class)->reservedCharacters ?? self::RESERVED_CHARACTERS;
70+
$reserved = config(Cache::class)->reservedCharacters;
71+
7172
if ($reserved !== '' && strpbrk($key, $reserved) !== false) {
7273
throw new InvalidArgumentException('Cache key contains reserved characters ' . $reserved);
7374
}
@@ -83,7 +84,7 @@ public static function validateKey($key, $prefix = ''): string
8384
* @param int $ttl Time to live
8485
* @param Closure(): mixed $callback Callback return value
8586
*
86-
* @return array|bool|float|int|object|string|null
87+
* @return mixed
8788
*/
8889
public function remember(string $key, int $ttl, Closure $callback)
8990
{
@@ -103,7 +104,7 @@ public function remember(string $key, int $ttl, Closure $callback)
103104
*
104105
* @param string $pattern Cache items glob-style pattern
105106
*
106-
* @return int|never
107+
* @return int
107108
*
108109
* @throws Exception
109110
*/

system/Cache/Handlers/FileHandler.php

Lines changed: 44 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,19 @@ class FileHandler extends BaseHandler
5454
*/
5555
public function __construct(Cache $config)
5656
{
57-
$this->path = ! empty($config->file['storePath']) ? $config->file['storePath'] : WRITEPATH . 'cache';
58-
$this->path = rtrim($this->path, '/') . '/';
57+
$options = [
58+
...['storePath' => WRITEPATH . 'cache', 'mode' => 0640],
59+
...$config->file,
60+
];
61+
62+
$this->path = $options['storePath'] !== '' ? $options['storePath'] : WRITEPATH . 'cache';
63+
$this->path = rtrim($this->path, '\\/') . '/';
5964

6065
if (! is_really_writable($this->path)) {
6166
throw CacheException::forUnableToWrite($this->path);
6267
}
6368

64-
$this->mode = $config->file['mode'] ?? 0640;
69+
$this->mode = $options['mode'];
6570
$this->prefix = $config->prefix;
6671

6772
helper('filesystem');
@@ -342,33 +347,46 @@ protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs
342347
* @param bool $topLevelOnly Look only at the top level directory specified?
343348
* @param bool $_recursion Internal variable to determine recursion status - do not use in calls
344349
*
345-
* @return array|false
350+
* @return array<string, array{
351+
* name: string,
352+
* server_path: string,
353+
* size: int,
354+
* date: int,
355+
* relative_path: string,
356+
* }>|false
346357
*/
347358
protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true, bool $_recursion = false)
348359
{
349-
static $_filedata = [];
350-
$relativePath = $sourceDir;
360+
static $filedata = [];
361+
362+
$relativePath = $sourceDir;
363+
$filePointer = @opendir($sourceDir);
351364

352-
if ($fp = @opendir($sourceDir)) {
365+
if (! is_bool($filePointer)) {
353366
// reset the array and make sure $sourceDir has a trailing slash on the initial call
354367
if ($_recursion === false) {
355-
$_filedata = [];
356-
$sourceDir = rtrim(realpath($sourceDir) ?: $sourceDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
368+
$filedata = [];
369+
370+
$resolvedSrc = realpath($sourceDir);
371+
$resolvedSrc = $resolvedSrc === false ? $sourceDir : $resolvedSrc;
372+
373+
$sourceDir = rtrim($resolvedSrc, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
357374
}
358375

359376
// Used to be foreach (scandir($sourceDir, 1) as $file), but scandir() is simply not as fast
360-
while (false !== ($file = readdir($fp))) {
377+
while (false !== $file = readdir($filePointer)) {
361378
if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
362379
$this->getDirFileInfo($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
363380
} elseif (! is_dir($sourceDir . $file) && $file[0] !== '.') {
364-
$_filedata[$file] = $this->getFileInfo($sourceDir . $file);
365-
$_filedata[$file]['relative_path'] = $relativePath;
381+
$filedata[$file] = $this->getFileInfo($sourceDir . $file);
382+
383+
$filedata[$file]['relative_path'] = $relativePath;
366384
}
367385
}
368386

369-
closedir($fp);
387+
closedir($filePointer);
370388

371-
return $_filedata;
389+
return $filedata;
372390
}
373391

374392
return false;
@@ -382,10 +400,19 @@ protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true,
382400
*
383401
* @deprecated 4.6.1 Use `get_file_info()` instead.
384402
*
385-
* @param string $file Path to file
386-
* @param array|string $returnedValues Array or comma separated string of information returned
403+
* @param string $file Path to file
404+
* @param list<string>|string $returnedValues Array or comma separated string of information returned
387405
*
388-
* @return array|false
406+
* @return array{
407+
* name?: string,
408+
* server_path?: string,
409+
* size?: int,
410+
* date?: int,
411+
* readable?: bool,
412+
* writable?: bool,
413+
* executable?: bool,
414+
* fileperms?: int
415+
* }|false
389416
*/
390417
protected function getFileInfo(string $file, $returnedValues = ['name', 'server_path', 'size', 'date'])
391418
{

system/Cache/Handlers/MemcachedHandler.php

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class MemcachedHandler extends BaseHandler
3838
/**
3939
* Memcached Configuration
4040
*
41-
* @var array
41+
* @var array{host: string, port: int, weight: int, raw: bool}
4242
*/
4343
protected $config = [
4444
'host' => '127.0.0.1',
@@ -76,43 +76,32 @@ public function initialize()
7676
{
7777
try {
7878
if (class_exists(Memcached::class)) {
79-
// Create new instance of Memcached
8079
$this->memcached = new Memcached();
80+
8181
if ($this->config['raw']) {
8282
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
8383
}
8484

85-
// Add server
8685
$this->memcached->addServer(
8786
$this->config['host'],
8887
$this->config['port'],
8988
$this->config['weight'],
9089
);
9190

92-
// attempt to get status of servers
9391
$stats = $this->memcached->getStats();
9492

9593
// $stats should be an associate array with a key in the format of host:port.
9694
// If it doesn't have the key, we know the server is not working as expected.
97-
if (! isset($stats[$this->config['host'] . ':' . $this->config['port']])) {
95+
if (! is_array($stats) || ! isset($stats[$this->config['host'] . ':' . $this->config['port']])) {
9896
throw new CriticalError('Cache: Memcached connection failed.');
9997
}
10098
} elseif (class_exists(Memcache::class)) {
101-
// Create new instance of Memcache
10299
$this->memcached = new Memcache();
103100

104-
// Check if we can connect to the server
105-
$canConnect = $this->memcached->connect(
106-
$this->config['host'],
107-
$this->config['port'],
108-
);
109-
110-
// If we can't connect, throw a CriticalError exception
111-
if ($canConnect === false) {
101+
if (! $this->memcached->connect($this->config['host'], $this->config['port'])) {
112102
throw new CriticalError('Cache: Memcache connection failed.');
113103
}
114104

115-
// Add server, third parameter is persistence and defaults to TRUE.
116105
$this->memcached->addServer(
117106
$this->config['host'],
118107
$this->config['port'],

0 commit comments

Comments
 (0)