<?php

namespace Velis\Cache\Adapter;

use Exception;
use Phalcon\Cache\Adapter\AdapterInterface;
use Phalcon\Storage\Adapter\Redis as BaseAdapter;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class Phalcon4RedisAdapter extends BaseAdapter implements AdapterInterface
{
    public function clear(): bool
    {
        try {
            $redis = $this->getAdapter();
            $keys = $redis->keys('*');

            foreach ($keys as $key) {
                $key = str_replace($this->prefix, '', $key);
                $redis->del($key);
            }
        } catch (Exception $e) {
            return false;
        }

        return true;
    }


    public function getKeys($prefix = ""): array
    {
        try {
            $redis = $this->getAdapter();
            $keys = [];

            foreach ($redis->keys('*') as $key) {
                if (preg_match('/' . $prefix . '.*/i', $key, $matches)) {
                    $keys[] = $matches[0];
                }
            }

            return $keys;
        } catch (Exception $e) {
            return [];
        }
    }
}
