<?php
/**
 * 
 * @author Jani Kuula
 *
 */


class caching {

    private static string $datetimeformat = 'Y-m-d H:i:s';

    public static function setContent(string $file, mixed $content, string $expires): void {
    
        //expires: string + 1 day or DateTime
        if(gettype($expires)=='string'){
            $datetime=new DateTime();
            $expires = $datetime->modify($expires);
        }
    
        $file = self::getFile($file);
        if(null===$file){ return; }
        @file_put_contents(
            $file, 
            json_encode(['content'=>$content, 'expires'=>$expires->format(self::$datetimeformat)])
        );
    }

    
    private static function getFile(string $file): ?string {
        if(!preg_match('/^[A-Za-z0-9_-]+$/', $file)){
            die('Possible directory traversal attempt found in caching::getFile');
        }
        $storage=rtrim(config::get('core_filestore'),'/').'/cache/';
        if(!file_exists($storage) &&!!@mkdir($storage, true)){
            return null;
        }
        return $storage.$file.'.txt';
    }

    
    public static function getContent(string $file, bool $full=false): string|array {
        $content=file_get_contents(self::getFile($file));
        $content=json_decode($content, true);
        return $full?$content:$content['content'];
    }


    public static function has(string $file): bool {
        $path=self::getFile($file);
        if(null===$path || !file_exists($path)){
            return false;
        }
        $content=self::getContent($file, true);
        if(!array_key_exists('expires', $content)){
            //not valid
            return false;
        }
        $datetime=DateTime::createFromFormat(self::$datetimeformat, $content['expires']);
        if(false===$datetime){
            //not valid
            return false;
        }
        if(new DateTime()>$datetime){
            //expired
            return false;
        }
        return true;
    }

	/**
	 * @throws ServerException
	 */
	public static function getAll() {
		throw new ServerException('getAll not implemented in caching');
	}

}