<?php
/**
 * Page Cache powered by Jpresta (jpresta . com)
 *
 *    @author    Jpresta
 *    @copyright Jpresta
 *    @license   You are just allowed to modify this copy for your own use. You must not redistribute it. License
 *               is permitted for one Prestashop instance only but you can install it on your test instances.
 */

class Media extends MediaCore
{

    public static function clearCache()
    {
        if (Module::isEnabled('pagecache')) {
            $pagecacheInstance = Module::getInstanceByName('pagecache');
            if ($pagecacheInstance) {
                $caller = self::getCallerMethod();
                if (strcmp($caller, 'clearAllCaches') === 0) {
                    $pagecacheInstance->clearCache();
                } else {
                    $files = array_merge(
                        // I split the string because some Prestashop version think it is a PHP comment
                        glob(_PS_THEME_DIR_ . 'assets/cache/' . '*'),
                        glob(_PS_THEME_DIR_ . 'cache/' . '*')
                    );

                    foreach ($files as $file) {
                        if ('index.php' !== basename($file)) {
                            $pagecacheInstance->clearCache();
                            break;
                        }
                    }
                }
            }
        }
        return parent::clearCache();
    }

    private static function getCallerMethod()
    {
        $traces = debug_backtrace();
        if (isset($traces[2])) {
            return $traces[2]['function'];
        }
        return null;
    }
}
