<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/


class AHDMN_Core_Cache {

    protected $path;
    protected $ttl;

    /**
     * @param array $config
     * @throws Exception
     */
    public function __construct( array $config )
    {
        // Validate
        $path = isset( $config[ 'path' ] ) ? rtrim( $config[ 'path' ] ) : NULL;
        if ( is_null( $path ) || !is_dir( $path ) || !is_writable( $path ) )
        {
            throw new Exception( "Invalid path given." );
        }

        $this->path = $path;
        $this->ttl = isset( $config[ 'ttl' ] ) ? +$config[ 'ttl' ] : 3600;

    }

    /**
     * @param $id
     * @param $data
     */
    public function set( $id, $data )
    {
        $filename = $this->getFilenameById( $id );
        try
        {
            $packedData = base64_encode( json_encode( $data ) );
            if ( is_string( $packedData ) )
            {
                @file_put_contents( $filename, $packedData );
                return true;
            }
            else
            {
                throw new Exception( 'Cannot pack data.' );
            }
        }
        catch ( Exception $e )
        {
            var_dump( $e );
            // Do nothing
            return false;
        }
    }

    /**
     * @param $id
     */
    public function get( $id )
    {
        $data = NULL;
        $filename = $this->getFilenameById( $id );

        if ( file_exists( $filename ) &&
             filemtime( $filename ) + $this->ttl >= time() )
        {
            $packedData = file_get_contents( $filename );
            $data = json_decode( base64_decode( $packedData ), true );
            if ( json_last_error() !== JSON_ERROR_NONE )
            {
                $data = NULL;
            }
        }

        return $data;
    }

    /**
     * Get
     * @param $id
     * @return mixed|string
     */
    private function getFilenameById( $id )
    {
        $filename = preg_replace('/[^0-9a-z\.\_\-]/i','', strtolower( $id) );
        $filename = $this->path . DIRECTORY_SEPARATOR . $filename . '.cached';
        return $filename;
    }

}