Create a default file cache for the Translate and DB adapters to speed up execution

@return \Zend_Cache_Core
492090
protected function _initCache()
    {
        $this->bootstrap('project');

        $useCache = $this->getResource('project')->getCache();

        $cache       = null;
        $exists      = false;
        $cachePrefix = GEMS_PROJECT_NAME . '_';


        // Check if APC extension is loaded and enabled
        if (\MUtil_Console::isConsole() && !ini_get('apc.enable_cli') && $useCache === 'apc') {
            // To keep the rest readable, we just fall back to File when apc is disabled on cli
            $useCache = "File";
        }
        if ($useCache === 'apc' && extension_loaded('apc') && ini_get('apc.enabled')) {
            //Add path to the prefix as APC is a SHARED cache
            $cachePrefix .= md5(APPLICATION_PATH);
            $cacheBackendOptions = array('cache_id_prefix' => $cachePrefix);
            $cacheBackend = new \Gems\Cache\Backend\Apc($cacheBackendOptions);
            $exists = true;
        } else {
            $cacheBackend = 'File';
            $cacheDir = GEMS_ROOT_DIR . "/var/cache/";
            $cacheBackendOptions = array('cache_dir' => $cacheDir);
            if (!file_exists($cacheDir)) {
                if (@mkdir($cacheDir, 0777, true)) {
                    $exists = true;
                }
            } else {
                $exists = true;
            }
        }

        if ($exists && $useCache <> 'none') {
            /**
             * automatic_cleaning_factor disables automatic cleaning of the cache and should get rid of
             *                           random delays on heavy traffic sites with File cache. Apc does
             *                           not support automatic cleaning.
             */
            $cacheFrontendOptions = array('automatic_serialization' => true,
                                          'cache_id_prefix' => $cachePrefix,
                                          'automatic_cleaning_factor' => 0);

            $cache = \Zend_Cache::factory('Core', $cacheBackend, $cacheFrontendOptions, $cacheBackendOptions);
        } else {
            $cache = \Zend_Cache::factory('Core', 'Static', array('caching' => false), array('disable_caching' => true));
        }

        \Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);
        \Zend_Translate::setCache($cache);
        \Zend_Locale::setCache($cache);

        return $cache;
    }
75389
private function createCache()
    {
        $cachePath = $this->getCachePath();
        $content   = json_encode([], JSON_PRETTY_PRINT);

        $this->files->put($cachePath, $content);

        return collect(json_decode($content, true));
    }
103173
protected function cachedFile()
    {
        if (null === $this->cachedFile) {
            $this->cachedFile = rtrim($this->dir, '/') . '/' . ltrim($this->filename, '/');
        }

        return $this->cachedFile;
    }
344444
protected function createMemcachedDriver()
    {
        $servers = $this->app['config']['cache.memcached'];

        $memcached = $this->app['memcached.connector']->connect($servers);

        return $this->repository(new MemcachedStore($memcached, $this->getPrefix()));
    }
475459
public function getItemStorage()
    {
        // Hack for weird initialization logic
        if (!$this->itemStorage) {
            $this->itemStorage = new CacheItemStorage(
                $this->cacheAdapter ?: $this->getDefaultCacheAdapter(),
                $this->config->getCacheExpirationInSeconds()
            );
        }

        return $this->itemStorage;
    }
329516
public function createFile()
    {
        $cacheDependencyFileName = $this->getDependencyFileName();
        if ( ! file_exists(dirname($cacheDependencyFileName)) ) {
            FileHelper::createDirectory(dirname($cacheDependencyFileName));
        }
        file_put_contents($cacheDependencyFileName, uniqid());
        return $cacheDependencyFileName;
    }
344783
private function getCache()
    {
        $cachePath = $this->getCachePath();

        if (!$this->files->exists($cachePath)) {
            $this->createCache();

            $this->optimize();
        }

        return collect(json_decode($this->files->get($cachePath), true));
    }
489786
private function bootCacher()
    {
        /** @var Cacher $cacher */
        $cacher = Cacher::getInstance();

        // Default cacher if FileCache, so we do not check it
        if (MemcachedCache::itWorks()) { // Distributed cache new version
            $cacher->setDefaultCacher('MemcachedCache');
        } elseif (MemcacheCache::itWorks()) { // Distributed cache old version
            $cacher->setDefaultCacher('MemcacheCache');
        } elseif (RedisCache::itWorks()) { // No-sql database
            $cacher->setDefaultCacher('RedisCache');
        }
    }
718950
public static function file()
    {
        if (!isset(self::core()->file)) {
            //====================================================================//
            // Initialize Tasks List
            self::core()->file = new FileManager();

            //====================================================================//
            //  Load Translation File
            self::translator()->load('file');
        }

        return self::core()->file;
    }
253432
private function createCacheFactories()
    {
        if (null !== $this->cacheFactories) {
            return $this->cacheFactories;
        }

        // load bundled cache factories
        $tempContainer = new ContainerBuilder();
        $loader = new Loader\XmlFileLoader($tempContainer, new FileLocator(__DIR__.'/../Resources/config'));

        $loader->load('cache_factories.xml');

        $cacheFactories = array();
        foreach ($tempContainer->findTaggedServiceIds('tbbc_cache.cache_factory') as $id => $factories) {
            foreach ($factories as $factory) {
                if (!isset($factory['cache_type'])) {
                    throw new \InvalidArgumentException(sprintf(
                        'Service "%s" must define a "cache_type" attribute for "tbbc_cache.cache_factory" tag',
                        $id
                    ));
                }

                $factoryService = $tempContainer->get($id);
                $cacheFactories[str_replace('-', '_', strtolower($factory['cache_type']))] = $factoryService;
            }
        }

        return $this->cacheFactories = $cacheFactories;
    }
756289
static public function getDefaultCacheHandler() {
        if(!isset(self::$defaultCacheHandler)) {            
            global $container;
            if(self::BACKWORDS_COMPATIBLE && isset($container) && isset($container['memcache'])) {
                // Backwards Compatibility
                if(class_exists("Memcache") && is_a($container['memcache'], "Memcache")) {
                    self::$defaultCacheHandler = new CacheHandler\Memcache($container['memcache']);
                } else if (class_exists("Memcached") && is_a($container['memcache'], "Memcached")) {
                    self::$defaultCacheHandler = new CacheHandler\Memcached($container['memcache']);    
                } else {
                    trigger_error("Before using NoizuLabs/Fragmented you must set a cache handler using NoizuLabs\FragmentedKeys\Configuration::setDefaultCacheHandler(ICacheHandle \$handler) or use only KeyRing entries with a specified storage mechanism.", E_USER_ERROR);    
                }
            }  else {
                trigger_error("Before using NoizuLabs/Fragmented you must set a cache handler using NoizuLabs\FragmentedKeys\Configuration::setDefaultCacheHandler(ICacheHandle \$handler) or use only KeyRing entries with a specified storage mechanism.", E_USER_ERROR);
            }
        }
        return self::$defaultCacheHandler;
    }
765664
private function saveObjectDataToCache()
    {
        Cacher::getInstance()->getDefaultCacher()->set($this->getCacheKey(), $this->getAsArray(), 3600);

        return $this;
    }
1097354
public final function getFinalCache() {
        $resource = $this;
        while (true) {
            $cache_file = $this->getParentProject()->getCacheManager()->getCacheBuilt($resource);
            if (\is_null($cache_file) ||
                    \is_null($this->getParentProject()->getResourceByFile($cache_file)) ||
                    $this->getParentProject()->getResourceByFile($cache_file)->getMemberId() === $resource->getMemberId()
            ) {
                return $resource;
            }
            $resource = $this->getParentProject()->getResourceByFile($cache_file);
        }
    }
1269214
public function getCache() {
    if (!isset($this->cache))
      $this->cache = new \Doctrine\Common\Cache\ArrayCache;
      
    return $this->cache;
  }
1208323
public static function build()
    {
        switch (true) {
            // @codeCoverageIgnoreStart
            case extension_loaded('apc'):
                $cacheDriver = new ApcuCache;
                break;

            case extension_loaded('xcache'):
                $cacheDriver = new XcacheCache;
                break;

            case extension_loaded('memcache'):
                $memcache = new \Memcache;
                $memcache->connect('127.0.0.1');

                $cacheDriver = new MemcacheCache;
                $cacheDriver->setMemcache($memcache);
                break;

            case extension_loaded('redis'):
                $redis = new \Redis();
                $redis->connect('127.0.0.1');

                $cacheDriver = new RedisCache;
                $cacheDriver->setRedis($redis);
                break;
            // @codeCoverageIgnoreEnd

            default:
                $cacheDriver = new ArrayCache;
        }

        return $cacheDriver;
    }
339814
private function createFileCache():File
    {
        /** @var IConfig $config */
        $config = $this->di->getShared('config');
        /** @var IApp $app */
        $app = $this->di->getShared('app');
        $lifetime = (int)$config->get($this->getName() . '.lifetime', 3600);
        $cacheDir = $app->getCacheDir();
        $frontCache = new FrontData([
            "lifetime" => $lifetime
        ]);
        return new File($frontCache, ['cacheDir' => $cacheDir]);

    }
578134
private function router()
    {
        $routes = require $this->config['paths']['routes'];
        $request = \Zend\Diactoros\ServerRequestFactory::fromGlobals();

        $cacheFileName = 'routes.'.filemtime($this->config['paths']['routes']).'.cache';
        $cacheFile = $this->config['paths']['routesCache'].'/'.$cacheFileName;

        if (!file_exists($cacheFile)) {
            array_map('unlink', glob($this->config['paths']['routesCache'].'/*.cache'));
        }

        $dispatcher = \FastRoute\cachedDispatcher(
            function(\FastRoute\RouteCollector $r) use ($routes) {
                foreach ($routes as $route) {
                    $r->addRoute($route['methods'], $route['endpoint'], $route['call']);
                }
            },
            [
                'cacheFile' => $cacheFile,
            ]
        );

        $request = $request->withHeader('lang', $this->config['lang']);
        $request = $request->withHeader('config', json_encode($this->config));

        $routeInfo = $dispatcher->dispatch(
            $request->getMethod(),
            $request->getUri()->getPath()
        );

        $response = new \Zend\Diactoros\Response();

        switch ($routeInfo[0]) {

            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $response->getBody()->write('METHOD NOT ALLOWED');
                $response = $response->withStatus(405);
                $this->response = $response;
                break;

            case \FastRoute\Dispatcher::NOT_FOUND:
            case \FastRoute\Dispatcher::FOUND:

                $handler = isset($routeInfo[1]) ? $routeInfo[1] : $this->config['config']['not_found_controller'];
                $vars = isset($routeInfo[2]) ? $routeInfo[2] : [];
                $handler = explode('::', $handler);
                $class = $handler[0];
                $method = $handler[1];

                $response = (new \SideDevOrg\MiniPhpFw\Resolver())->dispatch(
                    $class,
                    $method,
                    $vars,
                    $request,
                    $response,
                    $middlewares = require $this->config['paths']['middlewares']
                );

                if (!isset($routeInfo[1])) {
                    $response = $response->withStatus(404);
                }
                $this->response = $response;
                break;
        }
    }