codeigniter4 / CodeIgniter4

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
5.4k stars 1.9k forks source link

Bug: Cache RedisHandler Always Returns null MetaData if a prefix is Set #7304

Closed AmitSonkhiya closed 1 year ago

AmitSonkhiya commented 1 year ago

PHP Version

8.2

CodeIgniter4 Version

4.3.2

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

Linux

Which server did you use?

cli-server (PHP built-in webserver)

Database

No response

What happened?

When a prefix is provided for the Redis cache handler, the getMetaData() method always returns null.

Steps to Reproduce

  1. Set up Redis handler in the file App\Config\Cache.php.
  2. Set the handler redis.
  3. Set a key prefix.
  4. Provide the appropriate Redis configuration.
  5. Ensure that Redis is valid handler.

Now try to store any value in the Redis caching using the service. Try to access the metadata using the method getMetaData(). It will be received null.

Expected Output

Proper Metadata array about the existing cache key.

Anything else?

In the file system\Cache\Handlers\RedisHandler.php Line #236, the key is validated and the prefix is prepended. In the next line the get() method is called which again prepend the prefix.

Hence, prepending the prefix twice turns the key into an always non-existing key. The resolution is exchanging the order of execution for both lines.

public function getMetaData(string $key)
    {
        $value = $this->get($key);
        $key   = static::validateKey($key, $this->prefix);

        if ($value !== null) {
            $time = Time::now()->getTimestamp();
            $ttl  = $this->redis->ttl($key);

            return [
                'expire' => $ttl > 0 ? $time + $ttl : null,
                'mtime'  => $time,
                'data'   => $value,
            ];
        }

        return null;
    }
kenjis commented 1 year ago

Thank you for reporting.

It seems you are correct. We accept a PR to fix it.