<?php
/**
 * @author Ulrich Hecht <ulrich.hecht@hecht-software.de>
 * @date 12/01/2016
 */

namespace AppBundle;


class RedisClassLoader
{
    private $prefix;

    /**
     * A class loader object that implements the findFile() method.
     *
     * @var object
     */
    private $decorated;

    /**
     * @var null|\Redis
     */
    private $redis = null;

    /**
     * Constructor.
     *
     * @param string $prefix    The XCache namespace prefix to use
     * @param object $decorated A class loader object that implements the findFile() method
     *
     * @throws \RuntimeException
     * @throws \InvalidArgumentException
     */
    public function __construct($prefix, $decorated)
    {
        if (extension_loaded('redis')) {
            $this->redis = new \Redis();
            $this->redis->connect('127.0.0.1');
        }

        if (!method_exists($decorated, 'findFile')) {
            throw new \InvalidArgumentException('The class finder must implement a "findFile" method.');
        }

        $this->prefix = $prefix;
        $this->decorated = $decorated;
    }

    /**
     * Registers this instance as an autoloader.
     *
     * @param bool $prepend Whether to prepend the autoloader or not
     */
    public function register($prepend = false)
    {
        spl_autoload_register(array($this, 'loadClass'), true, $prepend);
    }

    /**
     * Unregisters this instance as an autoloader.
     */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));
    }

    /**
     * Loads the given class or interface.
     *
     * @param string $class The name of the class
     *
     * @return bool|null True, if loaded
     */
    public function loadClass($class)
    {
        if ($file = $this->findFile($class)) {
            require $file;

            return true;
        }
    }

    /**
     * Finds a file by class name while caching lookups to Xcache.
     *
     * @param string $class A class name to resolve to file
     *
     * @return string|null
     */
    public function findFile($class)
    {
        if ($this->redis === null)
        {
            return $this->decorated->findFile($class) ?: null;
        }

        if ($this->redis->exists($this->prefix.$class))
        {
            $file = $this->redis->get($this->prefix.$class);
        }
        else
        {
            $file = $this->decorated->findFile($class) ?: null;
            $this->redis->set($this->prefix.$class, $file);
        }

        return $file;
    }

    /**
     * Passes through all unknown calls onto the decorated object.
     */
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->decorated, $method), $args);
    }
}