public function setUp() { $this->originalTimezone = date_default_timezone_get(); date_default_timezone_set('Europe/Paris'); $this->_cache = Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => dirname(__FILE__) . '/../_files/')); DateObjectTestHelper::setOptions(array('cache' => $this->_cache)); }
/** * Constructor * * @param array $options associative array of options * @throws \Zend\Cache\Exception */ public function __construct(array $options = array()) { if (!function_exists('zend_disk_cache_store')) { Cache\Cache::throwException('Zend_Cache_ZendServer_Disk backend has to be used within Zend Server environment.'); } parent::__construct($options); }
public function setUp($notag = false) { $this->mkdir(); $this->_cache_dir = $this->mkdir(); @mkdir($this->_cache_dir.'/tags'); $this->_innerCache = Cache\Cache::factory('Core','File', array('automatic_serialization'=>true), array('cache_dir'=>$this->_cache_dir.'/tags') ); $this->_instance = new Cache\Backend\StaticBackend(array( 'public_dir' => $this->_cache_dir, 'tag_cache' => $this->_innerCache )); $logger = new \Zend\Log\Logger(new \Zend\Log\Writer\Null()); $this->_instance->setDirectives(array('logger' => $logger)); $this->_requestUriOld = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null; $_SERVER['REQUEST_URI'] = '/foo'; $this->_instance->setDirectives(array('logging' => true)); $this->_instance->save('bar : data to cache', bin2hex('/bar'), array('tag3', 'tag4')); $this->_instance->save('bar2 : data to cache', bin2hex('/bar2'), array('tag3', 'tag1')); $this->_instance->save('bar3 : data to cache', bin2hex('/bar3'), array('tag2', 'tag3')); }
public function setUp() { $this->_cache = Cache::factory('Core', 'File', array('lifetime' => 1, 'automatic_serialization' => true), array('cache_dir' => __DIR__ . '/../../_files/')); Cldr::setCache($this->_cache); }
/** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @return void */ public function setUp() { $this->clearRegistry(); $this->_cache = Cache\Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => sys_get_temp_dir())); Currency\Currency::setCache($this->_cache); $this->helper = new Helper\Currency('de_AT'); }
/** * Enter description here... * * @return \Zend\Service\SlideShare */ protected function _getSSObject() { $ss = new SlideShareService(TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY, TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET, TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME, TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD, TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID); $cache = Cache::factory('Core', 'File', array('lifetime' => 0, 'automatic_serialization' => true), array('cache_dir' => __DIR__ . "/_files")); $ss->setCacheObject($cache); return $ss; }
protected function setUp() { if (!extension_loaded('pdo_sqlite')) { $this->markTestSkipped('Pdo_Sqlite extension is not loaded'); } $this->_adapter = new \Zend\Db\Adapter\Pdo\Sqlite(array( 'dbname' => __DIR__ . '/_files/test.sqlite' )); $this->_query = $this->_adapter->select()->from('test'); $this->_testCollection = range(1, 101); $this->_paginator = Paginator\Paginator::factory($this->_testCollection); $this->_config = new Config\Xml(__DIR__ . '/_files/config.xml'); // get a fresh new copy of ViewRenderer in each tests $this->front = FrontController::getInstance(); $this->front->resetInstance(); $this->broker = $this->front->getHelperBroker(); $fO = array('lifetime' => 3600, 'automatic_serialization' => true); $bO = array('cache_dir'=> $this->_getTmpDir()); $this->_cache = \Zend\Cache\Cache::factory('Core', 'File', $fO, $bO); Paginator\Paginator::setCache($this->_cache); $this->_restorePaginatorDefaults(); }
/** * @group ZF-10033 */ public function testSetDefaultMetadataCache() { $cache = \Zend\Cache\Cache::factory('Core', 'BlackHole', array('lifetime' => 120, 'automatic_serialization' => true)); $config = array('adapter' => 'Pdo\\Sqlite', 'params' => array('dbname' => ':memory:'), 'defaultMetadataCache' => $cache); $resource = new DbResource($config); $resource->init(); $this->assertInstanceOf('Zend\\Cache\\Frontend', \Zend\Db\Table\AbstractTable::getDefaultMetadataCache()); }
public function setUp() { $this->_cache_dir = $this->mkdir(); $this->_cache = Cache\Cache::factory( 'Core', 'File', array('automatic_serialization'=>true), array('cache_dir'=>$this->_cache_dir) ); }
public function setUp() { $this->_locale = setlocale(LC_ALL, 0); setlocale(LC_ALL, 'de'); $this->_cache = Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => __DIR__ . '/../_files/')); LocaleTestHelper::resetObject(); LocaleTestHelper::setCache($this->_cache); putenv("HTTP_ACCEPT_LANGUAGE=,de,en-UK-US;q=0.5,fr_FR;q=0.2"); }
public function setUp() { $this->_locale = setlocale(LC_ALL, 0); setlocale(LC_ALL, 'de'); $this->_cache = Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => __DIR__ . '/../_files/')); LocaleTestHelper::resetObject(); LocaleTestHelper::setCache($this->_cache); // compatibilityMode is true until 1.8 therefor we have to change it LocaleTestHelper::$compatibilityMode = false; putenv("HTTP_ACCEPT_LANGUAGE=,de,en-UK-US;q=0.5,fr_FR;q=0.2"); }
/** * callback for output buffering * (shouldn't really be called manually) * * @param string $data Buffered output * @return string Data to send to browser */ public function _flush($data) { $id = array_pop($this->_idStack); if (is_null($id)) { Cache::throwException('use of _flush() without a start()'); } if ($this->_extension) { $this->save(serialize(array($data, $this->_extension)), $id, $this->_tags); } else { $this->save($data, $id, $this->_tags); } return $data; }
/** * Stop the cache * * @param array $tags Tags array * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime) * @param string $forcedDatas If not null, force written datas with this * @param boolean $echoData If set to true, datas are sent to the browser * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends * @return void */ public function end($tags = array(), $specificLifetime = false, $forcedDatas = null, $echoData = true, $priority = 8) { if ($forcedDatas === null) { $data = ob_get_contents(); ob_end_clean(); } else { $data =& $forcedDatas; } $id = array_pop($this->_idStack); if ($id === null) { Cache::throwException('use of end() without a start()'); } $this->save($data, $id, $tags, $specificLifetime, $priority); if ($echoData) { echo $data; } }
/** * Log a message at the WARN (4) priority. * * @param string $message * @throws \Zend\Cache\Exception * @return void */ protected function _log($message, $priority = 4) { if (!$this->_options['logging']) { return; } if (!(isset($this->_options['logger']) || $this->_options['logger'] instanceof Log\Logger)) { Cache::throwException('Logging is enabled but logger is not set'); } $logger = $this->_options['logger']; $logger->log($message, $priority); }
/** * Make a cache id from the function name and parameters * * @param callback $callback A valid callback * @param array $args Function parameters * @throws \Zend\Cache\Exception * @return string Cache id */ public function makeId($callback, array $args = array()) { if (!is_callable($callback, true, $name)) { Cache::throwException('Invalid callback'); } // functions, methods and classnames are case-insensitive $name = strtolower($name); // generate a unique id for object callbacks if (is_object($callback)) { // Closures & __invoke $object = $callback; } elseif (isset($callback[0])) { // array($object, 'method') $object = $callback[0]; } if (isset($object)) { try { $tmp = @serialize($callback); } catch (\Exception $e) { Cache::throwException($e->getMessage()); } if (!$tmp) { $lastErr = error_get_last(); Cache::throwException("Can't serialize callback object to generate id: {$lastErr['message']}"); } $name .= '__' . $tmp; } // generate a unique id for arguments $argsStr = ''; if ($args) { try { $argsStr = @serialize(array_values($args)); } catch (\Exception $e) { Cache::throwException($e->getMessage()); } if (!$argsStr) { $lastErr = error_get_last(); throw Cache::throwException("Can't serialize arguments to generate id: {$lastErr['message']}"); } } return md5($name . $argsStr); }
/** * Gets the Zend\Cache object which will be used to cache API queries. If no cache object * was previously set the the default will be used (Filesystem caching in /tmp with a life * time of 43200 seconds) * * @return Zend\Cache\Frontend\Core The object used in caching */ public function getCacheObject() { if(!($this->_cacheobject instanceof Frontend\Core)) { $cache = \Zend\Cache\Cache::factory('Core', 'File', array('lifetime' => 43200, 'automatic_serialization' => true), array('cache_dir' => '/tmp')); $this->setCacheObject($cache); } return $this->_cacheobject; }
/** * Clean some cache records * * Available modes are : * 'all' (default) => remove all cache entries ($tags is not used) * 'old' => unsupported * 'matchingTag' => unsupported * 'notMatchingTag' => unsupported * 'matchingAnyTag' => unsupported * * @param string $mode clean mode * @param array $tags array of tags * @throws \Zend\Cache\Exception * @return boolean true if no problem */ public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { case Cache\Cache::CLEANING_MODE_ALL: // Necessary because xcache_clear_cache() need basic authentification $backup = array(); if (isset($_SERVER['PHP_AUTH_USER'])) { $backup['PHP_AUTH_USER'] = $_SERVER['PHP_AUTH_USER']; } if (isset($_SERVER['PHP_AUTH_PW'])) { $backup['PHP_AUTH_PW'] = $_SERVER['PHP_AUTH_PW']; } if ($this->_options['user']) { $_SERVER['PHP_AUTH_USER'] = $this->_options['user']; } if ($this->_options['password']) { $_SERVER['PHP_AUTH_PW'] = $this->_options['password']; } xcache_clear_cache(XC_TYPE_VAR, 0); if (isset($backup['PHP_AUTH_USER'])) { $_SERVER['PHP_AUTH_USER'] = $backup['PHP_AUTH_USER']; $_SERVER['PHP_AUTH_PW'] = $backup['PHP_AUTH_PW']; } return true; break; case Cache\Cache::CLEANING_MODE_OLD: $this->_log("Zend_Cache_Backend_Xcache::clean() : CLEANING_MODE_OLD is unsupported by the Xcache backend"); break; case Cache\Cache::CLEANING_MODE_MATCHING_TAG: case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND); break; default: Cache\Cache::throwException('Invalid mode for clean() method'); break; } }
/** * @group ZF-10049 */ public function testSetDefaultMetadataCache() { $cache = Cache::factory('Core', 'BlackHole', array('lifetime' => 120, 'automatic_serialization' => true)); $options = $this->_dbOptions; $options['defaultMetadataCache'] = $cache; $resource = new MultidbResource($options); $resource->init(); $this->assertType('Zend\\Cache\\Frontend\\Core', DBTable::getDefaultMetadataCache()); }
/** * Returns a clean Zend_Cache_Core with File backend * * @return Zend_Cache_Core */ protected function _getCacheNowrite() { /** * @see Zend_Cache */ $folder = __DIR__ . DIRECTORY_SEPARATOR . '../_files' . DIRECTORY_SEPARATOR . 'nofiles'; if (!file_exists($folder)) { mkdir($folder, 0777); } $frontendOptions = array('automatic_serialization' => true); $backendOptions = array('cache_dir' => $folder, 'file_name_prefix' => 'Zend_Db_Table_TestCommon'); $cacheFrontend = Cache\Cache::factory('Core', 'File', $frontendOptions, $backendOptions); $cacheFrontend->clean(Cache\Cache::CLEANING_MODE_ALL); rmdir($folder); return $cacheFrontend; }
/** * Log a message at the WARN (4) priority. * * @param string $message * @throws \Zend\Cache\Exception * @return void */ protected function _log($message, $priority = 4) { if (!$this->_directives['logging']) { return; } if (!isset($this->_directives['logger'])) { Cache\Cache::throwException('Logging is enabled but logger is not set.'); } $logger = $this->_directives['logger']; if (!$logger instanceof Log\Logger) { Cache\Cache::throwException('Logger object is not an instance of Zend_Log class.'); } $logger->log($message, $priority); }
/** * Check if the database structure is ok (with the good version), if no : build it * * @throws \Zend\Cache\Exception * @return boolean True if ok */ private function _checkAndBuildStructure() { if (!$this->_structureChecked) { if (!$this->_checkStructureVersion()) { $this->_buildStructure(); if (!$this->_checkStructureVersion()) { Cache\Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']); } } $this->_structureChecked = true; } return true; }
/** * Return the filling percentage of the backend storage * * @throws \Zend\Cache\Exception * @return int integer between 0 and 100 */ public function getFillingPercentage() { $mem = apc_sma_info(true); $memSize = $mem['num_seg'] * $mem['seg_size']; $memAvailable = $mem['avail_mem']; $memUsed = $memSize - $memAvailable; if ($memSize == 0) { Cache\Cache::throwException('can\'t get apc memory size'); } if ($memUsed > $memSize) { return 100; } return (int) (100.0 * ($memUsed / $memSize)); }
public function testBadBackend() { try { Cache\Cache::factory('Output', 'badBackend'); } catch (Cache\Exception $e) { return; } $this->fail('Zend_Exception was expected but not thrown'); }
/** * ZF-9877 */ public function testSetCacheThroughOptions() { $cache = Cache\Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => __DIR__ . '/../_files/')); $translate = new Translator\Translator(array('adapter' => Translator\Translator::AN_ARRAY, 'content' => array('msg1' => 'Message 1 (en)'), 'locale' => 'en', 'cache' => $cache)); $return = Translator\Translator::getCache(); $this->assertTrue($return instanceof Cache\Frontend); $this->assertTrue(Translator\Translator::hasCache()); }
/** * Validate a cache id or a tag (security, reliable filenames, reserved prefixes...) * * Throw an exception if a problem is found * * @param string $string Cache id or tag * @throws \Zend\Cache\Exception * @return void * @deprecated Not usable until perhaps ZF 2.0 */ protected static function _validateIdOrTag($string) { if (!is_string($string)) { Cache\Cache::throwException('Invalid id or tag : must be a string'); } // Internal only checked in Frontend - not here! if (substr($string, 0, 9) == 'internal-') { return; } // Validation assumes no query string, fragments or scheme included - only the path if (!preg_match('/^(?:\\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\\[\\]:@&=+$,;])*)?)+$/', $string)) { Cache\Cache::throwException("Invalid id or tag '{$string}' : must be a valid URL path"); } }
/** * Clean some cache records * * Available modes are : * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used) * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used) * This mode is not supported in this backend * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags * ($tags can be an array of strings or a single string) * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => unsupported * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags * ($tags can be an array of strings or a single string) * * @param string $mode Clean mode * @param array $tags Array of tags * @throws \Zend\Cache\Exception * @return boolean True if no problem */ public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { case Cache\Cache::CLEANING_MODE_ALL: case Cache\Cache::CLEANING_MODE_OLD: $cache_dir = ini_get('zend_accelerator.output_cache_dir'); if (!$cache_dir) { return false; } $cache_dir .= '/.php_cache_api/'; return $this->_clean($cache_dir, $mode); break; case Cache\Cache::CLEANING_MODE_MATCHING_TAG: $idlist = null; foreach ($tags as $tag) { $next_idlist = output_cache_get(self::TAGS_PREFIX . $tag, $this->_directives['lifetime']); if ($idlist) { $idlist = array_intersect_assoc($idlist, $next_idlist); } else { $idlist = $next_idlist; } if (count($idlist) == 0) { // if ID list is already empty - we may skip checking other IDs $idlist = null; break; } } if ($idlist) { foreach ($idlist as $id) { output_cache_remove_key($id); } } return true; break; case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: $this->_log("Zend_Cache_Backend_ZendPlatform::clean() : CLEANING_MODE_NOT_MATCHING_TAG is not supported by the Zend Platform backend"); return false; break; case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $idlist = null; foreach ($tags as $tag) { $next_idlist = output_cache_get(self::TAGS_PREFIX . $tag, $this->_directives['lifetime']); if ($idlist) { $idlist = array_merge_recursive($idlist, $next_idlist); } else { $idlist = $next_idlist; } if (count($idlist) == 0) { // if ID list is already empty - we may skip checking other IDs $idlist = null; break; } } if ($idlist) { foreach ($idlist as $id) { output_cache_remove_key($id); } } return true; break; default: Cache\Cache::throwException('Invalid mode for clean() method'); break; } }
public function testLoadingFilesIntoCacheAfterwards() { $cache = Cache\Cache::factory('Core', 'File', array('lifetime' => 120, 'automatic_serialization' => true), array('cache_dir' => dirname(__FILE__) . '/_files/')); $this->assertFalse(Adapter\ArrayAdapter::hasCache()); Adapter\ArrayAdapter::setCache($cache); $this->assertTrue(Adapter\ArrayAdapter::hasCache()); $adapter = new Adapter\ArrayAdapter(dirname(__FILE__) . '/_files/translation_en.php', 'en'); $cache = Adapter\ArrayAdapter::getCache(); $this->assertTrue($cache instanceof Frontend\Core); $adapter->addTranslation(dirname(__FILE__) . '/_files/translation_en.php', 'ru', array('reload' => true)); $test = $adapter->getMessages('all'); $this->assertEquals(6, count($test['ru'])); }
/** * Make a control key with the string containing datas * * @param string $data Data * @param string $controlType Type of control 'md5', 'crc32' or 'strlen' * @throws \Zend\Cache\Exception * @return string Control key */ protected function _hash($data, $controlType) { switch ($controlType) { case 'md5': return md5($data); case 'crc32': return crc32($data); case 'strlen': return strlen($data); case 'adler32': return hash('adler32', $data); default: Cache\Cache::throwException("Incorrect hash function : {$controlType}"); } }
/** * Return the filling percentage of the backend storage * * @throws \Zend\Cache\Exception * @return int integer between 0 and 100 */ public function getFillingPercentage() { $mems = $this->_memcache->getExtendedStats(); $memSize = null; $memUsed = null; foreach ($mems as $key => $mem) { if ($mem === false) { $this->_log('can\'t get stat from ' . $key); continue; } $eachSize = $mem['limit_maxbytes']; $eachUsed = $mem['bytes']; if ($eachUsed > $eachSize) { $eachUsed = $eachSize; } $memSize += $eachSize; $memUsed += $eachUsed; } if ($memSize === null || $memUsed === null) { Cache\Cache::throwException('Can\'t get filling percentage'); } return (int) (100.0 * ($memUsed / $memSize)); }
/** * Change the master_file option * * @param string $masterFile the complete path and name of the master file */ public function setMasterFiles($masterFiles) { clearstatcache(); $this->_specificOptions['master_file'] = $masterFiles[0]; // to keep a compatibility $this->_specificOptions['master_files'] = $masterFiles; $this->_masterFile_mtimes = array(); $i = 0; foreach ($masterFiles as $masterFile) { $this->_masterFile_mtimes[$i] = @filemtime($masterFile); if (!$this->_specificOptions['ignore_missing_master_files'] && !$this->_masterFile_mtimes[$i]) { Cache::throwException('Unable to read master_file : ' . $masterFile); } $i++; } }