<?php

namespace Ministra\Admin;

use Moust\Silex\Provider\CacheServiceProvider as MCacheServiceProvider;
use Pimple\Container;
class CacheServiceProvider extends \Moust\Silex\Provider\CacheServiceProvider
{
    public function register(\Pimple\Container $app)
    {
        $options = $app->offsetExists('memcache.options') ? $app['memcache.options'] : ['memcache.options' => ['host' => 'localhost', 'default_timeout' => 1800]];
        if (null !== ($instance = $this->checkMemcacheConnect($options['memcache.options']['host']))) {
            $app['caches.options'] = ['memcache' => ['driver' => \get_class($instance) === 'Memcache' ? 'memcache' : 'memcached', 'memcache' => function () use($instance) {
                return $instance;
            }]];
        } else {
            $app['caches.options'] = ['filesystem' => ['driver' => 'file', 'cache_dir' => __DIR__ . '/../resources/cache/admin']];
        }
        return parent::register($app);
    }
    private function checkMemcacheConnect($hosts)
    {
        if (!\class_exists('Memcache') && !\class_exists('Memcached')) {
            return null;
        }
        $memcache = \class_exists('Memcached') ? new \Memcached() : new \Memcache();
        if (!\is_array($hosts)) {
            $hosts = [$hosts];
        }
        $countDisabled = 0;
        foreach ($hosts as $host) {
            if (!$memcache->addServer($host, 11211)) {
                ++$countDisabled;
                \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\e7c78b97b208e4e1ae814a978ff35f3c('Could not connect to memcached. Host: ' . $host);
            }
            if (!$memcache->set('test', '123')) {
                ++$countDisabled;
                \Ministra\Lib\w13ec15f0067ea75861e61e27c990e4ba\e7c78b97b208e4e1ae814a978ff35f3c('Could not connect to memcached. Host: ' . $host);
            }
        }
        return $countDisabled === \count($hosts) ? null : $memcache;
    }
}
