Commit 915033c4 by lmf

补充vendor忽略文件

parent 140e5076
<?php
/*
* This file is part of the Behat Gherkin.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Gherkin\Cache;
use Behat\Gherkin\Node\FeatureNode;
/**
* Parser cache interface.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
interface CacheInterface
{
/**
* Checks that cache for feature exists and is fresh.
*
* @param string $path Feature path
* @param integer $timestamp The last time feature was updated
*
* @return bool
*/
public function isFresh($path, $timestamp);
/**
* Reads feature cache from path.
*
* @param string $path Feature path
*
* @return FeatureNode
*/
public function read($path);
/**
* Caches feature node.
*
* @param string $path Feature path
* @param FeatureNode $feature Feature instance
*/
public function write($path, FeatureNode $feature);
}
<?php
/*
* This file is part of the Behat Gherkin.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Gherkin\Cache;
use Behat\Gherkin\Exception\CacheException;
use Behat\Gherkin\Node\FeatureNode;
use Behat\Gherkin\Gherkin;
/**
* File cache.
* Caches feature into a file.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class FileCache implements CacheInterface
{
private $path;
/**
* Initializes file cache.
*
* @param string $path Path to the folder where to store caches.
*
* @throws CacheException
*/
public function __construct($path)
{
$this->path = rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.'v'.Gherkin::VERSION;
if (!is_dir($this->path)) {
@mkdir($this->path, 0777, true);
}
if (!is_writeable($this->path)) {
throw new CacheException(sprintf('Cache path "%s" is not writeable. Check your filesystem permissions or disable Gherkin file cache.', $this->path));
}
}
/**
* Checks that cache for feature exists and is fresh.
*
* @param string $path Feature path
* @param integer $timestamp The last time feature was updated
*
* @return bool
*/
public function isFresh($path, $timestamp)
{
$cachePath = $this->getCachePathFor($path);
if (!file_exists($cachePath)) {
return false;
}
return filemtime($cachePath) > $timestamp;
}
/**
* Reads feature cache from path.
*
* @param string $path Feature path
*
* @return FeatureNode
*
* @throws CacheException
*/
public function read($path)
{
$cachePath = $this->getCachePathFor($path);
$feature = unserialize(file_get_contents($cachePath));
if (!$feature instanceof FeatureNode) {
throw new CacheException(sprintf('Can not load cache for a feature "%s" from "%s".', $path, $cachePath ));
}
return $feature;
}
/**
* Caches feature node.
*
* @param string $path Feature path
* @param FeatureNode $feature Feature instance
*/
public function write($path, FeatureNode $feature)
{
file_put_contents($this->getCachePathFor($path), serialize($feature));
}
/**
* Returns feature cache file path from features path.
*
* @param string $path Feature path
*
* @return string
*/
protected function getCachePathFor($path)
{
return $this->path.'/'.md5($path).'.feature.cache';
}
}
<?php
/*
* This file is part of the Behat Gherkin.
* (c) Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\Gherkin\Cache;
use Behat\Gherkin\Node\FeatureNode;
/**
* Memory cache.
* Caches feature into a memory.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class MemoryCache implements CacheInterface
{
private $features = array();
private $timestamps = array();
/**
* Checks that cache for feature exists and is fresh.
*
* @param string $path Feature path
* @param integer $timestamp The last time feature was updated
*
* @return bool
*/
public function isFresh($path, $timestamp)
{
if (!isset($this->features[$path])) {
return false;
}
return $this->timestamps[$path] > $timestamp;
}
/**
* Reads feature cache from path.
*
* @param string $path Feature path
*
* @return FeatureNode
*/
public function read($path)
{
return $this->features[$path];
}
/**
* Caches feature node.
*
* @param string $path Feature path
* @param FeatureNode $feature Feature instance
*/
public function write($path, FeatureNode $feature)
{
$this->features[$path] = $feature;
$this->timestamps[$path] = time();
}
}
<?php
namespace Codeception\PHPUnit\Log;
use Codeception\Configuration;
use Codeception\Test\Interfaces\Reported;
use Codeception\Test\Test;
use PHPUnit\Framework\TestCase;
class JUnit extends \Codeception\PHPUnit\NonFinal\JUnit
{
protected $strictAttributes = ['file', 'name', 'class'];
public function startTest(\PHPUnit\Framework\Test $test):void
{
if (!$test instanceof Reported) {
parent::startTest($test);
return;
}
$this->currentTestCase = $this->document->createElement('testcase');
$isStrict = Configuration::config()['settings']['strict_xml'];
foreach ($test->getReportFields() as $attr => $value) {
if ($isStrict and !in_array($attr, $this->strictAttributes)) {
continue;
}
$this->currentTestCase->setAttribute($attr, $value);
}
}
public function endTest(\PHPUnit\Framework\Test $test, float $time):void
{
if ($this->currentTestCase !== null and $test instanceof Test) {
$numAssertions = $test->getNumAssertions();
$this->testSuiteAssertions[$this->testSuiteLevel] += $numAssertions;
$this->currentTestCase->setAttribute(
'assertions',
$numAssertions
);
}
if ($test instanceof TestCase) {
parent::endTest($test, $time);
return;
}
// since PhpUnit 7.4.0, parent::endTest ignores tests that aren't instances of TestCase
// so I copied this code from PhpUnit 7.3.5
$this->currentTestCase->setAttribute(
'time',
\sprintf('%F', $time)
);
$this->testSuites[$this->testSuiteLevel]->appendChild(
$this->currentTestCase
);
$this->testSuiteTests[$this->testSuiteLevel]++;
$this->testSuiteTimes[$this->testSuiteLevel] += $time;
$this->currentTestCase = null;
}
}
<?php
namespace Codeception\PHPUnit\Log;
use Codeception\Configuration;
use Codeception\Test\Interfaces\Reported;
use Codeception\Test\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;
class PhpUnit extends \Codeception\PHPUnit\NonFinal\JUnit
{
const SUITE_LEVEL = 1;
const FILE_LEVEL = 2;
protected $strictAttributes = ['file', 'name', 'class'];
private $currentFile;
private $currentFileSuite;
public function startTest(\PHPUnit\Framework\Test $test):void
{
if (method_exists($test, 'getFileName') ) {
$filename = $test->getFileName();
} else {
$reflector = new \ReflectionClass($test);
$filename = $reflector->getFileName();
}
if ($filename !== $this->currentFile) {
if ($this->currentFile !== null) {
parent::endTestSuite(new TestSuite());
}
//initialize all values to avoid warnings
$this->testSuiteAssertions[self::FILE_LEVEL] = 0;
$this->testSuiteTests[self::FILE_LEVEL] = 0;
$this->testSuiteTimes[self::FILE_LEVEL] = 0;
$this->testSuiteErrors[self::FILE_LEVEL] = 0;
$this->testSuiteFailures[self::FILE_LEVEL] = 0;
$this->testSuiteSkipped[self::FILE_LEVEL] = 0;
$this->testSuiteLevel = self::FILE_LEVEL;
$this->currentFile = $filename;
$this->currentFileSuite = $this->document->createElement('testsuite');
if ($test instanceof Reported) {
$reportFields = $test->getReportFields();
$class = isset($reportFields['class']) ? $reportFields['class'] : $reportFields['name'];
$this->currentFileSuite->setAttribute('name', $class);
} else {
$this->currentFileSuite->setAttribute('name', get_class($test));
}
$this->currentFileSuite->setAttribute('file', $filename);
$this->testSuites[self::SUITE_LEVEL]->appendChild($this->currentFileSuite);
$this->testSuites[self::FILE_LEVEL] = $this->currentFileSuite;
}
if (!$test instanceof Reported) {
parent::startTest($test);
return;
}
$this->currentTestCase = $this->document->createElement('testcase');
$isStrict = Configuration::config()['settings']['strict_xml'];
foreach ($test->getReportFields() as $attr => $value) {
if ($isStrict and !in_array($attr, $this->strictAttributes)) {
continue;
}
$this->currentTestCase->setAttribute($attr, $value);
}
}
public function endTest(\PHPUnit\Framework\Test $test, float $time):void
{
if ($this->currentTestCase !== null && $test instanceof Test) {
$numAssertions = $test->getNumAssertions();
$this->testSuiteAssertions[$this->testSuiteLevel] += $numAssertions;
$this->currentTestCase->setAttribute(
'assertions',
$numAssertions
);
}
if ($test instanceof TestCase) {
parent::endTest($test, $time);
return;
}
// In PhpUnit 7.4.*, parent::endTest ignores tests that aren't instances of TestCase
// so I copied this code from PhpUnit 7.3.5
$this->currentTestCase->setAttribute(
'time',
\sprintf('%F', $time)
);
$this->testSuites[$this->testSuiteLevel]->appendChild(
$this->currentTestCase
);
$this->testSuiteTests[$this->testSuiteLevel]++;
$this->testSuiteTimes[$this->testSuiteLevel] += $time;
$this->currentTestCase = null;
}
/**
* Cleans the mess caused by test suite manipulation in startTest
*/
public function endTestSuite(TestSuite $suite): void
{
if ($suite->getName()) {
if ($this->currentFile) {
//close last file in the test suite
parent::endTestSuite(new TestSuite());
$this->currentFile = null;
}
$this->testSuiteLevel = self::SUITE_LEVEL;
}
parent::endTestSuite($suite);
}
}
<?php
/*
==New BSD License==
Copyright (c) 2013, Colin Mollenhour
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The name of Colin Mollenhour may not be used to endorse or promote products
derived from this software without specific prior written permission.
* The class name must remain as Cm_Cache_Backend_Redis.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Redis adapter for Zend_Cache
*
* @copyright Copyright (c) 2013 Colin Mollenhour (http://colin.mollenhour.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @author Colin Mollenhour (http://colin.mollenhour.com)
*/
class Cm_Cache_Backend_Redis extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
const SET_IDS = 'zc:ids';
const SET_TAGS = 'zc:tags';
const PREFIX_KEY = 'zc:k:';
const PREFIX_TAG_IDS = 'zc:ti:';
const FIELD_DATA = 'd';
const FIELD_MTIME = 'm';
const FIELD_TAGS = 't';
const FIELD_INF = 'i';
const MAX_LIFETIME = 2592000; /* Redis backend limit */
const COMPRESS_PREFIX = ":\x1f\x8b";
const DEFAULT_CONNECT_TIMEOUT = 2.5;
const DEFAULT_CONNECT_RETRIES = 1;
const LUA_SAVE_SH1 = '1617c9fb2bda7d790bb1aaa320c1099d81825e64';
const LUA_CLEAN_SH1 = '42ab2fe548aee5ff540123687a2c39a38b54e4a2';
const LUA_GC_SH1 = 'c00416b970f1aa6363b44965d4cf60ee99a6f065';
/** @var Credis_Client */
protected $_redis;
/** @var bool */
protected $_notMatchingTags = FALSE;
/** @var int */
protected $_lifetimelimit = self::MAX_LIFETIME; /* Redis backend limit */
/** @var int|bool */
protected $_compressTags = 1;
/** @var int|bool */
protected $_compressData = 1;
/** @var int */
protected $_compressThreshold = 20480;
/** @var string */
protected $_compressionLib;
/**
* On large data sets SUNION slows down considerably when used with too many arguments
* so this is used to chunk the SUNION into a few commands where the number of set ids
* exceeds this setting.
*
* @var int
*/
protected $_sunionChunkSize = 500;
/** @var bool */
protected $_useLua = false;
/** @var integer */
protected $_autoExpireLifetime = 0;
/** @var string */
protected $_autoExpirePattern = '/REQEST/';
/** @var boolean */
protected $_autoExpireRefreshOnLoad = false;
/**
* Lua's unpack() has a limit on the size of the table imposed by
* the number of Lua stack slots that a C function can use.
* This value is defined by LUAI_MAXCSTACK in luaconf.h and for Redis it is set to 8000.
*
* @see https://github.com/antirez/redis/blob/b903145/deps/lua/src/luaconf.h#L439
* @var int
*/
protected $_luaMaxCStack = 5000;
/**
* If 'retry_reads_on_master' is truthy then reads will be retried against master when slave returns "(nil)" value
*
* @var boolean
*/
protected $_retryReadsOnMaster = false;
/**
* @var stdClass
*/
protected $_clientOptions;
/**
* If 'load_from_slaves' is truthy then reads are performed on a randomly selected slave server
*
* @var Credis_Client
*/
protected $_slave;
protected function getClientOptions($options = array())
{
$clientOptions = new stdClass();
$clientOptions->forceStandalone = isset($options['force_standalone']) && $options['force_standalone'];
$clientOptions->connectRetries = isset($options['connect_retries']) ? (int) $options['connect_retries'] : self::DEFAULT_CONNECT_RETRIES;
$clientOptions->readTimeout = isset($options['read_timeout']) ? (float) $options['read_timeout'] : NULL;
$clientOptions->password = isset($options['password']) ? $options['password'] : NULL;
$clientOptions->database = isset($options['database']) ? (int) $options['database'] : 0;
$clientOptions->persistent = isset($options['persistent']) ? $options['persistent'] : '';
$clientOptions->timeout = isset($options['timeout']) ? $options['timeout'] : self::DEFAULT_CONNECT_TIMEOUT;
return $clientOptions;
}
/**
* Construct Zend_Cache Redis backend
* @param array $options
* @return \Cm_Cache_Backend_Redis
*/
public function __construct($options = array())
{
if ( empty($options['server']) && empty($options['cluster'])) {
Zend_Cache::throwException('Redis \'server\' not specified.');
}
$this->_clientOptions = $this->getClientOptions($options);
// If 'sentinel_master' is specified then server is actually sentinel and master address should be fetched from server.
$sentinelMaster = empty($options['sentinel_master']) ? NULL : $options['sentinel_master'];
if ($sentinelMaster) {
$sentinelClientOptions = isset($options['sentinel']) && is_array($options['sentinel'])
? $this->getClientOptions($options['sentinel'] + $options)
: $this->_clientOptions;
$servers = preg_split('/\s*,\s*/', trim($options['server']), NULL, PREG_SPLIT_NO_EMPTY);
$sentinel = NULL;
$exception = NULL;
for ($i = 0; $i <= $sentinelClientOptions->connectRetries; $i++) // Try each sentinel in round-robin fashion
foreach ($servers as $server) {
try {
$sentinelClient = new Credis_Client($server, NULL, $sentinelClientOptions->timeout, $sentinelClientOptions->persistent);
$sentinelClient->forceStandalone();
$sentinelClient->setMaxConnectRetries(0);
if ($sentinelClientOptions->readTimeout) {
$sentinelClient->setReadTimeout($sentinelClientOptions->readTimeout);
}
// Sentinel currently doesn't support AUTH
//if ($password) {
// $sentinelClient->auth($password) or Zend_Cache::throwException('Unable to authenticate with the redis sentinel.');
//}
$sentinel = new Credis_Sentinel($sentinelClient);
$sentinel
->setClientTimeout($this->_clientOptions->timeout)
->setClientPersistent($this->_clientOptions->persistent);
$redisMaster = $sentinel->getMasterClient($sentinelMaster);
$this->_applyClientOptions($redisMaster);
// Verify connected server is actually master as per Sentinel client spec
if ( ! empty($options['sentinel_master_verify'])) {
$roleData = $redisMaster->role();
if ( ! $roleData || $roleData[0] != 'master') {
usleep(100000); // Sleep 100ms and try again
$redisMaster = $sentinel->getMasterClient($sentinelMaster);
$this->_applyClientOptions($redisMaster);
$roleData = $redisMaster->role();
if ( ! $roleData || $roleData[0] != 'master') {
Zend_Cache::throwException('Unable to determine master redis server.');
}
}
}
$this->_redis = $redisMaster;
break 2;
} catch (Exception $e) {
unset($sentinelClient);
$exception = $e;
}
}
if ( ! $this->_redis) {
Zend_Cache::throwException('Unable to connect to a redis sentinel: '.$exception->getMessage(), $exception);
}
// Optionally use read slaves - will only be used for 'load' operation
if ( ! empty($options['load_from_slaves'])) {
$slaves = $sentinel->getSlaveClients($sentinelMaster);
if ($slaves) {
if ($options['load_from_slaves'] == 2) {
array_push($slaves, $this->_redis); // Also send reads to the master
}
$slaveSelect = isset($options['slave_select_callable']) && is_callable($options['slave_select_callable']) ? $options['slave_select_callable'] : null;
if ($slaveSelect) {
$slave = $slaveSelect($slaves, $this->_redis);
} else {
$slaveKey = array_rand($slaves, 1);
$slave = $slaves[$slaveKey]; /* @var $slave Credis_Client */
}
if ($slave instanceof Credis_Client && $slave != $this->_redis) {
try {
$this->_applyClientOptions($slave, TRUE);
$this->_slave = $slave;
} catch (Exception $e) {
// If there is a problem with first slave then skip 'load_from_slaves' option
}
}
}
}
unset($sentinel);
}
// Instantiate Credis_Cluster
// DEPRECATED
else if ( ! empty($options['cluster'])) {
$this->_setupReadWriteCluster($options);
}
// Direct connection to single Redis server and optional slaves
else {
$port = isset($options['port']) ? $options['port'] : 6379;
$this->_redis = new Credis_Client($options['server'], $port, $this->_clientOptions->timeout, $this->_clientOptions->persistent);
$this->_applyClientOptions($this->_redis);
// Support loading from a replication slave
if (isset($options['load_from_slave'])) {
if (is_array($options['load_from_slave'])) {
if (isset($options['load_from_slave']['server'])) { // Single slave
$server = $options['load_from_slave']['server'];
$port = $options['load_from_slave']['port'];
$clientOptions = $this->getClientOptions($options['load_from_slave'] + $options);
$totalServers = 2;
} else { // Multiple slaves
$slaveKey = array_rand($options['load_from_slave'], 1);
$slave = $options['load_from_slave'][$slaveKey];
$server = $slave['server'];
$port = $slave['port'];
$clientOptions = $this->getClientOptions($slave + $options);
$totalServers = count($options['load_from_slave']) + 1;
}
} else { // String
$server = $options['load_from_slave'];
$port = 6379;
$clientOptions = $this->_clientOptions;
// If multiple addresses are given, split and choose a random one
if (strpos($server, ',') !== FALSE) {
$slaves = preg_split('/\s*,\s*/', $server, -1, PREG_SPLIT_NO_EMPTY);
$slaveKey = array_rand($slaves, 1);
$server = $slaves[$slaveKey];
$port = NULL;
$totalServers = count($slaves) + 1;
} else {
$totalServers = 2;
}
}
// Skip setting up slave if master is not write only and it is randomly chosen to be the read server
$masterWriteOnly = isset($options['master_write_only']) ? (int) $options['master_write_only'] : FALSE;
if (is_string($server) && $server && ! (!$masterWriteOnly && rand(1,$totalServers) === 1)) {
try {
$slave = new Credis_Client($server, $port, $clientOptions->timeout, $clientOptions->persistent);
$this->_applyClientOptions($slave, TRUE, $clientOptions);
$this->_slave = $slave;
} catch (Exception $e) {
// Slave will not be used
}
}
}
}
if ( isset($options['notMatchingTags']) ) {
$this->_notMatchingTags = (bool) $options['notMatchingTags'];
}
if ( isset($options['compress_tags'])) {
$this->_compressTags = (int) $options['compress_tags'];
}
if ( isset($options['compress_data'])) {
$this->_compressData = (int) $options['compress_data'];
}
if ( isset($options['lifetimelimit'])) {
$this->_lifetimelimit = (int) min($options['lifetimelimit'], self::MAX_LIFETIME);
}
if ( isset($options['compress_threshold'])) {
$this->_compressThreshold = (int) $options['compress_threshold'];
if ($this->_compressThreshold < 1) {
$this->_compressThreshold = 1;
}
}
if ( isset($options['automatic_cleaning_factor']) ) {
$this->_options['automatic_cleaning_factor'] = (int) $options['automatic_cleaning_factor'];
} else {
$this->_options['automatic_cleaning_factor'] = 0;
}
if ( isset($options['compression_lib']) ) {
$this->_compressionLib = (string) $options['compression_lib'];
}
else if ( function_exists('snappy_compress') ) {
$this->_compressionLib = 'snappy';
}
else if ( function_exists('lz4_compress')) {
$version = phpversion("lz4");
if (version_compare($version, "0.3.0") < 0)
{
$this->_compressTags = $this->_compressTags > 1 ? true : false;
$this->_compressData = $this->_compressData > 1 ? true : false;
}
$this->_compressionLib = 'l4z';
}
else if ( function_exists('zstd_compress')) {
$version = phpversion("zstd");
if (version_compare($version, "0.4.13") < 0)
{
$this->_compressTags = $this->_compressTags > 1 ? true : false;
$this->_compressData = $this->_compressData > 1 ? true : false;
}
$this->_compressionLib = 'zstd';
}
else if ( function_exists('lzf_compress') ) {
$this->_compressionLib = 'lzf';
}
else {
$this->_compressionLib = 'gzip';
}
$this->_compressPrefix = substr($this->_compressionLib,0,2).self::COMPRESS_PREFIX;
if ( isset($options['sunion_chunk_size']) && $options['sunion_chunk_size'] > 0) {
$this->_sunionChunkSize = (int) $options['sunion_chunk_size'];
}
if (isset($options['use_lua'])) {
$this->_useLua = (bool) $options['use_lua'];
}
if (isset($options['lua_max_c_stack'])) {
$this->_luaMaxCStack = (int) $options['lua_max_c_stack'];
}
if (isset($options['retry_reads_on_master'])) {
$this->_retryReadsOnMaster = (bool) $options['retry_reads_on_master'];
}
if (isset($options['auto_expire_lifetime'])) {
$this->_autoExpireLifetime = (int) $options['auto_expire_lifetime'];
}
if (isset($options['auto_expire_pattern'])) {
$this->_autoExpirePattern = (string) $options['auto_expire_pattern'];
}
if (isset($options['auto_expire_refresh_on_load'])) {
$this->_autoExpireRefreshOnLoad = (bool) $options['auto_expire_refresh_on_load'];
}
}
/**
* Apply common configuration to client instances.
*
* @param Credis_Client $client
*/
protected function _applyClientOptions(Credis_Client $client, $forceSelect = FALSE, $clientOptions = null)
{
if ($clientOptions === null) {
$clientOptions = $this->_clientOptions;
}
if ($clientOptions->forceStandalone) {
$client->forceStandalone();
}
$client->setMaxConnectRetries($clientOptions->connectRetries);
if ($clientOptions->readTimeout) {
$client->setReadTimeout($clientOptions->readTimeout);
}
if ($clientOptions->password) {
$client->auth($clientOptions->password) or Zend_Cache::throwException('Unable to authenticate with the redis server.');
}
// Always select database when persistent is used in case connection is re-used by other clients
if ($forceSelect || $clientOptions->database || $client->getPersistence()) {
$client->select($clientOptions->database) or Zend_Cache::throwException('The redis database could not be selected.');
}
}
/**
* @deprecated - Previously this setup an instance of Credis_Cluster but this class was not complete or flawed
* @param $options
*/
protected function _setupReadWriteCluster($options)
{
if (!empty($options['cluster']['master'])) {
foreach ($options['cluster']['master'] as $masterNode) {
if (empty($masterNode['server']) || empty($masterNode['port'])) {
continue;
}
$this->_redis = new Credis_Client(
$masterNode['host'],
$masterNode['port'],
isset($masterNode['timeout']) ? $masterNode['timeout'] : 2.5,
isset($masterNode['persistent']) ? $masterNode['persistent'] : ''
);
$this->_applyClientOptions($this->_redis);
break;
}
}
if (!empty($options['cluster']['slave'])) {
$slaveKey = array_rand($options['cluster']['slave'], 1);
$slave = $options['cluster']['slave'][$slaveKey];
$this->_slave = new Credis_Client(
$slave['host'],
$slave['port'],
isset($slave['timeout']) ? $slave['timeout'] : 2.5,
isset($slave['persistent']) ? $slave['persistent'] : ''
);
$this->_applyClientOptions($this->_redis, TRUE);
}
}
/**
* Load value with given id from cache
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return bool|string
*/
public function load($id, $doNotTestCacheValidity = false)
{
if ($this->_slave) {
$data = $this->_slave->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
// Prevent compounded effect of cache flood on asynchronously replicating master/slave setup
if ($this->_retryReadsOnMaster && $data === false) {
$data = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
}
} else {
$data = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_DATA);
}
if ($data === NULL) {
return FALSE;
}
$decoded = $this->_decodeData($data);
if ($this->_autoExpireLifetime === 0 || !$this->_autoExpireRefreshOnLoad) {
return $decoded;
}
$matches = $this->_matchesAutoExpiringPattern($id);
if (!$matches) {
return $decoded;
}
$this->_redis->expire(self::PREFIX_KEY.$id, min($this->_autoExpireLifetime, self::MAX_LIFETIME));
return $decoded;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return bool|int False if record is not available or "last modified" timestamp of the available cache record
*/
public function test($id)
{
// Don't use slave for this since `test` is usually used for locking
$mtime = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_MTIME);
return ($mtime ? $mtime : FALSE);
}
/**
* Get the life time
*
* if $specificLifetime is not false, the given specific life time is used
* else, the global lifetime is used
*
* @param int $specificLifetime
* @return int Cache life time
*/
public function getLifetime($specificLifetime)
{
// Lifetimes set via Layout XMLs get parsed as string so bool(false) becomes string("false")
if ($specificLifetime === 'false') {
$specificLifetime = false;
}
return parent::getLifetime($specificLifetime);
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param bool|int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @throws CredisException
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
if(!is_array($tags))
$tags = $tags ? array($tags) : array();
else
$tags = array_flip(array_flip($tags));
$lifetime = (int)$this->_getAutoExpiringLifetime($this->getLifetime($specificLifetime), $id);
if ($this->_useLua) {
$sArgs = array(
self::PREFIX_KEY,
self::FIELD_DATA,
self::FIELD_TAGS,
self::FIELD_MTIME,
self::FIELD_INF,
self::SET_TAGS,
self::PREFIX_TAG_IDS,
self::SET_IDS,
$id,
$this->_encodeData($data, $this->_compressData),
$this->_encodeData(implode(',',$tags), $this->_compressTags),
time(),
$lifetime ? 0 : 1,
min($lifetime, self::MAX_LIFETIME),
$this->_notMatchingTags ? 1 : 0
);
$res = $this->_redis->evalSha(self::LUA_SAVE_SH1, $tags, $sArgs);
if (is_null($res)) {
$script =
"local oldTags = redis.call('HGET', ARGV[1]..ARGV[9], ARGV[3]) ".
"redis.call('HMSET', ARGV[1]..ARGV[9], ARGV[2], ARGV[10], ARGV[3], ARGV[11], ARGV[4], ARGV[12], ARGV[5], ARGV[13]) ".
"if (ARGV[13] == '0') then ".
"redis.call('EXPIRE', ARGV[1]..ARGV[9], ARGV[14]) ".
"end ".
"if next(KEYS) ~= nil then ".
"redis.call('SADD', ARGV[6], unpack(KEYS)) ".
"for _, tagname in ipairs(KEYS) do ".
"redis.call('SADD', ARGV[7]..tagname, ARGV[9]) ".
"end ".
"end ".
"if (ARGV[15] == '1') then ".
"redis.call('SADD', ARGV[8], ARGV[9]) ".
"end ".
"if (oldTags ~= false) then ".
"return oldTags ".
"else ".
"return '' ".
"end";
$res = $this->_redis->eval($script, $tags, $sArgs);
}
// Process removed tags if cache entry already existed
if ($res) {
$oldTags = explode(',', $this->_decodeData($res));
if ($remTags = ($oldTags ? array_diff($oldTags, $tags) : FALSE))
{
// Update the id list for each tag
foreach($remTags as $tag)
{
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $id);
}
}
}
return TRUE;
}
// Get list of tags previously assigned
$oldTags = $this->_decodeData($this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_TAGS));
$oldTags = $oldTags ? explode(',', $oldTags) : array();
$this->_redis->pipeline()->multi();
// Set the data
$result = $this->_redis->hMSet(self::PREFIX_KEY.$id, array(
self::FIELD_DATA => $this->_encodeData($data, $this->_compressData),
self::FIELD_TAGS => $this->_encodeData(implode(',',$tags), $this->_compressTags),
self::FIELD_MTIME => time(),
self::FIELD_INF => $lifetime ? 0 : 1,
));
if( ! $result) {
throw new CredisException("Could not set cache key $id");
}
// Set expiration if specified
if ($lifetime) {
$this->_redis->expire(self::PREFIX_KEY.$id, min($lifetime, self::MAX_LIFETIME));
}
// Process added tags
if ($tags)
{
// Update the list with all the tags
$this->_redis->sAdd( self::SET_TAGS, $tags);
// Update the id list for each tag
foreach($tags as $tag)
{
$this->_redis->sAdd(self::PREFIX_TAG_IDS . $tag, $id);
}
}
// Process removed tags
if ($remTags = ($oldTags ? array_diff($oldTags, $tags) : FALSE))
{
// Update the id list for each tag
foreach($remTags as $tag)
{
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $id);
}
}
// Update the list with all the ids
if($this->_notMatchingTags) {
$this->_redis->sAdd(self::SET_IDS, $id);
}
$this->_redis->exec();
return TRUE;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
// Get list of tags for this id
$tags = explode(',', $this->_decodeData($this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_TAGS)));
$this->_redis->pipeline()->multi();
// Remove data
$this->_redis->del(self::PREFIX_KEY.$id);
// Remove id from list of all ids
if($this->_notMatchingTags) {
$this->_redis->sRem( self::SET_IDS, $id );
}
// Update the id list for each tag
foreach($tags as $tag) {
$this->_redis->sRem(self::PREFIX_TAG_IDS . $tag, $id);
}
$result = $this->_redis->exec();
return (bool) $result[0];
}
/**
* @param array $tags
*/
protected function _removeByNotMatchingTags($tags)
{
$ids = $this->getIdsNotMatchingTags($tags);
if($ids)
{
$this->_redis->pipeline()->multi();
// Remove data
$this->_redis->del( $this->_preprocessIds($ids));
// Remove ids from list of all ids
if($this->_notMatchingTags) {
$this->_redis->sRem( self::SET_IDS, $ids);
}
$this->_redis->exec();
}
}
/**
* @param array $tags
*/
protected function _removeByMatchingTags($tags)
{
$ids = $this->getIdsMatchingTags($tags);
if($ids)
{
$this->_redis->pipeline()->multi();
// Remove data
$this->_redis->del( $this->_preprocessIds($ids));
// Remove ids from list of all ids
if($this->_notMatchingTags) {
$this->_redis->sRem( self::SET_IDS, $ids);
}
$this->_redis->exec();
}
}
/**
* @param array $tags
*/
protected function _removeByMatchingAnyTags($tags)
{
if ($this->_useLua) {
$tags = array_chunk($tags, $this->_sunionChunkSize);
foreach ($tags as $chunk) {
$chunk = $this->_preprocessTagIds($chunk);
$args = array(self::PREFIX_KEY, self::SET_TAGS, self::SET_IDS, ($this->_notMatchingTags ? 1 : 0), (int) $this->_luaMaxCStack);
if ( ! $this->_redis->evalSha(self::LUA_CLEAN_SH1, $chunk, $args)) {
$script =
"for i = 1, #KEYS, ARGV[5] do ".
"local keysToDel = redis.call('SUNION', unpack(KEYS, i, math.min(#KEYS, i + ARGV[5] - 1))) ".
"for _, keyname in ipairs(keysToDel) do ".
"redis.call('DEL', ARGV[1]..keyname) ".
"if (ARGV[4] == '1') then ".
"redis.call('SREM', ARGV[3], keyname) ".
"end ".
"end ".
"redis.call('DEL', unpack(KEYS, i, math.min(#KEYS, i + ARGV[5] - 1))) ".
"redis.call('SREM', ARGV[2], unpack(KEYS, i, math.min(#KEYS, i + ARGV[5] - 1))) ".
"end ".
"return true";
$this->_redis->eval($script, $chunk, $args);
}
}
return;
}
$ids = $this->getIdsMatchingAnyTags($tags);
$this->_redis->pipeline()->multi();
if($ids)
{
// Remove data
$this->_redis->del( $this->_preprocessIds($ids));
// Remove ids from list of all ids
if($this->_notMatchingTags) {
$this->_redis->sRem( self::SET_IDS, $ids);
}
}
// Remove tag id lists
$this->_redis->del( $this->_preprocessTagIds($tags));
// Remove tags from list of tags
$this->_redis->sRem( self::SET_TAGS, $tags);
$this->_redis->exec();
}
/**
* Clean up tag id lists since as keys expire the ids remain in the tag id lists
*/
protected function _collectGarbage()
{
// Clean up expired keys from tag id set and global id set
if ($this->_useLua) {
$sArgs = array(self::PREFIX_KEY, self::SET_TAGS, self::SET_IDS, self::PREFIX_TAG_IDS, ($this->_notMatchingTags ? 1 : 0));
$allTags = (array) $this->_redis->sMembers(self::SET_TAGS);
$tagsCount = count($allTags);
$counter = 0;
$tagsBatch = array();
foreach ($allTags as $tag) {
$tagsBatch[] = $tag;
$counter++;
if (count($tagsBatch) == 10 || $counter == $tagsCount ) {
if ( ! $this->_redis->evalSha(self::LUA_GC_SH1, $tagsBatch, $sArgs)) {
$script =
"local tagKeys = {} ".
"local expired = {} ".
"local expiredCount = 0 ".
"local notExpiredCount = 0 ".
"for _, tagName in ipairs(KEYS) do ".
"tagKeys = redis.call('SMEMBERS', ARGV[4]..tagName) ".
"for __, keyName in ipairs(tagKeys) do ".
"if (redis.call('EXISTS', ARGV[1]..keyName) == 0) then ".
"expiredCount = expiredCount + 1 ".
"expired[expiredCount] = keyName ".
/* Redis Lua scripts have a hard limit of 8000 parameters per command */
"if (expiredCount == 7990) then ".
"redis.call('SREM', ARGV[4]..tagName, unpack(expired)) ".
"if (ARGV[5] == '1') then ".
"redis.call('SREM', ARGV[3], unpack(expired)) ".
"end ".
"expiredCount = 0 ".
"expired = {} ".
"end ".
"else ".
"notExpiredCount = notExpiredCount + 1 ".
"end ".
"end ".
"if (expiredCount > 0) then ".
"redis.call('SREM', ARGV[4]..tagName, unpack(expired)) ".
"if (ARGV[5] == '1') then ".
"redis.call('SREM', ARGV[3], unpack(expired)) ".
"end ".
"end ".
"if (notExpiredCount == 0) then ".
"redis.call ('DEL', ARGV[4]..tagName) ".
"redis.call ('SREM', ARGV[2], tagName) ".
"end ".
"expired = {} ".
"expiredCount = 0 ".
"notExpiredCount = 0 ".
"end ".
"return true";
$this->_redis->eval($script, $tagsBatch, $sArgs);
}
$tagsBatch = array();
/* Give Redis some time to handle other requests */
usleep(20000);
}
}
return;
}
$exists = array();
$tags = (array) $this->_redis->sMembers(self::SET_TAGS);
foreach($tags as $tag)
{
// Get list of expired ids for each tag
$tagMembers = $this->_redis->sMembers(self::PREFIX_TAG_IDS . $tag);
$numTagMembers = count($tagMembers);
$expired = array();
$numExpired = $numNotExpired = 0;
if($numTagMembers) {
while ($id = array_pop($tagMembers)) {
if( ! isset($exists[$id])) {
$exists[$id] = $this->_redis->exists(self::PREFIX_KEY.$id);
}
if ($exists[$id]) {
$numNotExpired++;
}
else {
$numExpired++;
$expired[] = $id;
// Remove incrementally to reduce memory usage
if (count($expired) % 100 == 0 && $numNotExpired > 0) {
$this->_redis->sRem( self::PREFIX_TAG_IDS . $tag, $expired);
if($this->_notMatchingTags) { // Clean up expired ids from ids set
$this->_redis->sRem( self::SET_IDS, $expired);
}
$expired = array();
}
}
}
if( ! count($expired)) continue;
}
// Remove empty tags or completely expired tags
if ($numExpired == $numTagMembers) {
$this->_redis->del(self::PREFIX_TAG_IDS . $tag);
$this->_redis->sRem(self::SET_TAGS, $tag);
}
// Clean up expired ids from tag ids set
else if (count($expired)) {
$this->_redis->sRem( self::PREFIX_TAG_IDS . $tag, $expired);
if($this->_notMatchingTags) { // Clean up expired ids from ids set
$this->_redis->sRem( self::SET_IDS, $expired);
}
}
unset($expired);
}
// Clean up global list of ids for ids with no tag
if($this->_notMatchingTags) {
// TODO
}
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => runs _collectGarbage()
* 'matchingTag' => supported
* 'notMatchingTag' => supported
* 'matchingAnyTag' => supported
*
* @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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if( $tags && ! is_array($tags)) {
$tags = array($tags);
}
try {
if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
return $this->_redis->flushDb();
}
if ($mode == Zend_Cache::CLEANING_MODE_OLD) {
$this->_collectGarbage();
return TRUE;
}
if ( ! count($tags)) {
return TRUE;
}
switch ($mode)
{
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$this->_removeByMatchingTags($tags);
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$this->_removeByNotMatchingTags($tags);
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_removeByMatchingAnyTags($tags);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method: '.$mode);
}
} catch (CredisException $e) {
Zend_Cache::throwException('Error cleaning cache by mode '.$mode.': '.$e->getMessage(), $e);
}
return TRUE;
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return TRUE;
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
parent::setDirectives($directives);
$lifetime = $this->getLifetime(false);
if ($lifetime > self::MAX_LIFETIME) {
Zend_Cache::throwException('Redis backend has a limit of 30 days (2592000 seconds) for the lifetime');
}
}
/**
* Get the auto expiring lifetime.
*
* Mainly a workaround for the issues that arise due to the fact that
* Magento's Enterprise_PageCache module doesn't set any expiry.
*
* @param int $specificLifetime
* @param string $id
* @return int Cache life time
*/
protected function _getAutoExpiringLifetime($lifetime, $id)
{
if ($lifetime || !$this->_autoExpireLifetime) {
// If it's already truthy, or there's no auto expire go with it.
return $lifetime;
}
$matches = $this->_matchesAutoExpiringPattern($id);
if (!$matches) {
// Only apply auto expire for keys that match the pattern
return $lifetime;
}
if ($this->_autoExpireLifetime > 0) {
// Return the auto expire lifetime if set
return $this->_autoExpireLifetime;
}
// Return whatever it was set to.
return $lifetime;
}
protected function _matchesAutoExpiringPattern($id)
{
$matches = array();
preg_match($this->_autoExpirePattern, $id, $matches);
return !empty($matches);
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
if($this->_notMatchingTags) {
return (array) $this->_redis->sMembers(self::SET_IDS);
} else {
$keys = $this->_redis->keys(self::PREFIX_KEY . '*');
$prefixLen = strlen(self::PREFIX_KEY);
foreach($keys as $index => $key) {
$keys[$index] = substr($key, $prefixLen);
}
return $keys;
}
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return (array) $this->_redis->sMembers(self::SET_TAGS);
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
if ($tags) {
return (array) $this->_redis->sInter( $this->_preprocessTagIds($tags) );
}
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a negated logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
if( ! $this->_notMatchingTags) {
Zend_Cache::throwException("notMatchingTags is currently disabled.");
}
if ($tags) {
return (array) $this->_redis->sDiff( self::SET_IDS, $this->_preprocessTagIds($tags) );
}
return (array) $this->_redis->sMembers( self::SET_IDS );
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$result = array();
if ($tags) {
$chunks = array_chunk($tags, $this->_sunionChunkSize);
foreach ($chunks as $chunk) {
$result = array_merge($result, (array) $this->_redis->sUnion( $this->_preprocessTagIds($chunk)));
}
if (count($chunks) > 1) {
$result = array_unique($result); // since we are chunking requests, we must de-duplicate member names
}
}
return $result;
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$maxMem = $this->_redis->config('GET','maxmemory');
if (0 == (int) $maxMem['maxmemory']) {
return 1;
}
$info = $this->_redis->info();
return (int) round(
($info['used_memory']/$maxMem['maxmemory']*100)
,0
,PHP_ROUND_HALF_UP
);
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
list($tags, $mtime, $inf) = array_values(
$this->_redis->hMGet(self::PREFIX_KEY.$id, array(self::FIELD_TAGS, self::FIELD_MTIME, self::FIELD_INF))
);
if( ! $mtime) {
return FALSE;
}
$tags = explode(',', $this->_decodeData($tags));
$expire = $inf === '1' ? FALSE : time() + $this->_redis->ttl(self::PREFIX_KEY.$id);
return array(
'expire' => $expire,
'tags' => $tags,
'mtime' => $mtime,
);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
list($inf) = $this->_redis->hGet(self::PREFIX_KEY.$id, self::FIELD_INF);
if ($inf === '0') {
$expireAt = time() + $this->_redis->ttl(self::PREFIX_KEY.$id) + $extraLifetime;
return (bool) $this->_redis->expireAt(self::PREFIX_KEY.$id, $expireAt);
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => ($this->_options['automatic_cleaning_factor'] > 0),
'tags' => true,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => true,
'get_list' => true,
);
}
/**
* @param string $data
* @param int $level
* @throws CredisException
* @return string
*/
protected function _encodeData($data, $level)
{
if ($this->_compressionLib && $level !== 0 && strlen($data) >= $this->_compressThreshold) {
switch($this->_compressionLib) {
case 'snappy': $data = snappy_compress($data); break;
case 'lzf': $data = lzf_compress($data); break;
case 'l4z': $data = lz4_compress($data, $level); break;
case 'zstd': $data = zstd_compress($data, $level); break;
case 'gzip': $data = gzcompress($data, $level); break;
default: throw new CredisException("Unrecognized 'compression_lib'.");
}
if( ! $data) {
throw new CredisException("Could not compress cache data.");
}
return $this->_compressPrefix.$data;
}
return $data;
}
/**
* @param bool|string $data
* @return string
*/
protected function _decodeData($data)
{
if (substr($data,2,3) == self::COMPRESS_PREFIX) {
switch(substr($data,0,2)) {
case 'sn': return snappy_uncompress(substr($data,5));
case 'lz': return lzf_decompress(substr($data,5));
case 'l4': return lz4_uncompress(substr($data,5));
case 'zs': return zstd_uncompress(substr($data,5));
case 'gz': case 'zc': return gzuncompress(substr($data,5));
}
}
return $data;
}
/**
* @param $item
* @param $index
* @param $prefix
*/
protected function _preprocess(&$item, $index, $prefix)
{
$item = $prefix . $item;
}
/**
* @param $ids
* @return array
*/
protected function _preprocessIds($ids)
{
array_walk($ids, array($this, '_preprocess'), self::PREFIX_KEY);
return $ids;
}
/**
* @param $tags
* @return array
*/
protected function _preprocessTagIds($tags)
{
array_walk($tags, array($this, '_preprocess'), self::PREFIX_TAG_IDS);
return $tags;
}
/**
* Required to pass unit tests
*
* @param string $id
* @return void
*/
public function ___expire($id)
{
$this->_redis->del(self::PREFIX_KEY.$id);
}
/**
* Only for unit tests
*/
public function ___scriptFlush()
{
$this->_redis->script('flush');
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
final class Cache implements CacheInterface
{
/**
* @var SignatureInterface
*/
private $signature;
/**
* @var array
*/
private $hashes = [];
public function __construct(SignatureInterface $signature)
{
$this->signature = $signature;
}
public function getSignature()
{
return $this->signature;
}
public function has($file)
{
return \array_key_exists($file, $this->hashes);
}
public function get($file)
{
if (!$this->has($file)) {
return null;
}
return $this->hashes[$file];
}
public function set($file, $hash)
{
$this->hashes[$file] = $hash;
}
public function clear($file)
{
unset($this->hashes[$file]);
}
public function toJson()
{
$json = json_encode([
'php' => $this->getSignature()->getPhpVersion(),
'version' => $this->getSignature()->getFixerVersion(),
'indent' => $this->getSignature()->getIndent(),
'lineEnding' => $this->getSignature()->getLineEnding(),
'rules' => $this->getSignature()->getRules(),
'hashes' => $this->hashes,
]);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new \UnexpectedValueException(sprintf(
'Can not encode cache signature to JSON, error: "%s". If you have non-UTF8 chars in your signature, like in license for `header_comment`, consider enabling `ext-mbstring` or install `symfony/polyfill-mbstring`.',
json_last_error_msg()
));
}
return $json;
}
/**
* @param string $json
*
* @throws \InvalidArgumentException
*
* @return Cache
*/
public static function fromJson($json)
{
$data = json_decode($json, true);
if (null === $data && JSON_ERROR_NONE !== json_last_error()) {
throw new \InvalidArgumentException(sprintf(
'Value needs to be a valid JSON string, got "%s", error: "%s".',
$json,
json_last_error_msg()
));
}
$requiredKeys = [
'php',
'version',
'indent',
'lineEnding',
'rules',
'hashes',
];
$missingKeys = array_diff_key(array_flip($requiredKeys), $data);
if (\count($missingKeys)) {
throw new \InvalidArgumentException(sprintf(
'JSON data is missing keys "%s"',
implode('", "', $missingKeys)
));
}
$signature = new Signature(
$data['php'],
$data['version'],
$data['indent'],
$data['lineEnding'],
$data['rules']
);
$cache = new self($signature);
$cache->hashes = $data['hashes'];
return $cache;
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
interface CacheInterface
{
/**
* @return SignatureInterface
*/
public function getSignature();
/**
* @param string $file
*
* @return bool
*/
public function has($file);
/**
* @param string $file
*
* @return null|int
*/
public function get($file);
/**
* @param string $file
* @param int $hash
*/
public function set($file, $hash);
/**
* @param string $file
*/
public function clear($file);
/**
* @return string
*/
public function toJson();
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*/
interface CacheManagerInterface
{
/**
* @param string $file
* @param string $fileContent
*
* @return bool
*/
public function needFixing($file, $fileContent);
/**
* @param string $file
* @param string $fileContent
*/
public function setFile($file, $fileContent);
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*/
final class Directory implements DirectoryInterface
{
/**
* @var string
*/
private $directoryName;
/**
* @param string $directoryName
*/
public function __construct($directoryName)
{
$this->directoryName = $directoryName;
}
public function getRelativePathTo($file)
{
$file = $this->normalizePath($file);
if (
'' === $this->directoryName
|| 0 !== stripos($file, $this->directoryName.\DIRECTORY_SEPARATOR)
) {
return $file;
}
return substr($file, \strlen($this->directoryName) + 1);
}
private function normalizePath($path)
{
return str_replace(['\\', '/'], \DIRECTORY_SEPARATOR, $path);
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*/
interface DirectoryInterface
{
/**
* @param string $file
*
* @return string
*/
public function getRelativePathTo($file);
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* Class supports caching information about state of fixing files.
*
* Cache is supported only for phar version and version installed via composer.
*
* File will be processed by PHP CS Fixer only if any of the following conditions is fulfilled:
* - cache is corrupt
* - fixer version changed
* - rules changed
* - file is new
* - file changed
*
* @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* @internal
*/
final class FileCacheManager implements CacheManagerInterface
{
/**
* @var FileHandlerInterface
*/
private $handler;
/**
* @var SignatureInterface
*/
private $signature;
/**
* @var CacheInterface
*/
private $cache;
/**
* @var bool
*/
private $isDryRun;
/**
* @var DirectoryInterface
*/
private $cacheDirectory;
/**
* @param bool $isDryRun
*/
public function __construct(
FileHandlerInterface $handler,
SignatureInterface $signature,
$isDryRun = false,
DirectoryInterface $cacheDirectory = null
) {
$this->handler = $handler;
$this->signature = $signature;
$this->isDryRun = $isDryRun;
$this->cacheDirectory = $cacheDirectory ?: new Directory('');
$this->readCache();
}
public function __destruct()
{
$this->writeCache();
}
/**
* This class is not intended to be serialized,
* and cannot be deserialized (see __wakeup method).
*/
public function __sleep()
{
throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
}
/**
* Disable the deserialization of the class to prevent attacker executing
* code by leveraging the __destruct method.
*
* @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection
*/
public function __wakeup()
{
throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
}
public function needFixing($file, $fileContent)
{
$file = $this->cacheDirectory->getRelativePathTo($file);
return !$this->cache->has($file) || $this->cache->get($file) !== $this->calcHash($fileContent);
}
public function setFile($file, $fileContent)
{
$file = $this->cacheDirectory->getRelativePathTo($file);
$hash = $this->calcHash($fileContent);
if ($this->isDryRun && $this->cache->has($file) && $this->cache->get($file) !== $hash) {
$this->cache->clear($file);
return;
}
$this->cache->set($file, $hash);
}
private function readCache()
{
$cache = $this->handler->read();
if (!$cache || !$this->signature->equals($cache->getSignature())) {
$cache = new Cache($this->signature);
}
$this->cache = $cache;
}
private function writeCache()
{
$this->handler->write($this->cache);
}
private function calcHash($content)
{
return crc32($content);
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
use Symfony\Component\Filesystem\Exception\IOException;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
final class FileHandler implements FileHandlerInterface
{
/**
* @var string
*/
private $file;
/**
* @param string $file
*/
public function __construct($file)
{
$this->file = $file;
}
public function getFile()
{
return $this->file;
}
public function read()
{
if (!file_exists($this->file)) {
return null;
}
$content = file_get_contents($this->file);
try {
$cache = Cache::fromJson($content);
} catch (\InvalidArgumentException $exception) {
return null;
}
return $cache;
}
public function write(CacheInterface $cache)
{
$content = $cache->toJson();
if (file_exists($this->file)) {
if (is_dir($this->file)) {
throw new IOException(
sprintf('Cannot write cache file "%s" as the location exists as directory.', realpath($this->file)),
0,
null,
$this->file
);
}
if (!is_writable($this->file)) {
throw new IOException(
sprintf('Cannot write to file "%s" as it is not writable.', realpath($this->file)),
0,
null,
$this->file
);
}
} else {
$dir = \dirname($this->file);
if (!is_dir($dir)) {
throw new IOException(
sprintf('Directory of cache file "%s" does not exists.', $this->file),
0,
null,
$this->file
);
}
@touch($this->file);
@chmod($this->file, 0666);
}
$bytesWritten = @file_put_contents($this->file, $content);
if (false === $bytesWritten) {
$error = error_get_last();
throw new IOException(
sprintf('Failed to write file "%s", "%s".', $this->file, isset($error['message']) ? $error['message'] : 'no reason available'),
0,
null,
$this->file
);
}
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
interface FileHandlerInterface
{
/**
* @return string
*/
public function getFile();
/**
* @return null|CacheInterface
*/
public function read();
public function write(CacheInterface $cache);
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
final class NullCacheManager implements CacheManagerInterface
{
public function needFixing($file, $fileContent)
{
return true;
}
public function setFile($file, $fileContent)
{
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
final class Signature implements SignatureInterface
{
/**
* @var string
*/
private $phpVersion;
/**
* @var string
*/
private $fixerVersion;
/**
* @var string
*/
private $indent;
/**
* @var string
*/
private $lineEnding;
/**
* @var array
*/
private $rules;
/**
* @param string $phpVersion
* @param string $fixerVersion
* @param string $indent
* @param string $lineEnding
*/
public function __construct($phpVersion, $fixerVersion, $indent, $lineEnding, array $rules)
{
$this->phpVersion = $phpVersion;
$this->fixerVersion = $fixerVersion;
$this->indent = $indent;
$this->lineEnding = $lineEnding;
$this->rules = self::utf8Encode($rules);
}
public function getPhpVersion()
{
return $this->phpVersion;
}
public function getFixerVersion()
{
return $this->fixerVersion;
}
public function getIndent()
{
return $this->indent;
}
public function getLineEnding()
{
return $this->lineEnding;
}
public function getRules()
{
return $this->rules;
}
public function equals(SignatureInterface $signature)
{
return $this->phpVersion === $signature->getPhpVersion()
&& $this->fixerVersion === $signature->getFixerVersion()
&& $this->indent === $signature->getIndent()
&& $this->lineEnding === $signature->getLineEnding()
&& $this->rules === $signature->getRules();
}
private static function utf8Encode(array $data)
{
if (!\function_exists('mb_detect_encoding')) {
return $data;
}
array_walk_recursive($data, static function (&$item) {
if (\is_string($item) && !mb_detect_encoding($item, 'utf-8', true)) {
$item = utf8_encode($item);
}
});
return $data;
}
}
<?php
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Cache;
/**
* @author Andreas Möller <am@localheinz.com>
*
* @internal
*/
interface SignatureInterface
{
/**
* @return string
*/
public function getPhpVersion();
/**
* @return string
*/
public function getFixerVersion();
/**
* @return string
*/
public function getIndent();
/**
* @return string
*/
public function getLineEnding();
/**
* @return array
*/
public function getRules();
/**
* @param SignatureInterface $signature
*
* @return bool
*/
public function equals(self $signature);
}
<?php
declare(strict_types=1);
namespace Metadata\Cache;
use Metadata\ClassMetadata;
interface CacheInterface
{
/**
* Loads a class metadata instance from the cache
*/
public function load(string $class): ?ClassMetadata;
/**
* Puts a class metadata instance into the cache
*/
public function put(ClassMetadata $metadata): void;
/**
* Evicts the class metadata for the given class from the cache.
*/
public function evict(string $class): void;
}
<?php
declare(strict_types=1);
namespace Metadata\Cache;
/**
* @author Alexander Strizhak <gam6itko@gmail.com>
*/
interface ClearableCacheInterface
{
/**
* Clear all classes metadata from the cache.
*/
public function clear(): bool;
}
<?php
declare(strict_types=1);
namespace Metadata\Cache;
use Doctrine\Common\Cache\Cache;
use Metadata\ClassMetadata;
/**
* @author Henrik Bjornskov <henrik@bjrnskov.dk>
*/
class DoctrineCacheAdapter implements CacheInterface, ClearableCacheInterface
{
/**
* @var string
*/
private $prefix;
/**
* @var Cache
*/
private $cache;
public function __construct(string $prefix, Cache $cache)
{
$this->prefix = $prefix;
$this->cache = $cache;
}
public function load(string $class): ?ClassMetadata
{
$cache = $this->cache->fetch($this->prefix . $class);
return false === $cache ? null : $cache;
}
public function put(ClassMetadata $metadata): void
{
$this->cache->save($this->prefix . $metadata->name, $metadata);
}
public function evict(string $class): void
{
$this->cache->delete($this->prefix . $class);
}
public function clear(): bool
{
if (method_exists($this->cache, 'deleteAll')) { // or $this->cache instanceof ClearableCache
return call_user_func([$this->cache, 'deleteAll']);
}
return false;
}
}
<?php
declare(strict_types=1);
namespace Metadata\Cache;
use Metadata\ClassMetadata;
class FileCache implements CacheInterface, ClearableCacheInterface
{
/**
* @var string
*/
private $dir;
public function __construct(string $dir)
{
if (!is_dir($dir) && false === @mkdir($dir, 0777, true)) {
throw new \InvalidArgumentException(sprintf('Can\'t create directory for cache at "%s"', $dir));
}
$this->dir = rtrim($dir, '\\/');
}
public function load(string $class): ?ClassMetadata
{
$path = $this->getCachePath($class);
if (!is_readable($path)) {
return null;
}
try {
$metadata = include $path;
if ($metadata instanceof ClassMetadata) {
return $metadata;
}
// if the file does not return anything, the return value is integer `1`.
} catch (\Error $e) {
// ignore corrupted cache
}
return null;
}
public function put(ClassMetadata $metadata): void
{
if (!is_writable($this->dir)) {
throw new \InvalidArgumentException(sprintf('The directory "%s" is not writable.', $this->dir));
}
$path = $this->getCachePath($metadata->name);
if (!is_writable(dirname($path))) {
throw new \RuntimeException(sprintf('Cache file "%s" is not writable.', $path));
}
$tmpFile = tempnam($this->dir, 'metadata-cache');
if (false === $tmpFile) {
$this->evict($metadata->name);
return;
}
$data = '<?php return unserialize(' . var_export(serialize($metadata), true) . ');';
$bytesWritten = file_put_contents($tmpFile, $data);
// use strlen and not mb_strlen. if there is utf8 in the code, it also writes more bytes.
if ($bytesWritten !== strlen($data)) {
@unlink($tmpFile);
// also evict the cache to not use an outdated version.
$this->evict($metadata->name);
return;
}
// Let's not break filesystems which do not support chmod.
@chmod($tmpFile, 0666 & ~umask());
$this->renameFile($tmpFile, $path);
}
/**
* Renames a file with fallback for windows
*/
private function renameFile(string $source, string $target): void
{
if (false === @rename($source, $target)) {
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
if (false === copy($source, $target)) {
throw new \RuntimeException(sprintf('(WIN) Could not write new cache file to %s.', $target));
}
if (false === unlink($source)) {
throw new \RuntimeException(sprintf('(WIN) Could not delete temp cache file to %s.', $source));
}
} else {
throw new \RuntimeException(sprintf('Could not write new cache file to %s.', $target));
}
}
}
public function evict(string $class): void
{
$path = $this->getCachePath($class);
if (file_exists($path)) {
@unlink($path);
}
}
public function clear(): bool
{
$result = true;
$files = glob($this->dir . '/*.cache.php');
foreach ($files as $file) {
if (is_file($file)) {
$result = $result && @unlink($file);
}
}
return $result;
}
/**
* This function computes the cache file path.
*
* If anonymous class is to be cached, it contains invalid path characters that need to be removed/replaced
* Example of anonymous class name: class@anonymous\x00/app/src/Controller/DefaultController.php0x7f82a7e026ec
*/
private function getCachePath(string $key): string
{
$fileName = str_replace(['\\', "\0", '@', '/', '$', '{', '}', ':'], '-', $key);
return $this->dir . '/' . $fileName . '.cache.php';
}
}
<?php
declare(strict_types=1);
namespace Metadata\Cache;
use Metadata\ClassMetadata;
use Psr\Cache\CacheItemPoolInterface;
class PsrCacheAdapter implements CacheInterface, ClearableCacheInterface
{
/**
* @var string
*/
private $prefix;
/**
* @var CacheItemPoolInterface
*/
private $pool;
/**
* @var CacheItemPoolInterface
*/
private $lastItem;
public function __construct(string $prefix, CacheItemPoolInterface $pool)
{
$this->prefix = $prefix;
$this->pool = $pool;
}
public function load(string $class): ?ClassMetadata
{
$this->lastItem = $this->pool->getItem($this->sanitizeCacheKey($this->prefix . $class));
return $this->lastItem->get();
}
public function put(ClassMetadata $metadata): void
{
$key = $this->sanitizeCacheKey($this->prefix . $metadata->name);
if (null === $this->lastItem || $this->lastItem->getKey() !== $key) {
$this->lastItem = $this->pool->getItem($key);
}
$this->pool->save($this->lastItem->set($metadata));
}
public function evict(string $class): void
{
$this->pool->deleteItem($this->sanitizeCacheKey($this->prefix . $class));
}
public function clear(): bool
{
return $this->pool->clear();
}
/**
* If anonymous class is to be cached, it contains invalid path characters that need to be removed/replaced
* Example of anonymous class name: class@anonymous\x00/app/src/Controller/DefaultController.php0x7f82a7e026ec
*/
private function sanitizeCacheKey(string $key): string
{
return str_replace(['\\', "\0", '@', '/', '$', '{', '}', ':'], '-', $key);
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CodeMessDetector\Rule\Design;
use PHPMD\AbstractNode;
use PHPMD\AbstractRule;
use PHPMD\Rule\ClassAware;
use PHPMD\Rule\MethodAware;
/**
* Magento is a highly extensible and customizable platform.
* Usage of final classes and methods is prohibited.
*/
class FinalImplementation extends AbstractRule implements ClassAware, MethodAware
{
/**
* @inheritdoc
*/
public function apply(AbstractNode $node)
{
if ($node->isFinal()) {
$this->addViolation($node, [$node->getType(), $node->getFullQualifiedName()]);
}
}
}
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<ruleset name="Magento Specific Design Rules"
xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
<rule name="FinalImplementation"
class="Magento\CodeMessDetector\Rule\Design\FinalImplementation"
message= "The {0} {1} declared as final.">
<description>
<![CDATA[
Final keyword is prohibited in Magento as this decreases extensibility and customizability.
Final classes and method are not compatible with plugins and proxies.
]]>
</description>
<priority>1</priority>
<properties />
<example>
<![CDATA[
final class Foo
{
public function bar() {}
}
class Baz {
final public function bad() {}
}
]]>
</example>
</rule>
</ruleset>
<?xml version='1.0' encoding="UTF-8"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<ruleset name="Magento PHPMD rule set" xmlns="http://pmd.sf.net/ruleset/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd"
xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd">
<description>Magento Code Check Rules</description>
<php-includepath>../../../static</php-includepath>
<!-- Code Size Rules -->
<rule ref="rulesets/codesize.xml/CyclomaticComplexity" />
<rule ref="rulesets/codesize.xml/NPathComplexity" />
<rule ref="rulesets/codesize.xml/ExcessiveMethodLength" />
<rule ref="rulesets/codesize.xml/ExcessiveParameterList" />
<rule ref="rulesets/codesize.xml/ExcessivePublicCount" />
<rule ref="rulesets/codesize.xml/TooManyFields" />
<rule ref="rulesets/codesize.xml/ExcessiveClassComplexity">
<properties>
<property name="maximum" value="100" />
</properties>
</rule>
<!-- Unused code rules -->
<rule ref="rulesets/unusedcode.xml/UnusedPrivateField" />
<rule ref="rulesets/unusedcode.xml/UnusedPrivateMethod" />
<rule ref="rulesets/unusedcode.xml/UnusedFormalParameter" />
<rule ref="rulesets/unusedcode.xml/UnusedLocalVariable" >
<properties>
<property name="allow-unused-foreach-variables" value="true"/>
</properties>
</rule>
<!-- Code design rules -->
<rule ref="rulesets/design.xml/ExitExpression" />
<rule ref="rulesets/design.xml/EvalExpression" />
<rule ref="rulesets/design.xml/GotoStatement" />
<rule ref="rulesets/design.xml/NumberOfChildren" />
<rule ref="rulesets/design.xml/DepthOfInheritance">
<properties>
<property name="minimum" value="8" />
</properties>
</rule>
<rule ref="rulesets/design.xml/CouplingBetweenObjects" />
<!-- Naming Rules -->
<rule ref="rulesets/naming.xml/ShortMethodName" />
<rule ref="rulesets/naming.xml/ConstantNamingConventions" />
<rule ref="rulesets/naming.xml/BooleanGetMethodName" />
<!-- Magento Specific Rules -->
<rule ref="Magento/CodeMessDetector/resources/rulesets/design.xml/FinalImplementation" />
</ruleset>
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\Arrays;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class ShortArraySyntaxSniff implements Sniff
{
/**
* {@inheritdoc}
*/
public function register()
{
return [T_ARRAY];
}
/**
* {@inheritdoc}
*/
public function process(File $sourceFile, $stackPtr)
{
$sourceFile->addError(
'Short array syntax must be used; expected "[]" but found "array()"',
$stackPtr,
'ShortArraySyntax'
);
}
}
<?php
/**
* Parses and verifies the doc comments for functions.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace Magento\Sniffs\Commenting;
use PHP_CodeSniffer\Standards\PEAR\Sniffs\Commenting\FunctionCommentSniff as PEARFunctionCommentSniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Util\Common;
class FunctionCommentSniff extends PEARFunctionCommentSniff
{
/**
* The current PHP version.
*
* @var integer
*/
private $phpVersion = null;
/**
* Process the return comment of this function comment.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param int $commentStart The position in the stack where the comment started.
*
* @return void
*/
protected function processReturn(File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
// Skip constructor and destructor.
$methodName = $phpcsFile->getDeclarationName($stackPtr);
$isSpecialMethod = ($methodName === '__construct' || $methodName === '__destruct');
$return = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@return') {
if ($return !== null) {
$error = 'Only 1 @return tag is allowed in a function comment';
$phpcsFile->addError($error, $tag, 'DuplicateReturn');
return;
}
$return = $tag;
}
}
if ($isSpecialMethod === true) {
return;
}
if ($return !== null) {
$content = $tokens[($return + 2)]['content'];
if (empty($content) === true || $tokens[($return + 2)]['code'] !== T_DOC_COMMENT_STRING) {
$error = 'Return type missing for @return tag in function comment';
$phpcsFile->addError($error, $return, 'MissingReturnType');
} else {
// Support both a return type and a description.
preg_match('`^((?:\|?(?:array\([^\)]*\)|[\\\\a-z0-9\[\]]+))*)( .*)?`i', $content, $returnParts);
if (isset($returnParts[1]) === false) {
return;
}
$returnType = $returnParts[1];
// Check return type (can be multiple, separated by '|').
$typeNames = explode('|', $returnType);
$suggestedNames = array();
foreach ($typeNames as $typeName) {
$suggestedName = Common::suggestType($typeName);
if (in_array($suggestedName, $suggestedNames) === false) {
$suggestedNames[] = $suggestedName;
}
}
$suggestedType = implode('|', $suggestedNames);
if ($returnType !== $suggestedType) {
$error = 'Expected "%s" but found "%s" for function return type';
$data = array(
$suggestedType,
$returnType,
);
$fix = $phpcsFile->addFixableError($error, $return, 'InvalidReturn', $data);
if ($fix === true) {
$replacement = $suggestedType;
if (empty($returnParts[2]) === false) {
$replacement .= $returnParts[2];
}
$phpcsFile->fixer->replaceToken(($return + 2), $replacement);
unset($replacement);
}
}
// If the return type is void, make sure there is
// no return statement in the function.
if ($returnType === 'void') {
if (isset($tokens[$stackPtr]['scope_closer']) === true) {
$endToken = $tokens[$stackPtr]['scope_closer'];
for ($returnToken = $stackPtr; $returnToken < $endToken; $returnToken++) {
if ($tokens[$returnToken]['code'] === T_CLOSURE
|| $tokens[$returnToken]['code'] === T_ANON_CLASS
) {
$returnToken = $tokens[$returnToken]['scope_closer'];
continue;
}
if ($tokens[$returnToken]['code'] === T_RETURN
|| $tokens[$returnToken]['code'] === T_YIELD
|| $tokens[$returnToken]['code'] === T_YIELD_FROM
) {
break;
}
}
if ($returnToken !== $endToken) {
// If the function is not returning anything, just
// exiting, then there is no problem.
$semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true);
if ($tokens[$semicolon]['code'] !== T_SEMICOLON) {
$error = 'Function return type is void, but function contains return statement';
$phpcsFile->addError($error, $return, 'InvalidReturnVoid');
}
}
}//end if
} else if ($returnType !== 'mixed' && in_array('void', $typeNames, true) === false) {
// If return type is not void, there needs to be a return statement
// somewhere in the function that returns something.
if (isset($tokens[$stackPtr]['scope_closer']) === true) {
$endToken = $tokens[$stackPtr]['scope_closer'];
$returnToken = $phpcsFile->findNext(array(T_RETURN, T_YIELD, T_YIELD_FROM), $stackPtr, $endToken);
if ($returnToken === false) {
$error = 'Function return type is not void, but function has no return statement';
$phpcsFile->addError($error, $return, 'InvalidNoReturn');
} else {
$semicolon = $phpcsFile->findNext(T_WHITESPACE, ($returnToken + 1), null, true);
if ($tokens[$semicolon]['code'] === T_SEMICOLON) {
$error = 'Function return type is not void, but function is returning void here';
$phpcsFile->addError($error, $returnToken, 'InvalidReturnNotVoid');
}
}
}
}//end if
}//end if
} else {
$error = 'Missing @return tag in function comment';
$phpcsFile->addError($error, $tokens[$commentStart]['comment_closer'], 'MissingReturn');
}//end if
}//end processReturn()
/**
* Process any throw tags that this function comment has.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param int $commentStart The position in the stack where the comment started.
*
* @return void
*/
protected function processThrows(File $phpcsFile, $stackPtr, $commentStart)
{
$tokens = $phpcsFile->getTokens();
$throws = array();
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@throws') {
continue;
}
$exception = null;
$comment = null;
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
$matches = array();
preg_match('/([^\s]+)(?:\s+(.*))?/', $tokens[($tag + 2)]['content'], $matches);
$exception = $matches[1];
if (isset($matches[2]) === true && trim($matches[2]) !== '') {
$comment = $matches[2];
}
}
if ($exception === null) {
$error = 'Exception type and comment missing for @throws tag in function comment';
$phpcsFile->addError($error, $tag, 'InvalidThrows');
} else if ($comment === null) {
$error = 'Comment missing for @throws tag in function comment';
// $phpcsFile->addError($error, $tag, 'EmptyThrows');
} else {
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) {
$end = $tokens[$commentStart]['comment_tags'][($pos + 1)];
} else {
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
$comment .= ' '.$tokens[$i]['content'];
}
}
// Starts with a capital letter and ends with a fullstop.
$firstChar = $comment[0];
if (strtoupper($firstChar) !== $firstChar) {
$error = '@throws tag comment must start with a capital letter';
$phpcsFile->addError($error, ($tag + 2), 'ThrowsNotCapital');
}
$lastChar = substr($comment, -1);
if ($lastChar !== '.') {
$error = '@throws tag comment must end with a full stop';
$phpcsFile->addError($error, ($tag + 2), 'ThrowsNoFullStop');
}
}//end if
}//end foreach
}//end processThrows()
/**
* Process the function parameter comments.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
* @param int $commentStart The position in the stack where the comment started.
*
* @return void
*/
protected function processParams(File $phpcsFile, $stackPtr, $commentStart)
{
if ($this->phpVersion === null) {
$this->phpVersion = Config::getConfigData('php_version');
if ($this->phpVersion === null) {
$this->phpVersion = PHP_VERSION_ID;
}
}
$tokens = $phpcsFile->getTokens();
$params = array();
$maxType = 0;
$maxVar = 0;
foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) {
if ($tokens[$tag]['content'] !== '@param') {
continue;
}
$type = '';
$typeSpace = 0;
$var = '';
$varSpace = 0;
$comment = '';
$commentLines = array();
if ($tokens[($tag + 2)]['code'] === T_DOC_COMMENT_STRING) {
$matches = array();
preg_match('/([^$&.]+)(?:((?:\.\.\.)?(?:\$|&)[^\s]+)(?:(\s+)(.*))?)?/', $tokens[($tag + 2)]['content'], $matches);
if (empty($matches) === false) {
$typeLen = strlen($matches[1]);
$type = trim($matches[1]);
$typeSpace = ($typeLen - strlen($type));
$typeLen = strlen($type);
if ($typeLen > $maxType) {
$maxType = $typeLen;
}
}
if (isset($matches[2]) === true) {
$var = $matches[2];
$varLen = strlen($var);
if ($varLen > $maxVar) {
$maxVar = $varLen;
}
if (isset($matches[4]) === true) {
$varSpace = strlen($matches[3]);
$comment = $matches[4];
$commentLines[] = array(
'comment' => $comment,
'token' => ($tag + 2),
'indent' => $varSpace,
);
// Any strings until the next tag belong to this comment.
if (isset($tokens[$commentStart]['comment_tags'][($pos + 1)]) === true) {
$end = $tokens[$commentStart]['comment_tags'][($pos + 1)];
} else {
$end = $tokens[$commentStart]['comment_closer'];
}
for ($i = ($tag + 3); $i < $end; $i++) {
if ($tokens[$i]['code'] === T_DOC_COMMENT_STRING) {
$indent = 0;
if ($tokens[($i - 1)]['code'] === T_DOC_COMMENT_WHITESPACE) {
$indent = strlen($tokens[($i - 1)]['content']);
}
$comment .= ' '.$tokens[$i]['content'];
$commentLines[] = array(
'comment' => $tokens[$i]['content'],
'token' => $i,
'indent' => $indent,
);
}
}
} else {
$error = 'Missing parameter comment';
// $phpcsFile->addError($error, $tag, 'MissingParamComment');
$commentLines[] = array('comment' => '');
}//end if
} else {
$error = 'Missing parameter name';
$phpcsFile->addError($error, $tag, 'MissingParamName');
}//end if
} else {
$error = 'Missing parameter type';
$phpcsFile->addError($error, $tag, 'MissingParamType');
}//end if
$params[] = array(
'tag' => $tag,
'type' => $type,
'var' => $var,
'comment' => $comment,
'commentLines' => $commentLines,
'type_space' => $typeSpace,
'var_space' => $varSpace,
);
}//end foreach
$realParams = $phpcsFile->getMethodParameters($stackPtr);
$foundParams = array();
// We want to use ... for all variable length arguments, so added
// this prefix to the variable name so comparisons are easier.
foreach ($realParams as $pos => $param) {
if ($param['variable_length'] === true) {
$realParams[$pos]['name'] = '...'.$realParams[$pos]['name'];
}
}
foreach ($params as $pos => $param) {
// If the type is empty, the whole line is empty.
if ($param['type'] === '') {
continue;
}
// Check the param type value.
$typeNames = explode('|', $param['type']);
$suggestedTypeNames = array();
foreach ($typeNames as $typeName) {
$suggestedName = Common::suggestType($typeName);
$suggestedTypeNames[] = $suggestedName;
if (count($typeNames) > 1) {
continue;
}
// Check type hint for array and custom type.
$suggestedTypeHint = '';
if (strpos($suggestedName, 'array') !== false || substr($suggestedName, -2) === '[]') {
$suggestedTypeHint = 'array';
} else if (strpos($suggestedName, 'callable') !== false) {
$suggestedTypeHint = 'callable';
} else if (strpos($suggestedName, 'callback') !== false) {
$suggestedTypeHint = 'callable';
} else if (in_array($suggestedName, Common::$allowedTypes) === false) {
$suggestedTypeHint = $suggestedName;
}
if ($this->phpVersion >= 70000) {
if ($suggestedName === 'string') {
$suggestedTypeHint = 'string';
} else if ($suggestedName === 'int' || $suggestedName === 'integer') {
$suggestedTypeHint = 'int';
} else if ($suggestedName === 'float') {
$suggestedTypeHint = 'float';
} else if ($suggestedName === 'bool' || $suggestedName === 'boolean') {
$suggestedTypeHint = 'bool';
}
}
if ($suggestedTypeHint !== '' && isset($realParams[$pos]) === true) {
$typeHint = $realParams[$pos]['type_hint'];
if ($typeHint === '') {
$error = 'Type hint "%s" missing for %s';
$data = array(
$suggestedTypeHint,
$param['var'],
);
$errorCode = 'TypeHintMissing';
if ($suggestedTypeHint === 'string'
|| $suggestedTypeHint === 'int'
|| $suggestedTypeHint === 'float'
|| $suggestedTypeHint === 'bool'
) {
$errorCode = 'Scalar'.$errorCode;
}
// $phpcsFile->addError($error, $stackPtr, $errorCode, $data);
} else if ($typeHint !== substr($suggestedTypeHint, (strlen($typeHint) * -1))) {
$error = 'Expected type hint "%s"; found "%s" for %s';
$data = array(
$suggestedTypeHint,
$typeHint,
$param['var'],
);
$phpcsFile->addError($error, $stackPtr, 'IncorrectTypeHint', $data);
}//end if
} else if ($suggestedTypeHint === '' && isset($realParams[$pos]) === true) {
$typeHint = $realParams[$pos]['type_hint'];
if ($typeHint !== '') {
$error = 'Unknown type hint "%s" found for %s';
$data = array(
$typeHint,
$param['var'],
);
$phpcsFile->addError($error, $stackPtr, 'InvalidTypeHint', $data);
}
}//end if
}//end foreach
$suggestedType = implode('|', $suggestedTypeNames);
if ($param['type'] !== $suggestedType) {
$error = 'Expected "%s" but found "%s" for parameter type';
$data = array(
$suggestedType,
$param['type'],
);
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'IncorrectParamVarName', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
$content = $suggestedType;
$content .= str_repeat(' ', $param['type_space']);
$content .= $param['var'];
$content .= str_repeat(' ', $param['var_space']);
if (isset($param['commentLines'][0]) === true) {
$content .= $param['commentLines'][0]['comment'];
}
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);
// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
continue;
}
$diff = (strlen($param['type']) - strlen($suggestedType));
$newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff);
$phpcsFile->fixer->replaceToken(
($param['commentLines'][$lineNum]['token'] - 1),
str_repeat(' ', $newIndent)
);
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
if ($param['var'] === '') {
continue;
}
$foundParams[] = $param['var'];
// Check number of spaces after the type.
$this->checkSpacingAfterParamType($phpcsFile, $param, $maxType);
// Make sure the param name is correct.
if (isset($realParams[$pos]) === true) {
$realName = $realParams[$pos]['name'];
if ($realName !== $param['var']) {
$code = 'ParamNameNoMatch';
$data = array(
$param['var'],
$realName,
);
$error = 'Doc comment for parameter %s does not match ';
if (strtolower($param['var']) === strtolower($realName)) {
$error .= 'case of ';
$code = 'ParamNameNoCaseMatch';
}
$error .= 'actual variable name %s';
$phpcsFile->addError($error, $param['tag'], $code, $data);
}
} else if (substr($param['var'], -4) !== ',...') {
// We must have an extra parameter comment.
$error = 'Superfluous parameter comment';
$phpcsFile->addError($error, $param['tag'], 'ExtraParamComment');
}//end if
if ($param['comment'] === '') {
continue;
}
// Check number of spaces after the var name.
$this->checkSpacingAfterParamName($phpcsFile, $param, $maxVar);
// Param comments must start with a capital letter and end with the full stop.
if (preg_match('/^(\p{Ll}|\P{L})/u', $param['comment']) === 1) {
$error = 'Parameter comment must start with a capital letter';
$phpcsFile->addError($error, $param['tag'], 'ParamCommentNotCapital');
}
$lastChar = substr($param['comment'], -1);
if ($lastChar !== '.') {
$error = 'Parameter comment must end with a full stop';
$phpcsFile->addError($error, $param['tag'], 'ParamCommentFullStop');
}
}//end foreach
$realNames = array();
foreach ($realParams as $realParam) {
$realNames[] = $realParam['name'];
}
// Report missing comments.
$diff = array_diff($realNames, $foundParams);
foreach ($diff as $neededParam) {
$error = 'Doc comment for parameter "%s" missing';
$data = array($neededParam);
// $phpcsFile->addError($error, $commentStart, 'MissingParamTag', $data);
}
}//end processParams()
/**
* Check the spacing after the type of a parameter.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param array $param The parameter to be checked.
* @param int $maxType The maxlength of the longest parameter type.
* @param int $spacing The number of spaces to add after the type.
*
* @return void
*/
protected function checkSpacingAfterParamType(File $phpcsFile, $param, $maxType, $spacing=1)
{
// Check number of spaces after the type.
$spaces = ($maxType - strlen($param['type']) + $spacing);
if ($param['type_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter type; %s found';
$data = array(
$spaces,
$param['type_space'],
);
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamType', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
$content = $param['type'];
$content .= str_repeat(' ', $spaces);
$content .= $param['var'];
$content .= str_repeat(' ', $param['var_space']);
$content .= $param['commentLines'][0]['comment'];
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);
// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
continue;
}
$diff = ($param['type_space'] - $spaces);
$newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff);
$phpcsFile->fixer->replaceToken(
($param['commentLines'][$lineNum]['token'] - 1),
str_repeat(' ', $newIndent)
);
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
}//end checkSpacingAfterParamType()
/**
* Check the spacing after the name of a parameter.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param array $param The parameter to be checked.
* @param int $maxVar The maxlength of the longest parameter name.
* @param int $spacing The number of spaces to add after the type.
*
* @return void
*/
protected function checkSpacingAfterParamName(File $phpcsFile, $param, $maxVar, $spacing=1)
{
// Check number of spaces after the var name.
$spaces = ($maxVar - strlen($param['var']) + $spacing);
if ($param['var_space'] !== $spaces) {
$error = 'Expected %s spaces after parameter name; %s found';
$data = array(
$spaces,
$param['var_space'],
);
$fix = $phpcsFile->addFixableError($error, $param['tag'], 'SpacingAfterParamName', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
$content = $param['type'];
$content .= str_repeat(' ', $param['type_space']);
$content .= $param['var'];
$content .= str_repeat(' ', $spaces);
$content .= $param['commentLines'][0]['comment'];
$phpcsFile->fixer->replaceToken(($param['tag'] + 2), $content);
// Fix up the indent of additional comment lines.
foreach ($param['commentLines'] as $lineNum => $line) {
if ($lineNum === 0
|| $param['commentLines'][$lineNum]['indent'] === 0
) {
continue;
}
$diff = ($param['var_space'] - $spaces);
$newIndent = ($param['commentLines'][$lineNum]['indent'] - $diff);
$phpcsFile->fixer->replaceToken(
($param['commentLines'][$lineNum]['token'] - 1),
str_repeat(' ', $newIndent)
);
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
}//end checkSpacingAfterParamName()
}//end class
<?php
/**
* Parses and verifies the variable doc comment.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace Magento\Sniffs\Commenting;
use PHP_CodeSniffer\Sniffs\AbstractVariableSniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Common;
class VariableCommentSniff extends AbstractVariableSniff
{
/**
* Called to process class member vars.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function processMemberVar(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$ignore = array(
T_PUBLIC,
T_PRIVATE,
T_PROTECTED,
T_VAR,
T_STATIC,
T_WHITESPACE,
);
$commentEnd = $phpcsFile->findPrevious($ignore, ($stackPtr - 1), null, true);
if ($commentEnd === false
|| ($tokens[$commentEnd]['code'] !== T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$commentEnd]['code'] !== T_COMMENT)
) {
$phpcsFile->addError('Missing member variable doc comment', $stackPtr, 'Missing');
return;
}
if ($tokens[$commentEnd]['code'] === T_COMMENT) {
$phpcsFile->addError('You must use "/**" style comments for a member variable comment', $stackPtr, 'WrongStyle');
return;
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
$foundVar = null;
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] === '@var') {
if ($foundVar !== null) {
$error = 'Only one @var tag is allowed in a member variable comment';
$phpcsFile->addError($error, $tag, 'DuplicateVar');
} else {
$foundVar = $tag;
}
} else if ($tokens[$tag]['content'] === '@see') {
// Make sure the tag isn't empty.
$string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $tag, $commentEnd);
if ($string === false || $tokens[$string]['line'] !== $tokens[$tag]['line']) {
$error = 'Content missing for @see tag in member variable comment';
$phpcsFile->addError($error, $tag, 'EmptySees');
}
} else {
$error = '%s tag is not allowed in member variable comment';
$data = array($tokens[$tag]['content']);
$phpcsFile->addWarning($error, $tag, 'TagNotAllowed', $data);
}//end if
}//end foreach
// The @var tag is the only one we require.
if ($foundVar === null) {
$error = 'Missing @var tag in member variable comment';
$phpcsFile->addError($error, $commentEnd, 'MissingVar');
return;
}
$firstTag = $tokens[$commentStart]['comment_tags'][0];
if ($foundVar !== null && $tokens[$firstTag]['content'] !== '@var') {
$error = 'The @var tag must be the first tag in a member variable comment';
$phpcsFile->addError($error, $foundVar, 'VarOrder');
}
// Make sure the tag isn't empty and has the correct padding.
$string = $phpcsFile->findNext(T_DOC_COMMENT_STRING, $foundVar, $commentEnd);
if ($string === false || $tokens[$string]['line'] !== $tokens[$foundVar]['line']) {
$error = 'Content missing for @var tag in member variable comment';
$phpcsFile->addError($error, $foundVar, 'EmptyVar');
return;
}
$varType = $tokens[($foundVar + 2)]['content'];
$suggestedType = Common::suggestType($varType);
if ($varType !== $suggestedType) {
$error = 'Expected "%s" but found "%s" for @var tag in member variable comment';
$data = array(
$suggestedType,
$varType,
);
$fix = $phpcsFile->addFixableError($error, ($foundVar + 2), 'IncorrectVarType', $data);
if ($fix === true) {
$phpcsFile->fixer->replaceToken(($foundVar + 2), $suggestedType);
}
}
}//end processMemberVar()
/**
* Called to process a normal variable.
*
* Not required for this sniff.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this token was found.
* @param int $stackPtr The position where the double quoted
* string was found.
*
* @return void
*/
protected function processVariable(File $phpcsFile, $stackPtr)
{
}//end processVariable()
/**
* Called to process variables found in double quoted strings.
*
* Not required for this sniff.
*
* @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this token was found.
* @param int $stackPtr The position where the double quoted
* string was found.
*
* @return void
*/
protected function processVariableInString(File $phpcsFile, $stackPtr)
{
}//end processVariableInString()
}//end class
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\Files;
use PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff as FilesLineLengthSniff;
/**
* Line length sniff which ignores long lines in case they contain strings intended for translation.
*/
class LineLengthSniff extends FilesLineLengthSniff
{
/**
* Having previous line content allows to ignore long lines in case of multi-line declaration.
*
* @var string
*/
protected $previousLineContent = '';
/**
* {@inheritdoc}
*/
protected function checkLineLength($phpcsFile, $stackPtr, $lineContent)
{
$previousLineRegexp = '~__\($|\bPhrase\($~';
$currentLineRegexp = '~__\(.+\)|\bPhrase\(.+\)~';
$currentLineMatch = preg_match($currentLineRegexp, $lineContent) !== 0;
$previousLineMatch = preg_match($previousLineRegexp, $this->previousLineContent) !== 0;
$this->previousLineContent = $lineContent;
if (! $currentLineMatch && !$previousLineMatch) {
parent::checkLineLength($phpcsFile, $stackPtr, $lineContent);
}
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\LiteralNamespaces;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Custom phpcs sniff to detect usages of literal class and interface names.
*/
class LiteralNamespacesSniff implements Sniff
{
/**
* @var string
*/
private $literalNamespacePattern = '/^[\\\]{0,2}[A-Z][A-Za-z]+([\\\]{1,2}[A-Z][A-Za-z]+){2,}(?!\\\+)$/';
/**
* @var array
*/
private $classNames = [];
/**
* @inheritdoc
*/
public function register()
{
return [
T_CONSTANT_ENCAPSED_STRING,
T_DOUBLE_QUOTED_STRING,
];
}
/**
* @inheritdoc
*/
public function process(File $sourceFile, $stackPtr)
{
$tokens = $sourceFile->getTokens();
if ($sourceFile->findPrevious(T_STRING_CONCAT, $stackPtr, $stackPtr - 3) ||
$sourceFile->findNext(T_STRING_CONCAT, $stackPtr, $stackPtr + 3)
) {
return;
}
$content = trim($tokens[$stackPtr]['content'], "\"'");
// replace double slashes from class name for avoiding problems with class autoload
if (strpos($content, '\\') !== false) {
$content = preg_replace('|\\\{2,}|', '\\', $content);
}
if (preg_match($this->literalNamespacePattern, $content) === 1 && $this->classExists($content)) {
$sourceFile->addError(
"Use ::class notation instead.",
$stackPtr,
'LiteralClassUsage'
);
}
}
/**
* @param string $className
* @return bool
*/
private function classExists($className)
{
if (!isset($this->classNames[$className])) {
$this->classNames[$className] = class_exists($className) || interface_exists($className);
}
return $this->classNames[$className];
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\MicroOptimizations;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class IsNullSniff implements Sniff
{
/**
* @var string
*/
protected $blocklist = 'is_null';
/**
* @inheritdoc
*/
public function register()
{
return [T_STRING];
}
/**
* @inheritdoc
*/
public function process(File $sourceFile, $stackPtr)
{
$tokens = $sourceFile->getTokens();
if ($tokens[$stackPtr]['content'] === $this->blocklist) {
$sourceFile->addError(
"is_null must be avoided. Use strict comparison instead.",
$stackPtr,
'IsNullUsage'
);
}
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class InterfaceNameSniff implements Sniff
{
const INTERFACE_SUFFIX = 'Interface';
/**
* {@inheritdoc}
*/
public function register()
{
return [T_INTERFACE];
}
/**
* {@inheritdoc}
*/
public function process(File $sourceFile, $stackPtr)
{
$tokens = $sourceFile->getTokens();
$declarationLine = $tokens[$stackPtr]['line'];
$suffixLength = strlen(self::INTERFACE_SUFFIX);
// Find first T_STRING after 'interface' keyword in the line and verify it
while ($tokens[$stackPtr]['line'] == $declarationLine) {
if ($tokens[$stackPtr]['type'] == 'T_STRING') {
if (substr($tokens[$stackPtr]['content'], 0 - $suffixLength) != self::INTERFACE_SUFFIX) {
$sourceFile->addError(
'Interface should have name that ends with "Interface" suffix.',
$stackPtr,
'WrongInterfaceName'
);
}
break;
}
$stackPtr++;
}
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\NamingConventions;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class ReservedWordsSniff implements Sniff
{
/**
* The following words cannot be used to name a class, interface or trait,
* and they are also prohibited from being used in namespaces.
*
* @link http://php.net/manual/en/reserved.other-reserved-words.php
*
* @var string[]
*/
protected $reservedWords = [
'int' => '7',
'float' => '7',
'bool' => '7',
'string' => '7',
'true' => '7',
'false' => '7',
'null' => '7',
'void' => '7.1',
'iterable' => '7.1',
'resource' => '7',
'object' => '7',
'mixed' => '7',
'numeric' => '7',
];
/**
* {@inheritdoc}
*/
public function register()
{
return [T_CLASS, T_INTERFACE, T_TRAIT, T_NAMESPACE];
}
/**
* Check all namespace parts
*
* @param File $sourceFile
* @param int $stackPtr
* @return void
*/
protected function validateNamespace(File $sourceFile, $stackPtr)
{
$stackPtr += 2;
$tokens = $sourceFile->getTokens();
while ($stackPtr < $sourceFile->numTokens && $tokens[$stackPtr]['code'] !== T_SEMICOLON) {
if ($tokens[$stackPtr]['code'] === T_WHITESPACE || $tokens[$stackPtr]['code'] === T_NS_SEPARATOR) {
$stackPtr++; //skip "namespace" and whitespace
continue;
}
$namespacePart = $tokens[$stackPtr]['content'];
if (isset($this->reservedWords[strtolower($namespacePart)])) {
$sourceFile->addError(
'Cannot use "%s" in namespace as it is reserved since PHP %s',
$stackPtr,
'Namespace',
[$namespacePart, $this->reservedWords[$namespacePart]]
);
}
$stackPtr++;
}
}
/**
* Check class name not having reserved words
*
* @param File $sourceFile
* @param int $stackPtr
* @return void
*/
protected function validateClass(File $sourceFile, $stackPtr)
{
$tokens = $sourceFile->getTokens();
$stackPtr += 2; //skip "class" and whitespace
$className = strtolower($tokens[$stackPtr]['content']);
if (isset($this->reservedWords[$className])) {
$sourceFile->addError(
'Cannot use "%s" as class name as it is reserved since PHP %s',
$stackPtr,
'Class',
[$className, $this->reservedWords[$className]]
);
}
}
/**
* {@inheritdoc}
*/
public function process(File $sourceFile, $stackPtr)
{
$tokens = $sourceFile->getTokens();
switch ($tokens[$stackPtr]['code']) {
case T_CLASS:
case T_INTERFACE:
case T_TRAIT:
$this->validateClass($sourceFile, $stackPtr);
break;
case T_NAMESPACE:
$this->validateNamespace($sourceFile, $stackPtr);
break;
}
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\Whitespace;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Class EmptyLineMissedSniff
*/
class EmptyLineMissedSniff implements Sniff
{
/**
* {@inheritdoc}
*/
public function register()
{
return [T_DOC_COMMENT];
}
/**
* {@inheritdoc}
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($this->doCheck($phpcsFile, $stackPtr, $tokens)) {
$previous = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true);
if ($tokens[$stackPtr]['line'] - $tokens[$previous]['line'] < 2) {
$error = 'Empty line missed';
$phpcsFile->addError($error, $stackPtr, '', null);
}
}
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param array $tokens
* @return bool
*/
private function doCheck(File $phpcsFile, $stackPtr, $tokens)
{
$result = false;
if ($phpcsFile->hasCondition($stackPtr, T_CLASS) || $phpcsFile->hasCondition($stackPtr, T_INTERFACE)) {
$result = true;
}
if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION)) {
$result = false;
}
$previous = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true);
if ($tokens[$previous]['type'] === 'T_OPEN_CURLY_BRACKET') {
$result = false;
}
if (strpos($tokens[$stackPtr]['content'], '/**') === false) {
$result = false;
}
return $result;
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Sniffs\Whitespace;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Class MultipleEmptyLinesSniff
*/
class MultipleEmptyLinesSniff implements Sniff
{
/**
* {@inheritdoc}
*/
public function register()
{
return [T_WHITESPACE];
}
/**
* {@inheritdoc}
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION)
|| $phpcsFile->hasCondition($stackPtr, T_CLASS)
|| $phpcsFile->hasCondition($stackPtr, T_INTERFACE)
) {
if ($tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line']
&& $tokens[($stackPtr - 2)]['line'] === $tokens[($stackPtr - 1)]['line']
) {
// This is an empty line and the line before this one is not
// empty, so this could be the start of a multiple empty line block
$next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true);
$lines = $tokens[$next]['line'] - $tokens[$stackPtr]['line'];
if ($lines > 1) {
$error = 'Code must not contain multiple empty lines in a row; found %s empty lines';
$data = [$lines];
$phpcsFile->addError($error, $stackPtr, 'MultipleEmptyLines', $data);
}
}
}
}
}
<?xml version="1.0"?>
<!--
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<ruleset name="Magento2FunctionalTestingFramework">
<description>Custom Magento2 Functional Testing Framework coding standard.</description>
<rule ref="PSR2"/>
<rule ref="Magento.Files.LineLength">
<properties>
<property name="lineLimit" value="120"/>
<property name="absoluteLineLimit" value="120"/>
</properties>
</rule>
<rule ref="Magento.LiteralNamespaces.LiteralNamespaces">
<exclude-pattern>*/_files/*</exclude-pattern>
</rule>
<rule ref="Magento.Commenting.FunctionComment">
<exclude-pattern>*/dev/tests*</exclude-pattern>
</rule>
<rule ref="Magento.Commenting.VariableComment"/>
<rule ref="Generic.Functions.CallTimePassByReference"/>
<rule ref="Generic.PHP.DeprecatedFunctions"/>
<rule ref="Squiz.Commenting.DocCommentAlignment"/>
<rule ref="Squiz.Functions.GlobalFunction"/>
<rule ref="Squiz.WhiteSpace.LogicalOperatorSpacing"/>
<!-- Codeception Webdriver violates this, cannot fix as we extend from them -->
<rule ref="PSR2.Methods.MethodDeclaration.Underscore">
<severity>0</severity>
</rule>
</ruleset>
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Code\Reader;
class ClassReader implements ClassReaderInterface
{
/**
* Read class constructor signature
*
* @param string $className
* @return array|null
* @throws \ReflectionException
*/
public function getConstructor($className)
{
$class = new \ReflectionClass($className);
$result = null;
$constructor = $class->getConstructor();
if ($constructor) {
$result = [];
/** @var $parameter \ReflectionParameter */
foreach ($constructor->getParameters() as $parameter) {
try {
$result[] = [
$parameter->getName(),
$parameter->getClass() !== null ? $parameter->getClass()->getName() : null,
!$parameter->isOptional(),
$parameter->isOptional()
? ($parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null)
: null,
];
} catch (\ReflectionException $e) {
$message = $e->getMessage();
throw new \ReflectionException($message, 0, $e);
}
}
}
return $result;
}
/**
* Retrieve parent relation information for type in a following format
* array(
* 'Parent_Class_Name',
* 'Interface_1',
* 'Interface_2',
* ...
* )
*
* @param string $className
* @return string[]
*/
public function getParents($className)
{
$parentClass = get_parent_class($className);
if ($parentClass) {
$result = [];
$interfaces = class_implements($className);
if ($interfaces) {
$parentInterfaces = class_implements($parentClass);
if ($parentInterfaces) {
$result = array_values(array_diff($interfaces, $parentInterfaces));
} else {
$result = array_values($interfaces);
}
}
array_unshift($result, $parentClass);
} else {
$result = array_values(class_implements($className));
if ($result) {
array_unshift($result, null);
} else {
$result = [];
}
}
return $result;
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Code\Reader;
interface ClassReaderInterface
{
/**
* Read class constructor signature
*
* @param string $className
* @return array|null
* @throws \ReflectionException
*/
public function getConstructor($className);
/**
* Retrieve parent relation information for type in a following format
* array(
* 'Parent_Class_Name',
* 'Interface_1',
* 'Interface_2',
* ...
* )
*
* @param string $className
* @return string[]
*/
public function getParents($className);
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\Helper\Code;
/**
* Class ClassReader
*
* @internal
*/
class ClassReader
{
/**
* Read class method signature
*
* @param string $className
* @param string $method
* @return array|null
* @throws \ReflectionException
*/
public function getParameters($className, $method)
{
$class = new \ReflectionClass($className);
$result = null;
$method = $class->getMethod($method);
if ($method) {
$result = [];
/** @var $parameter \ReflectionParameter */
foreach ($method->getParameters() as $parameter) {
try {
$result[$parameter->getName()] = [
'type' => $parameter->getType() === null ? null : $parameter->getType()->getName(),
'variableName' => $parameter->getName(),
'isOptional' => $parameter->isOptional(),
'optionalValue' => $parameter->isOptional() ?
$parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null :
null
];
} catch (\ReflectionException $e) {
$message = $e->getMessage();
throw new \ReflectionException($message, 0, $e);
}
}
}
return $result;
}
}
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\FunctionalTestingFramework\System\Code;
/**
* Class ClassReader
*
* @internal
*/
class ClassReader
{
/**
* Read class method signature
*
* @param string $className
* @param string $method
* @return array|null
* @throws \ReflectionException
*/
public function getParameters($className, $method)
{
$class = new \ReflectionClass($className);
$result = null;
$method = $class->getMethod($method);
if ($method) {
$result = [];
/** @var $parameter \ReflectionParameter */
foreach ($method->getParameters() as $parameter) {
try {
$result[$parameter->getName()] = [
$parameter->getName(),
($parameter->getClass() !== null) ? $parameter->getClass()->getName() : null,
!$parameter->isOptional(),
$parameter->isOptional() ?
$parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null :
null
];
} catch (\ReflectionException $e) {
$message = $e->getMessage();
throw new \ReflectionException($message, 0, $e);
}
}
}
return $result;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend
{
/**
* Frontend or Core directives
*
* =====> (int) lifetime :
* - Cache lifetime (in seconds)
* - If null, the cache is valid forever
*
* =====> (int) logging :
* - if set to true, a logging is activated throw Zend_Log
*
* @var array directives
*/
protected $_directives = array(
'lifetime' => 3600,
'logging' => false,
'logger' => null
);
/**
* Available options
*
* @var array available options
*/
protected $_options = array();
/**
* Constructor
*
* @param array $options Associative array of options
*/
public function __construct(array $options = array())
{
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
if (!is_array($directives)) Zend_Cache::throwException('Directives parameter must be an array');
foreach ($directives as $name => $value) {
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_directives)) {
$this->_directives[$name] = $value;
}
}
$this->_loggerSanity();
}
/**
* Set an option
*
* @param string $name
* @param mixed $value
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
$this->_options[$name] = $value;
}
}
/**
* Returns an option
*
* @param string $name Optional, the options name to return
* @throws Zend_Cache_Exceptions
* @return mixed
*/
public function getOption($name)
{
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
return $this->_options[$name];
}
if (array_key_exists($name, $this->_directives)) {
return $this->_directives[$name];
}
Zend_Cache::throwException("Incorrect option name : {$name}");
}
/**
* Get the life time
*
* if $specificLifetime is not false, the given specific life time is used
* else, the global lifetime is used
*
* @param int $specificLifetime
* @return int Cache life time
*/
public function getLifetime($specificLifetime)
{
if ($specificLifetime === false) {
return $this->_directives['lifetime'];
}
return $specificLifetime;
}
/**
* Return true if the automatic cleaning is available for the backend
*
* DEPRECATED : use getCapabilities() instead
*
* @deprecated
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return true;
}
/**
* Determine system TMP directory and detect if we have read access
*
* inspired from Zend_File_Transfer_Adapter_Abstract
*
* @return string
* @throws Zend_Cache_Exception if unable to determine directory
*/
public function getTmpDir()
{
$tmpdir = array();
foreach (array($_ENV, $_SERVER) as $tab) {
foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
if (isset($tab[$key]) && is_string($tab[$key])) {
if (($key == 'windir') or ($key == 'SystemRoot')) {
$dir = realpath($tab[$key] . '\\temp');
} else {
$dir = realpath($tab[$key]);
}
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
}
}
$upload = ini_get('upload_tmp_dir');
if ($upload) {
$dir = realpath($upload);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if (function_exists('sys_get_temp_dir')) {
$dir = sys_get_temp_dir();
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
// Attemp to detect by creating a temporary file
$tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
if ($tempFile) {
$dir = realpath(dirname($tempFile));
unlink($tempFile);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if ($this->_isGoodTmpDir('/tmp')) {
return '/tmp';
}
if ($this->_isGoodTmpDir('\\temp')) {
return '\\temp';
}
Zend_Cache::throwException('Could not determine temp directory, please specify a cache_dir manually');
}
/**
* Verify if the given temporary directory is readable and writable
*
* @param string $dir temporary directory
* @return boolean true if the directory is ok
*/
protected function _isGoodTmpDir($dir)
{
if (is_readable($dir)) {
if (is_writable($dir)) {
return true;
}
}
return false;
}
/**
* Make sure if we enable logging that the Zend_Log class
* is available.
* Create a default log object if none is set.
*
* @throws Zend_Cache_Exception
* @return void
*/
protected function _loggerSanity()
{
if (!isset($this->_directives['logging']) || !$this->_directives['logging']) {
return;
}
if (isset($this->_directives['logger'])) {
if ($this->_directives['logger'] instanceof Zend_Log) {
return;
}
Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.');
}
// Create a default logger to the standard output stream
#require_once 'Zend/Log.php';
#require_once 'Zend/Log/Writer/Stream.php';
#require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
$logger->addFilter(new Zend_Log_Filter_Priority(Zend_Log::WARN, '<='));
$this->_directives['logger'] = $logger;
}
/**
* Log a message at the WARN (4) priority.
*
* @param string $message
* @param int $priority
* @return void
*/
protected function _log($message, $priority = 4)
{
if (!$this->_directives['logging']) {
return;
}
if (!isset($this->_directives['logger'])) {
Zend_Cache::throwException('Logging is enabled but logger is not set.');
}
$logger = $this->_directives['logger'];
if (!$logger instanceof Zend_Log) {
Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.');
}
$logger->log($message, $priority);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Apc extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND = 'Zend_Cache_Backend_Apc::clean() : tags are unsupported by the Apc backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND = 'Zend_Cache_Backend_Apc::save() : tags are unsupported by the Apc backend';
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('apc')) {
Zend_Cache::throwException('The apc extension must be loaded for using this backend !');
}
parent::__construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* WARNING $doNotTestCacheValidity=true is unsupported by the Apc backend
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$result = apc_store($id, array($data, time(), $lifetime), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return apc_delete($id);
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return apc_clear_cache('user');
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Apc::clean() : CLEANING_MODE_OLD is unsupported by the Apc backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* DEPRECATED : use getCapabilities() instead
*
* @deprecated
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* 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) {
Zend_Cache::throwException('can\'t get apc memory size');
}
if ($memUsed > $memSize) {
return 100;
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND);
return array();
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$ids = array();
$iterator = new APCIterator('user', null, APC_ITER_KEY);
foreach ($iterator as $item) {
$ids[] = $item['key'];
}
return $ids;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$tmp = apc_fetch($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
apc_store($id, array($data, time(), $newLifetime), $newLifetime);
return true;
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => true
);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_BlackHole
extends Zend_Cache_Backend
implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
return true;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return true;
}
/**
* Clean some cache records
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
* 'matchingAnyTag' => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode clean mode
* @param tags array $tags array of tags
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
return true;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
* @throws Zend_Cache_Exception
*/
public function getFillingPercentage()
{
return 0;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => true,
'tags' => true,
'expired_read' => true,
'priority' => true,
'infinite_lifetime' => true,
'get_list' => true,
);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/Interface.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_ExtendedInterface extends Zend_Cache_Backend_Interface
{
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds();
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags();
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array());
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array());
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array());
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage();
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id);
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime);
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities();
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_File extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* =====> (string) cache_dir :
* - Directory where to put the cache files
*
* =====> (boolean) file_locking :
* - Enable / disable file_locking
* - Can avoid cache corruption under bad circumstances but it doesn't work on multithread
* webservers and on NFS filesystems for example
*
* =====> (boolean) read_control :
* - Enable / disable read control
* - If enabled, a control key is embeded in cache file and this key is compared with the one
* calculated after the reading.
*
* =====> (string) read_control_type :
* - Type of read control (only if read control is enabled). Available values are :
* 'md5' for a md5 hash control (best but slowest)
* 'crc32' for a crc32 hash control (lightly less safe but faster, better choice)
* 'adler32' for an adler32 hash control (excellent choice too, faster than crc32)
* 'strlen' for a length only test (fastest)
*
* =====> (int) hashed_directory_level :
* - Hashed directory level
* - Set the hashed directory structure level. 0 means "no hashed directory
* structure", 1 means "one level of directory", 2 means "two levels"...
* This option can speed up the cache only when you have many thousands of
* cache file. Only specific benchs can help you to choose the perfect value
* for you. Maybe, 1 or 2 is a good start.
*
* =====> (int) hashed_directory_umask :
* - deprecated
* - Permissions for hashed directory structure
*
* =====> (int) hashed_directory_perm :
* - Permissions for hashed directory structure
*
* =====> (string) file_name_prefix :
* - prefix for cache files
* - be really carefull with this option because a too generic value in a system cache dir
* (like /tmp) can cause disasters when cleaning the cache
*
* =====> (int) cache_file_umask :
* - deprecated
* - Permissions for cache files
*
* =====> (int) cache_file_perm :
* - Permissions for cache files
*
* =====> (int) metatadatas_array_max_size :
* - max size for the metadatas array (don't change this value unless you
* know what you are doing)
*
* @var array available options
*/
protected $_options = array(
'cache_dir' => null,
'file_locking' => true,
'read_control' => true,
'read_control_type' => 'crc32',
'hashed_directory_level' => 0,
'hashed_directory_perm' => 0700,
'file_name_prefix' => 'zend_cache',
'cache_file_perm' => 0600,
'metadatas_array_max_size' => 100
);
/**
* Array of metadatas (each item is an associative array)
*
* @var array
*/
protected $_metadatasArray = array();
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if ($this->_options['cache_dir'] !== null) { // particular case for this option
$this->setCacheDir($this->_options['cache_dir']);
} else {
$this->setCacheDir(self::getTmpDir() . DIRECTORY_SEPARATOR, false);
}
if (isset($this->_options['file_name_prefix'])) { // particular case for this option
if (!preg_match('~^[a-zA-Z0-9_]+$~D', $this->_options['file_name_prefix'])) {
Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-Z0-9_]');
}
}
if ($this->_options['metadatas_array_max_size'] < 10) {
Zend_Cache::throwException('Invalid metadatas_array_max_size, must be > 10');
}
if (isset($options['hashed_directory_umask'])) {
// See #ZF-12047
trigger_error("'hashed_directory_umask' is deprecated -> please use 'hashed_directory_perm' instead", E_USER_NOTICE);
if (!isset($options['hashed_directory_perm'])) {
$options['hashed_directory_perm'] = $options['hashed_directory_umask'];
}
}
if (isset($options['hashed_directory_perm']) && is_string($options['hashed_directory_perm'])) {
// See #ZF-4422
$this->_options['hashed_directory_perm'] = octdec($this->_options['hashed_directory_perm']);
}
if (isset($options['cache_file_umask'])) {
// See #ZF-12047
trigger_error("'cache_file_umask' is deprecated -> please use 'cache_file_perm' instead", E_USER_NOTICE);
if (!isset($options['cache_file_perm'])) {
$options['cache_file_perm'] = $options['cache_file_umask'];
}
}
if (isset($options['cache_file_perm']) && is_string($options['cache_file_perm'])) {
// See #ZF-4422
$this->_options['cache_file_perm'] = octdec($this->_options['cache_file_perm']);
}
}
/**
* Set the cache_dir (particular case of setOption() method)
*
* @param string $value
* @param boolean $trailingSeparator If true, add a trailing separator is necessary
* @throws Zend_Cache_Exception
* @return void
*/
public function setCacheDir($value, $trailingSeparator = true)
{
if (!is_dir($value)) {
Zend_Cache::throwException(sprintf('cache_dir "%s" must be a directory', $value));
}
if (!is_writable($value)) {
Zend_Cache::throwException(sprintf('cache_dir "%s" is not writable', $value));
}
if ($trailingSeparator) {
// add a trailing DIRECTORY_SEPARATOR if necessary
$value = rtrim(realpath($value), '\\/') . DIRECTORY_SEPARATOR;
}
$this->_options['cache_dir'] = $value;
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
if (!($this->_test($id, $doNotTestCacheValidity))) {
// The cache is not hit !
return false;
}
$metadatas = $this->_getMetadatas($id);
$file = $this->_file($id);
$data = $this->_fileGetContents($file);
if ($this->_options['read_control']) {
$hashData = $this->_hash($data, $this->_options['read_control_type']);
$hashControl = $metadatas['hash'];
if ($hashData != $hashControl) {
// Problem detected by the read control !
$this->_log('Zend_Cache_Backend_File::load() / read_control : stored hash and computed hash do not match');
$this->remove($id);
return false;
}
}
return $data;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
clearstatcache();
return $this->_test($id, false);
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param boolean|int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
clearstatcache();
$file = $this->_file($id);
$path = $this->_path($id);
if ($this->_options['hashed_directory_level'] > 0) {
if (!is_writable($path)) {
// maybe, we just have to build the directory structure
$this->_recursiveMkdirAndChmod($id);
}
if (!is_writable($path)) {
return false;
}
}
if ($this->_options['read_control']) {
$hash = $this->_hash($data, $this->_options['read_control_type']);
} else {
$hash = '';
}
$metadatas = array(
'hash' => $hash,
'mtime' => time(),
'expire' => $this->_expireTime($this->getLifetime($specificLifetime)),
'tags' => $tags
);
$res = $this->_setMetadatas($id, $metadatas);
if (!$res) {
$this->_log('Zend_Cache_Backend_File::save() / error on saving metadata');
return false;
}
$res = $this->_filePutContents($file, $data);
return $res;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
$file = $this->_file($id);
$boolRemove = $this->_remove($file);
$boolMetadata = $this->_delMetadatas($id);
return $boolMetadata && $boolRemove;
}
/**
* 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)
* 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 => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* 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
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
// We use this protected method to hide the recursive stuff
clearstatcache();
return $this->_clean($this->_options['cache_dir'], $mode, $tags);
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return $this->_get($this->_options['cache_dir'], 'ids', array());
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return $this->_get($this->_options['cache_dir'], 'tags', array());
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
return $this->_get($this->_options['cache_dir'], 'matching', $tags);
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
return $this->_get($this->_options['cache_dir'], 'notMatching', $tags);
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
return $this->_get($this->_options['cache_dir'], 'matchingAny', $tags);
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$free = disk_free_space($this->_options['cache_dir']);
$total = disk_total_space($this->_options['cache_dir']);
if ($total == 0) {
Zend_Cache::throwException('can\'t get disk_total_space');
} else {
if ($free >= $total) {
return 100;
}
return ((int) (100. * ($total - $free) / $total));
}
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$metadatas = $this->_getMetadatas($id);
if (!$metadatas) {
return false;
}
if (time() > $metadatas['expire']) {
return false;
}
return array(
'expire' => $metadatas['expire'],
'tags' => $metadatas['tags'],
'mtime' => $metadatas['mtime']
);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$metadatas = $this->_getMetadatas($id);
if (!$metadatas) {
return false;
}
if (time() > $metadatas['expire']) {
return false;
}
$newMetadatas = array(
'hash' => $metadatas['hash'],
'mtime' => time(),
'expire' => $metadatas['expire'] + $extraLifetime,
'tags' => $metadatas['tags']
);
$res = $this->_setMetadatas($id, $newMetadatas);
if (!$res) {
return false;
}
return true;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => true,
'tags' => true,
'expired_read' => true,
'priority' => false,
'infinite_lifetime' => true,
'get_list' => true
);
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
$metadatas = $this->_getMetadatas($id);
if ($metadatas) {
$metadatas['expire'] = 1;
$this->_setMetadatas($id, $metadatas);
}
}
/**
* Get a metadatas record
*
* @param string $id Cache id
* @return array|false Associative array of metadatas
*/
protected function _getMetadatas($id)
{
if (isset($this->_metadatasArray[$id])) {
return $this->_metadatasArray[$id];
} else {
$metadatas = $this->_loadMetadatas($id);
if (!$metadatas) {
return false;
}
$this->_setMetadatas($id, $metadatas, false);
return $metadatas;
}
}
/**
* Set a metadatas record
*
* @param string $id Cache id
* @param array $metadatas Associative array of metadatas
* @param boolean $save optional pass false to disable saving to file
* @return boolean True if no problem
*/
protected function _setMetadatas($id, $metadatas, $save = true)
{
if (count($this->_metadatasArray) >= $this->_options['metadatas_array_max_size']) {
$n = (int) ($this->_options['metadatas_array_max_size'] / 10);
$this->_metadatasArray = array_slice($this->_metadatasArray, $n);
}
if ($save) {
$result = $this->_saveMetadatas($id, $metadatas);
if (!$result) {
return false;
}
}
$this->_metadatasArray[$id] = $metadatas;
return true;
}
/**
* Drop a metadata record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
protected function _delMetadatas($id)
{
if (isset($this->_metadatasArray[$id])) {
unset($this->_metadatasArray[$id]);
}
$file = $this->_metadatasFile($id);
return $this->_remove($file);
}
/**
* Clear the metadatas array
*
* @return void
*/
protected function _cleanMetadatas()
{
$this->_metadatasArray = array();
}
/**
* Load metadatas from disk
*
* @param string $id Cache id
* @return array|false Metadatas associative array
*/
protected function _loadMetadatas($id)
{
$file = $this->_metadatasFile($id);
$result = $this->_fileGetContents($file);
if (!$result) {
return false;
}
$tmp = @unserialize($result);
return $tmp;
}
/**
* Save metadatas to disk
*
* @param string $id Cache id
* @param array $metadatas Associative array
* @return boolean True if no problem
*/
protected function _saveMetadatas($id, $metadatas)
{
$file = $this->_metadatasFile($id);
$result = $this->_filePutContents($file, serialize($metadatas));
if (!$result) {
return false;
}
return true;
}
/**
* Make and return a file name (with path) for metadatas
*
* @param string $id Cache id
* @return string Metadatas file name (with path)
*/
protected function _metadatasFile($id)
{
$path = $this->_path($id);
$fileName = $this->_idToFileName('internal-metadatas---' . $id);
return $path . $fileName;
}
/**
* Check if the given filename is a metadatas one
*
* @param string $fileName File name
* @return boolean True if it's a metadatas one
*/
protected function _isMetadatasFile($fileName)
{
$id = $this->_fileNameToId($fileName);
if (substr($id, 0, 21) == 'internal-metadatas---') {
return true;
} else {
return false;
}
}
/**
* Remove a file
*
* If we can't remove the file (because of locks or any problem), we will touch
* the file to invalidate it
*
* @param string $file Complete file path
* @return boolean True if ok
*/
protected function _remove($file)
{
if (!is_file($file)) {
return false;
}
if (!@unlink($file)) {
# we can't remove the file (because of locks or any problem)
$this->_log("Zend_Cache_Backend_File::_remove() : we can't remove $file");
return false;
}
return true;
}
/**
* Clean some cache records (protected method used for recursive stuff)
*
* 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)
* 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 => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* 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 $dir Directory to clean
* @param string $mode Clean mode
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
if (!is_dir($dir)) {
return false;
}
$result = true;
$prefix = $this->_options['file_name_prefix'];
$glob = @glob($dir . $prefix . '--*');
if ($glob === false) {
// On some systems it is impossible to distinguish between empty match and an error.
return true;
}
$metadataFiles = array();
foreach ($glob as $file) {
if (is_file($file)) {
$fileName = basename($file);
if ($this->_isMetadatasFile($fileName)) {
// In CLEANING_MODE_ALL, we drop anything, even remainings old metadatas files.
// To do that, we need to save the list of the metadata files first.
if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
$metadataFiles[] = $file;
}
continue;
}
$id = $this->_fileNameToId($fileName);
$metadatas = $this->_getMetadatas($id);
if ($metadatas === FALSE) {
$metadatas = array('expire' => 1, 'tags' => array());
}
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$result = $result && $this->remove($id);
break;
case Zend_Cache::CLEANING_MODE_OLD:
if (time() > $metadatas['expire']) {
$result = $this->remove($id) && $result;
}
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$matching = true;
foreach ($tags as $tag) {
if (!in_array($tag, $metadatas['tags'])) {
$matching = false;
break;
}
}
if ($matching) {
$result = $this->remove($id) && $result;
}
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$matching = false;
foreach ($tags as $tag) {
if (in_array($tag, $metadatas['tags'])) {
$matching = true;
break;
}
}
if (!$matching) {
$result = $this->remove($id) && $result;
}
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$matching = false;
foreach ($tags as $tag) {
if (in_array($tag, $metadatas['tags'])) {
$matching = true;
break;
}
}
if ($matching) {
$result = $this->remove($id) && $result;
}
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) {
// Recursive call
$result = $this->_clean($file . DIRECTORY_SEPARATOR, $mode, $tags) && $result;
if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
// we try to drop the structure too
@rmdir($file);
}
}
}
// cycle through metadataFiles and delete orphaned ones
foreach ($metadataFiles as $file) {
if (file_exists($file)) {
$result = $this->_remove($file) && $result;
}
}
return $result;
}
protected function _get($dir, $mode, $tags = array())
{
if (!is_dir($dir)) {
return false;
}
$result = array();
$prefix = $this->_options['file_name_prefix'];
$glob = @glob($dir . $prefix . '--*');
if ($glob === false) {
// On some systems it is impossible to distinguish between empty match and an error.
return array();
}
foreach ($glob as $file) {
if (is_file($file)) {
$fileName = basename($file);
$id = $this->_fileNameToId($fileName);
$metadatas = $this->_getMetadatas($id);
if ($metadatas === FALSE) {
continue;
}
if (time() > $metadatas['expire']) {
continue;
}
switch ($mode) {
case 'ids':
$result[] = $id;
break;
case 'tags':
$result = array_unique(array_merge($result, $metadatas['tags']));
break;
case 'matching':
$matching = true;
foreach ($tags as $tag) {
if (!in_array($tag, $metadatas['tags'])) {
$matching = false;
break;
}
}
if ($matching) {
$result[] = $id;
}
break;
case 'notMatching':
$matching = false;
foreach ($tags as $tag) {
if (in_array($tag, $metadatas['tags'])) {
$matching = true;
break;
}
}
if (!$matching) {
$result[] = $id;
}
break;
case 'matchingAny':
$matching = false;
foreach ($tags as $tag) {
if (in_array($tag, $metadatas['tags'])) {
$matching = true;
break;
}
}
if ($matching) {
$result[] = $id;
}
break;
default:
Zend_Cache::throwException('Invalid mode for _get() method');
break;
}
}
if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) {
// Recursive call
$recursiveRs = $this->_get($file . DIRECTORY_SEPARATOR, $mode, $tags);
if ($recursiveRs === false) {
$this->_log('Zend_Cache_Backend_File::_get() / recursive call : can\'t list entries of "'.$file.'"');
} else {
$result = array_unique(array_merge($result, $recursiveRs));
}
}
}
return array_unique($result);
}
/**
* Compute & return the expire time
*
* @param int $lifetime
* @return int expire time (unix timestamp)
*/
protected function _expireTime($lifetime)
{
if ($lifetime === null) {
return 9999999999;
}
return time() + $lifetime;
}
/**
* 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:
Zend_Cache::throwException("Incorrect hash function : $controlType");
}
}
/**
* Transform a cache id into a file name and return it
*
* @param string $id Cache id
* @return string File name
*/
protected function _idToFileName($id)
{
$prefix = $this->_options['file_name_prefix'];
$result = $prefix . '---' . $id;
return $result;
}
/**
* Make and return a file name (with path)
*
* @param string $id Cache id
* @return string File name (with path)
*/
protected function _file($id)
{
$path = $this->_path($id);
$fileName = $this->_idToFileName($id);
return $path . $fileName;
}
/**
* Return the complete directory path of a filename (including hashedDirectoryStructure)
*
* @param string $id Cache id
* @param boolean $parts if true, returns array of directory parts instead of single string
* @return string Complete directory path
*/
protected function _path($id, $parts = false)
{
$partsArray = array();
$root = $this->_options['cache_dir'];
$prefix = $this->_options['file_name_prefix'];
if ($this->_options['hashed_directory_level']>0) {
$hash = hash('adler32', $id);
for ($i=0 ; $i < $this->_options['hashed_directory_level'] ; $i++) {
$root = $root . $prefix . '--' . substr($hash, 0, $i + 1) . DIRECTORY_SEPARATOR;
$partsArray[] = $root;
}
}
if ($parts) {
return $partsArray;
} else {
return $root;
}
}
/**
* Make the directory strucuture for the given id
*
* @param string $id cache id
* @return boolean true
*/
protected function _recursiveMkdirAndChmod($id)
{
if ($this->_options['hashed_directory_level'] <=0) {
return true;
}
$partsArray = $this->_path($id, true);
foreach ($partsArray as $part) {
if (!is_dir($part)) {
@mkdir($part, $this->_options['hashed_directory_perm']);
@chmod($part, $this->_options['hashed_directory_perm']); // see #ZF-320 (this line is required in some configurations)
}
}
return true;
}
/**
* Test if the given cache id is available (and still valid as a cache record)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return boolean|mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
protected function _test($id, $doNotTestCacheValidity)
{
$metadatas = $this->_getMetadatas($id);
if (!$metadatas) {
return false;
}
if ($doNotTestCacheValidity || (time() <= $metadatas['expire'])) {
return $metadatas['mtime'];
}
return false;
}
/**
* Return the file content of the given file
*
* @param string $file File complete path
* @return string File content (or false if problem)
*/
protected function _fileGetContents($file)
{
$result = false;
if (!is_file($file)) {
return false;
}
$f = @fopen($file, 'rb');
if ($f) {
if ($this->_options['file_locking']) @flock($f, LOCK_SH);
$result = stream_get_contents($f);
if ($this->_options['file_locking']) @flock($f, LOCK_UN);
@fclose($f);
}
return $result;
}
/**
* Put the given string into the given file
*
* @param string $file File complete path
* @param string $string String to put in file
* @return boolean true if no problem
*/
protected function _filePutContents($file, $string)
{
$result = false;
$f = @fopen($file, 'ab+');
if ($f) {
if ($this->_options['file_locking']) @flock($f, LOCK_EX);
fseek($f, 0);
ftruncate($f, 0);
$tmp = @fwrite($f, $string);
if (!($tmp === FALSE)) {
$result = true;
}
@fclose($f);
}
@chmod($file, $this->_options['cache_file_perm']);
return $result;
}
/**
* Transform a file name into cache id and return it
*
* @param string $fileName File name
* @return string Cache id
*/
protected function _fileNameToId($fileName)
{
$prefix = $this->_options['file_name_prefix'];
return preg_replace('~^' . $prefix . '---(.*)$~', '$1', $fileName);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
interface Zend_Cache_Backend_Interface
{
/**
* Set the frontend directives
*
* @param array $directives assoc of directives
*/
public function setDirectives($directives);
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false);
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id);
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false);
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id);
/**
* 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)
* 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 => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* 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
* @return boolean true if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array());
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Libmemcached extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Default Server Values
*/
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PORT = 11211;
const DEFAULT_WEIGHT = 1;
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_LIBMEMCACHED_BACKEND = 'Zend_Cache_Backend_Libmemcached::clean() : tags are unsupported by the Libmemcached backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND = 'Zend_Cache_Backend_Libmemcached::save() : tags are unsupported by the Libmemcached backend';
/**
* Available options
*
* =====> (array) servers :
* an array of memcached server ; each memcached server is described by an associative array :
* 'host' => (string) : the name of the memcached server
* 'port' => (int) : the port of the memcached server
* 'weight' => (int) : number of buckets to create for this server which in turn control its
* probability of it being selected. The probability is relative to the total
* weight of all servers.
* =====> (array) client :
* an array of memcached client options ; the memcached client is described by an associative array :
* @see http://php.net/manual/memcached.constants.php
* - The option name can be the name of the constant without the prefix 'OPT_'
* or the integer value of this option constant
*
* @var array available options
*/
protected $_options = array(
'servers' => array(array(
'host' => self::DEFAULT_HOST,
'port' => self::DEFAULT_PORT,
'weight' => self::DEFAULT_WEIGHT,
)),
'client' => array()
);
/**
* Memcached object
*
* @var mixed memcached object
*/
protected $_memcache = null;
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('memcached')) {
Zend_Cache::throwException('The memcached extension must be loaded for using this backend !');
}
// override default client options
$this->_options['client'] = array(
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_HASH => Memcached::HASH_MD5,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
);
parent::__construct($options);
if (isset($this->_options['servers'])) {
$value = $this->_options['servers'];
if (isset($value['host'])) {
// in this case, $value seems to be a simple associative array (one server only)
$value = array(0 => $value); // let's transform it into a classical array of associative arrays
}
$this->setOption('servers', $value);
}
$this->_memcache = new Memcached;
// setup memcached client options
foreach ($this->_options['client'] as $name => $value) {
$optId = null;
if (is_int($name)) {
$optId = $name;
} else {
$optConst = 'Memcached::OPT_' . strtoupper($name);
if (defined($optConst)) {
$optId = constant($optConst);
} else {
$this->_log("Unknown memcached client option '{$name}' ({$optConst})");
}
}
if (null !== $optId) {
if (!$this->_memcache->setOption($optId, $value)) {
$this->_log("Setting memcached client option '{$optId}' failed");
}
}
}
// setup memcached servers
$servers = array();
foreach ($this->_options['servers'] as $server) {
if (!array_key_exists('port', $server)) {
$server['port'] = self::DEFAULT_PORT;
}
if (!array_key_exists('weight', $server)) {
$server['weight'] = self::DEFAULT_WEIGHT;
}
$servers[] = array($server['host'], $server['port'], $server['weight']);
}
$this->_memcache->addServers($servers);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0])) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return int|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0], $tmp[1])) {
return (int)$tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
// ZF-8856: using set because add needs a second request if item already exists
$result = @$this->_memcache->set($id, array($data, time(), $lifetime), $lifetime);
if ($result === false) {
$rsCode = $this->_memcache->getResultCode();
$rsMsg = $this->_memcache->getResultMessage();
$this->_log("Memcached::set() failed: [{$rsCode}] {$rsMsg}");
}
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return $this->_memcache->delete($id);
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return $this->_memcache->flush();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Libmemcached::clean() : CLEANING_MODE_OLD is unsupported by the Libmemcached backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_LIBMEMCACHED_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
parent::setDirectives($directives);
$lifetime = $this->getLifetime(false);
if ($lifetime > 2592000) {
// #ZF-3490 : For the memcached backend, there is a lifetime limit of 30 days (2592000 seconds)
$this->_log('memcached backend has a limit of 30 days (2592000 seconds) for the lifetime');
}
if ($lifetime === null) {
// #ZF-4614 : we tranform null to zero to get the maximal lifetime
parent::setDirectives(array('lifetime' => 0));
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_log("Zend_Cache_Backend_Libmemcached::save() : getting the list of cache ids is unsupported by the Libmemcached backend");
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_LIBMEMCACHED_BACKEND);
return array();
}
/**
* 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->getStats();
if ($mems === false) {
return 0;
}
$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) {
Zend_Cache::throwException('Can\'t get filling percentage');
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0], $tmp[1], $tmp[2])) {
$data = $tmp[0];
$mtime = $tmp[1];
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$tmp = $this->_memcache->get($id);
if (isset($tmp[0], $tmp[1], $tmp[2])) {
$data = $tmp[0];
$mtime = $tmp[1];
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
// #ZF-5702 : we try replace() first becase set() seems to be slower
if (!($result = $this->_memcache->replace($id, array($data, time(), $newLifetime), $newLifetime))) {
$result = $this->_memcache->set($id, array($data, time(), $newLifetime), $newLifetime);
if ($result === false) {
$rsCode = $this->_memcache->getResultCode();
$rsMsg = $this->_memcache->getResultMessage();
$this->_log("Memcached::set() failed: [{$rsCode}] {$rsMsg}");
}
}
return $result;
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => false
);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Memcached extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Default Values
*/
const DEFAULT_HOST = '127.0.0.1';
const DEFAULT_PORT = 11211;
const DEFAULT_PERSISTENT = true;
const DEFAULT_WEIGHT = 1;
const DEFAULT_TIMEOUT = 1;
const DEFAULT_RETRY_INTERVAL = 15;
const DEFAULT_STATUS = true;
const DEFAULT_FAILURE_CALLBACK = null;
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_MEMCACHED_BACKEND = 'Zend_Cache_Backend_Memcached::clean() : tags are unsupported by the Memcached backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND = 'Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend';
/**
* Available options
*
* =====> (array) servers :
* an array of memcached server ; each memcached server is described by an associative array :
* 'host' => (string) : the name of the memcached server
* 'port' => (int) : the port of the memcached server
* 'persistent' => (bool) : use or not persistent connections to this memcached server
* 'weight' => (int) : number of buckets to create for this server which in turn control its
* probability of it being selected. The probability is relative to the total
* weight of all servers.
* 'timeout' => (int) : value in seconds which will be used for connecting to the daemon. Think twice
* before changing the default value of 1 second - you can lose all the
* advantages of caching if your connection is too slow.
* 'retry_interval' => (int) : controls how often a failed server will be retried, the default value
* is 15 seconds. Setting this parameter to -1 disables automatic retry.
* 'status' => (bool) : controls if the server should be flagged as online.
* 'failure_callback' => (callback) : Allows the user to specify a callback function to run upon
* encountering an error. The callback is run before failover
* is attempted. The function takes two parameters, the hostname
* and port of the failed server.
*
* =====> (boolean) compression :
* true if you want to use on-the-fly compression
*
* =====> (boolean) compatibility :
* true if you use old memcache server or extension
*
* @var array available options
*/
protected $_options = array(
'servers' => array(array(
'host' => self::DEFAULT_HOST,
'port' => self::DEFAULT_PORT,
'persistent' => self::DEFAULT_PERSISTENT,
'weight' => self::DEFAULT_WEIGHT,
'timeout' => self::DEFAULT_TIMEOUT,
'retry_interval' => self::DEFAULT_RETRY_INTERVAL,
'status' => self::DEFAULT_STATUS,
'failure_callback' => self::DEFAULT_FAILURE_CALLBACK
)),
'compression' => false,
'compatibility' => false,
);
/**
* Memcache object
*
* @var mixed memcache object
*/
protected $_memcache = null;
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('memcache')) {
Zend_Cache::throwException('The memcache extension must be loaded for using this backend !');
}
parent::__construct($options);
if (isset($this->_options['servers'])) {
$value= $this->_options['servers'];
if (isset($value['host'])) {
// in this case, $value seems to be a simple associative array (one server only)
$value = array(0 => $value); // let's transform it into a classical array of associative arrays
}
$this->setOption('servers', $value);
}
$this->_memcache = new Memcache;
foreach ($this->_options['servers'] as $server) {
if (!array_key_exists('port', $server)) {
$server['port'] = self::DEFAULT_PORT;
}
if (!array_key_exists('persistent', $server)) {
$server['persistent'] = self::DEFAULT_PERSISTENT;
}
if (!array_key_exists('weight', $server)) {
$server['weight'] = self::DEFAULT_WEIGHT;
}
if (!array_key_exists('timeout', $server)) {
$server['timeout'] = self::DEFAULT_TIMEOUT;
}
if (!array_key_exists('retry_interval', $server)) {
$server['retry_interval'] = self::DEFAULT_RETRY_INTERVAL;
}
if (!array_key_exists('status', $server)) {
$server['status'] = self::DEFAULT_STATUS;
}
if (!array_key_exists('failure_callback', $server)) {
$server['failure_callback'] = self::DEFAULT_FAILURE_CALLBACK;
}
if ($this->_options['compatibility']) {
// No status for compatibility mode (#ZF-5887)
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'],
$server['weight'], $server['timeout'],
$server['retry_interval']);
} else {
$this->_memcache->addServer($server['host'], $server['port'], $server['persistent'],
$server['weight'], $server['timeout'],
$server['retry_interval'],
$server['status'], $server['failure_callback']);
}
}
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp) && isset($tmp[0])) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
// ZF-8856: using set because add needs a second request if item already exists
$result = @$this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return $this->_memcache->delete($id, 0);
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return $this->_memcache->flush();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Memcached::clean() : CLEANING_MODE_OLD is unsupported by the Memcached backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_MEMCACHED_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Set the frontend directives
*
* @param array $directives Assoc of directives
* @throws Zend_Cache_Exception
* @return void
*/
public function setDirectives($directives)
{
parent::setDirectives($directives);
$lifetime = $this->getLifetime(false);
if ($lifetime > 2592000) {
// #ZF-3490 : For the memcached backend, there is a lifetime limit of 30 days (2592000 seconds)
$this->_log('memcached backend has a limit of 30 days (2592000 seconds) for the lifetime');
}
if ($lifetime === null) {
// #ZF-4614 : we tranform null to zero to get the maximal lifetime
parent::setDirectives(array('lifetime' => 0));
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$this->_log("Zend_Cache_Backend_Memcached::save() : getting the list of cache ids is unsupported by the Memcache backend");
return array();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND);
return array();
}
/**
* 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'];
/**
* Couchbase 1.x uses 'mem_used' instead of 'bytes'
* @see https://www.couchbase.com/issues/browse/MB-3466
*/
$eachUsed = isset($mem['bytes']) ? $mem['bytes'] : $mem['mem_used'];
if ($eachUsed > $eachSize) {
$eachUsed = $eachSize;
}
$memSize += $eachSize;
$memUsed += $eachUsed;
}
if ($memSize === null || $memUsed === null) {
Zend_Cache::throwException('Can\'t get filling percentage');
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
if ($this->_options['compression']) {
$flag = MEMCACHE_COMPRESSED;
} else {
$flag = 0;
}
$tmp = $this->_memcache->get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
// because this record is only with 1.7 release
// if old cache records are still there...
return false;
}
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
// #ZF-5702 : we try replace() first becase set() seems to be slower
if (!($result = $this->_memcache->replace($id, array($data, time(), $newLifetime), $flag, $newLifetime))) {
$result = $this->_memcache->set($id, array($data, time(), $newLifetime), $flag, $newLifetime);
}
return $result;
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => false
);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/Interface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Static
extends Zend_Cache_Backend
implements Zend_Cache_Backend_Interface
{
const INNER_CACHE_NAME = 'zend_cache_backend_static_tagcache';
/**
* Static backend options
* @var array
*/
protected $_options = array(
'public_dir' => null,
'sub_dir' => 'html',
'file_extension' => '.html',
'index_filename' => 'index',
'file_locking' => true,
'cache_file_perm' => 0600,
'cache_directory_perm' => 0700,
'debug_header' => false,
'tag_cache' => null,
'disable_caching' => false
);
/**
* Cache for handling tags
* @var Zend_Cache_Core
*/
protected $_tagCache = null;
/**
* Tagged items
* @var array
*/
protected $_tagged = null;
/**
* Interceptor child method to handle the case where an Inner
* Cache object is being set since it's not supported by the
* standard backend interface
*
* @param string $name
* @param mixed $value
* @return Zend_Cache_Backend_Static
*/
public function setOption($name, $value)
{
if ($name == 'tag_cache') {
$this->setInnerCache($value);
} else {
// See #ZF-12047 and #GH-91
if ($name == 'cache_file_umask') {
trigger_error(
"'cache_file_umask' is deprecated -> please use 'cache_file_perm' instead",
E_USER_NOTICE
);
$name = 'cache_file_perm';
}
if ($name == 'cache_directory_umask') {
trigger_error(
"'cache_directory_umask' is deprecated -> please use 'cache_directory_perm' instead",
E_USER_NOTICE
);
$name = 'cache_directory_perm';
}
parent::setOption($name, $value);
}
return $this;
}
/**
* Retrieve any option via interception of the parent's statically held
* options including the local option for a tag cache.
*
* @param string $name
* @return mixed
*/
public function getOption($name)
{
$name = strtolower($name);
if ($name == 'tag_cache') {
return $this->getInnerCache();
}
return parent::getOption($name);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
if (($id = (string)$id) === '') {
$id = $this->_detectId();
} else {
$id = $this->_decodeId($id);
}
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
if ($doNotTestCacheValidity) {
$this->_log("Zend_Cache_Backend_Static::load() : \$doNotTestCacheValidity=true is unsupported by the Static backend");
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = $this->_options['public_dir'] . dirname($id);
$file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension'];
if (file_exists($file)) {
$content = file_get_contents($file);
return $content;
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return bool
*/
public function test($id)
{
$id = $this->_decodeId($id);
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (!$this->_tagged) {
return false;
}
$pathName = $this->_options['public_dir'] . dirname($id);
// Switch extension if needed
if (isset($this->_tagged[$id])) {
$extension = $this->_tagged[$id]['extension'];
} else {
$extension = $this->_options['file_extension'];
}
$file = $pathName . '/' . $fileName . $extension;
if (file_exists($file)) {
return true;
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
if ($this->_options['disable_caching']) {
return true;
}
$extension = null;
if ($this->_isSerialized($data)) {
$data = unserialize($data);
$extension = '.' . ltrim($data[1], '.');
$data = $data[0];
}
clearstatcache();
if (($id = (string)$id) === '') {
$id = $this->_detectId();
} else {
$id = $this->_decodeId($id);
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = realpath($this->_options['public_dir']) . dirname($id);
$this->_createDirectoriesFor($pathName);
if ($id === null || strlen($id) == 0) {
$dataUnserialized = unserialize($data);
$data = $dataUnserialized['data'];
}
$ext = $this->_options['file_extension'];
if ($extension) $ext = $extension;
$file = rtrim($pathName, '/') . '/' . $fileName . $ext;
if ($this->_options['file_locking']) {
$result = file_put_contents($file, $data, LOCK_EX);
} else {
$result = file_put_contents($file, $data);
}
@chmod($file, $this->_octdec($this->_options['cache_file_perm']));
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif ($this->_tagged === null) {
$this->_tagged = array();
}
if (!isset($this->_tagged[$id])) {
$this->_tagged[$id] = array();
}
if (!isset($this->_tagged[$id]['tags'])) {
$this->_tagged[$id]['tags'] = array();
}
$this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id]['tags'], $tags));
$this->_tagged[$id]['extension'] = $ext;
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
return (bool) $result;
}
/**
* Recursively create the directories needed to write the static file
*/
protected function _createDirectoriesFor($path)
{
if (!is_dir($path)) {
$oldUmask = umask(0);
if ( !@mkdir($path, $this->_octdec($this->_options['cache_directory_perm']), true)) {
$lastErr = error_get_last();
umask($oldUmask);
Zend_Cache::throwException("Can't create directory: {$lastErr['message']}");
}
umask($oldUmask);
}
}
/**
* Detect serialization of data (cannot predict since this is the only way
* to obey the interface yet pass in another parameter).
*
* In future, ZF 2.0, check if we can just avoid the interface restraints.
*
* This format is the only valid one possible for the class, so it's simple
* to just run a regular expression for the starting serialized format.
*/
protected function _isSerialized($data)
{
return preg_match("/a:2:\{i:0;s:\d+:\"/", $data);
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
$fileName = basename($id);
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (!$this->_tagged) {
return false;
}
if (isset($this->_tagged[$id])) {
$extension = $this->_tagged[$id]['extension'];
} else {
$extension = $this->_options['file_extension'];
}
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = $this->_options['public_dir'] . dirname($id);
$file = realpath($pathName) . '/' . $fileName . $extension;
if (!file_exists($file)) {
return false;
}
return unlink($file);
}
/**
* Remove a cache record recursively for the given directory matching a
* REQUEST_URI based relative path (deletes the actual file matching this
* in addition to the matching directory)
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function removeRecursively($id)
{
if (!$this->_verifyPath($id)) {
Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path');
}
$fileName = basename($id);
if ($fileName === '') {
$fileName = $this->_options['index_filename'];
}
$pathName = $this->_options['public_dir'] . dirname($id);
$file = $pathName . '/' . $fileName . $this->_options['file_extension'];
$directory = $pathName . '/' . $fileName;
if (file_exists($directory)) {
if (!is_writable($directory)) {
return false;
}
if (is_dir($directory)) {
foreach (new DirectoryIterator($directory) as $file) {
if (true === $file->isFile()) {
if (false === unlink($file->getPathName())) {
return false;
}
}
}
}
rmdir($directory);
}
if (file_exists($file)) {
if (!is_writable($file)) {
return false;
}
return unlink($file);
}
return true;
}
/**
* 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)
* 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 => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* 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
* @return boolean true if no problem
* @throws Zend_Exception
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
$result = false;
switch ($mode) {
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
if (empty($tags)) {
throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
}
if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) {
$this->_tagged = $tagged;
} elseif (!$this->_tagged) {
return true;
}
foreach ($tags as $tag) {
$urls = array_keys($this->_tagged);
foreach ($urls as $url) {
if (isset($this->_tagged[$url]['tags']) && in_array($tag, $this->_tagged[$url]['tags'])) {
$this->remove($url);
unset($this->_tagged[$url]);
}
}
}
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
$result = true;
break;
case Zend_Cache::CLEANING_MODE_ALL:
if ($this->_tagged === null) {
$tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
$this->_tagged = $tagged;
}
if ($this->_tagged === null || empty($this->_tagged)) {
return true;
}
$urls = array_keys($this->_tagged);
foreach ($urls as $url) {
$this->remove($url);
unset($this->_tagged[$url]);
}
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
$result = true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Static : Selected Cleaning Mode Currently Unsupported By This Backend");
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
if (empty($tags)) {
throw new Zend_Exception('Cannot use tag matching modes as no tags were defined');
}
if ($this->_tagged === null) {
$tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME);
$this->_tagged = $tagged;
}
if ($this->_tagged === null || empty($this->_tagged)) {
return true;
}
$urls = array_keys($this->_tagged);
foreach ($urls as $url) {
$difference = array_diff($tags, $this->_tagged[$url]['tags']);
if (count($tags) == count($difference)) {
$this->remove($url);
unset($this->_tagged[$url]);
}
}
$this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME);
$result = true;
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
return $result;
}
/**
* Set an Inner Cache, used here primarily to store Tags associated
* with caches created by this backend. Note: If Tags are lost, the cache
* should be completely cleaned as the mapping of tags to caches will
* have been irrevocably lost.
*
* @param Zend_Cache_Core
* @return void
*/
public function setInnerCache(Zend_Cache_Core $cache)
{
$this->_tagCache = $cache;
$this->_options['tag_cache'] = $cache;
}
/**
* Get the Inner Cache if set
*
* @return Zend_Cache_Core
*/
public function getInnerCache()
{
if ($this->_tagCache === null) {
Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()');
}
return $this->_tagCache;
}
/**
* Verify path exists and is non-empty
*
* @param string $path
* @return bool
*/
protected function _verifyPath($path)
{
$path = realpath($path);
$base = realpath($this->_options['public_dir']);
return strncmp($path, $base, strlen($base)) !== 0;
}
/**
* Determine the page to save from the request
*
* @return string
*/
protected function _detectId()
{
return $_SERVER['REQUEST_URI'];
}
/**
* 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)) {
Zend_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
)
) {
Zend_Cache::throwException("Invalid id or tag '$string' : must be a valid URL path");
}
}
/**
* Detect an octal string and return its octal value for file permission ops
* otherwise return the non-string (assumed octal or decimal int already)
*
* @param string $val The potential octal in need of conversion
* @return int
*/
protected function _octdec($val)
{
if (is_string($val) && decoct(octdec($val)) == $val) {
return octdec($val);
}
return $val;
}
/**
* Decode a request URI from the provided ID
*
* @param string $id
* @return string
*/
protected function _decodeId($id)
{
return pack('H*', $id);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Test extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* @var array available options
*/
protected $_options = array();
/**
* Frontend or Core directives
*
* @var array directives
*/
protected $_directives = array();
/**
* Array to log actions
*
* @var array $_log
*/
private $_log = array();
/**
* Current index for log array
*
* @var int $_index
*/
private $_index = 0;
/**
* Constructor
*
* @param array $options associative array of options
* @return void
*/
public function __construct($options = array())
{
$this->_addLog('construct', array($options));
}
/**
* Set the frontend directives
*
* @param array $directives assoc of directives
* @return void
*/
public function setDirectives($directives)
{
$this->_addLog('setDirectives', array($directives));
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* For this test backend only, if $id == 'false', then the method will return false
* if $id == 'serialized', the method will return a serialized array
* ('foo' else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string Cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$this->_addLog('get', array($id, $doNotTestCacheValidity));
if ( $id == 'false'
|| $id == 'd8523b3ee441006261eeffa5c3d3a0a7'
|| $id == 'e83249ea22178277d5befc2c5e2e9ace'
|| $id == '40f649b94977c0a6e76902e2a0b43587'
|| $id == '88161989b73a4cbfd0b701c446115a99'
|| $id == '205fc79cba24f0f0018eb92c7c8b3ba4'
|| $id == '170720e35f38150b811f68a937fb042d')
{
return false;
}
if ($id=='serialized') {
return serialize(array('foo'));
}
if ($id=='serialized2') {
return serialize(array('headers' => array(), 'data' => 'foo'));
}
if ( $id == '71769f39054f75894288e397df04e445' || $id == '615d222619fb20b527168340cebd0578'
|| $id == '8a02d218a5165c467e7a5747cc6bd4b6' || $id == '648aca1366211d17cbf48e65dc570bee'
|| $id == '4a923ef02d7f997ca14d56dfeae25ea7') {
return serialize(array('foo', 'bar'));
}
if ( $id == 'f53c7d912cc523d9a65834c8286eceb9') {
return serialize(array('foobar'));
}
return 'foo';
}
/**
* Test if a cache is available or not (for the given id)
*
* For this test backend only, if $id == 'false', then the method will return false
* (123456 else)
*
* @param string $id Cache id
* @return mixed|false false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$this->_addLog('test', array($id));
if ($id=='false') {
return false;
}
if (($id=='3c439c922209e2cb0b54d6deffccd75a')) {
return false;
}
return 123456;
}
/**
* Save some string datas into a cache record
*
* For this test backend only, if $id == 'false', then the method will return false
* (true else)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean True if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$this->_addLog('save', array($data, $id, $tags));
if (substr($id,-5)=='false') {
return false;
}
return true;
}
/**
* Remove a cache record
*
* For this test backend only, if $id == 'false', then the method will return false
* (true else)
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$this->_addLog('remove', array($id));
if (substr($id,-5)=='false') {
return false;
}
return true;
}
/**
* Clean some cache records
*
* For this test backend only, if $mode == 'false', then the method will return false
* (true else)
*
* 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)
* 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 => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
*
* @param string $mode Clean mode
* @param array $tags Array of tags
* @return boolean True if no problem
*/
public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
$this->_addLog('clean', array($mode, $tags));
if ($mode=='false') {
return false;
}
return true;
}
/**
* Get the last log
*
* @return string The last log
*/
public function getLastLog()
{
return $this->_log[$this->_index - 1];
}
/**
* Get the log index
*
* @return int Log index
*/
public function getLogIndex()
{
return $this->_index;
}
/**
* Get the complete log array
*
* @return array Complete log array
*/
public function getAllLogs()
{
return $this->_log;
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return true;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return array(
'prefix_id1', 'prefix_id2'
);
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return array(
'tag1', 'tag2'
);
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
if ($tags == array('tag1', 'tag2')) {
return array('prefix_id1', 'prefix_id2');
}
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
if ($tags == array('tag3', 'tag4')) {
return array('prefix_id3', 'prefix_id4');
}
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
if ($tags == array('tag5', 'tag6')) {
return array('prefix_id5', 'prefix_id6');
}
return array();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
return 50;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
return true;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => true,
'tags' => true,
'expired_read' => false,
'priority' => true,
'infinite_lifetime' => true,
'get_list' => true
);
}
/**
* Add an event to the log array
*
* @param string $methodName MethodName
* @param array $args Arguments
* @return void
*/
private function _addLog($methodName, $args)
{
$this->_log[$this->_index] = array(
'methodName' => $methodName,
'args' => $args
);
$this->_index = $this->_index + 1;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_ExtendedInterface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Available options
*
* =====> (string) slow_backend :
* - Slow backend name
* - Must implement the Zend_Cache_Backend_ExtendedInterface
* - Should provide a big storage
*
* =====> (string) fast_backend :
* - Flow backend name
* - Must implement the Zend_Cache_Backend_ExtendedInterface
* - Must be much faster than slow_backend
*
* =====> (array) slow_backend_options :
* - Slow backend options (see corresponding backend)
*
* =====> (array) fast_backend_options :
* - Fast backend options (see corresponding backend)
*
* =====> (int) stats_update_factor :
* - Disable / Tune the computation of the fast backend filling percentage
* - When saving a record into cache :
* 1 => systematic computation of the fast backend filling percentage
* x (integer) > 1 => computation of the fast backend filling percentage randomly 1 times on x cache write
*
* =====> (boolean) slow_backend_custom_naming :
* =====> (boolean) fast_backend_custom_naming :
* =====> (boolean) slow_backend_autoload :
* =====> (boolean) fast_backend_autoload :
* - See Zend_Cache::factory() method
*
* =====> (boolean) auto_fill_fast_cache
* - If true, automatically fill the fast cache when a cache record was not found in fast cache, but did
* exist in slow cache. This can be usefull when a non-persistent cache like APC or Memcached got
* purged for whatever reason.
*
* =====> (boolean) auto_refresh_fast_cache
* - If true, auto refresh the fast cache when a cache record is hit
*
* @var array available options
*/
protected $_options = array(
'slow_backend' => 'File',
'fast_backend' => 'Apc',
'slow_backend_options' => array(),
'fast_backend_options' => array(),
'stats_update_factor' => 10,
'slow_backend_custom_naming' => false,
'fast_backend_custom_naming' => false,
'slow_backend_autoload' => false,
'fast_backend_autoload' => false,
'auto_fill_fast_cache' => true,
'auto_refresh_fast_cache' => true
);
/**
* Slow Backend
*
* @var Zend_Cache_Backend_ExtendedInterface
*/
protected $_slowBackend;
/**
* Fast Backend
*
* @var Zend_Cache_Backend_ExtendedInterface
*/
protected $_fastBackend;
/**
* Cache for the fast backend filling percentage
*
* @var int
*/
protected $_fastBackendFillingPercentage = null;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
if ($this->_options['slow_backend'] === null) {
Zend_Cache::throwException('slow_backend option has to set');
} elseif ($this->_options['slow_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
$this->_slowBackend = $this->_options['slow_backend'];
} else {
$this->_slowBackend = Zend_Cache::_makeBackend(
$this->_options['slow_backend'],
$this->_options['slow_backend_options'],
$this->_options['slow_backend_custom_naming'],
$this->_options['slow_backend_autoload']
);
if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
}
}
if ($this->_options['fast_backend'] === null) {
Zend_Cache::throwException('fast_backend option has to set');
} elseif ($this->_options['fast_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
$this->_fastBackend = $this->_options['fast_backend'];
} else {
$this->_fastBackend = Zend_Cache::_makeBackend(
$this->_options['fast_backend'],
$this->_options['fast_backend_options'],
$this->_options['fast_backend_custom_naming'],
$this->_options['fast_backend_autoload']
);
if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
}
}
$this->_slowBackend->setDirectives($this->_directives);
$this->_fastBackend->setDirectives($this->_directives);
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$fastTest = $this->_fastBackend->test($id);
if ($fastTest) {
return $fastTest;
} else {
return $this->_slowBackend->test($id);
}
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Datas to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
{
$usage = $this->_getFastFillingPercentage('saving');
$boolFast = true;
$lifetime = $this->getLifetime($specificLifetime);
$preparedData = $this->_prepareData($data, $lifetime, $priority);
if (($priority > 0) && (10 * $priority >= $usage)) {
$fastLifetime = $this->_getFastLifetime($lifetime, $priority);
$boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
$boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
} else {
$boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
if ($boolSlow === true) {
$boolFast = $this->_fastBackend->remove($id);
if (!$boolFast && !$this->_fastBackend->test($id)) {
// some backends return false on remove() even if the key never existed. (and it won't if fast is full)
// all we care about is that the key doesn't exist now
$boolFast = true;
}
}
}
return ($boolFast && $boolSlow);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* Note : return value is always "string" (unserialization is done by the core not by the backend)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string|false cached datas
*/
public function load($id, $doNotTestCacheValidity = false)
{
$resultFast = $this->_fastBackend->load($id, $doNotTestCacheValidity);
if ($resultFast === false) {
$resultSlow = $this->_slowBackend->load($id, $doNotTestCacheValidity);
if ($resultSlow === false) {
// there is no cache at all for this id
return false;
}
}
$array = $resultFast !== false ? unserialize($resultFast) : unserialize($resultSlow);
//In case no cache entry was found in the FastCache and auto-filling is enabled, copy data to FastCache
if ($resultFast === false && $this->_options['auto_fill_fast_cache']) {
$preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
$this->_fastBackend->save($preparedData, $id, array(), $array['lifetime']);
}
// maybe, we have to refresh the fast cache ?
elseif ($this->_options['auto_refresh_fast_cache']) {
if ($array['priority'] == 10) {
// no need to refresh the fast cache with priority = 10
return $array['data'];
}
$newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
// we have the time to refresh the fast cache
$usage = $this->_getFastFillingPercentage('loading');
if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
// we can refresh the fast cache
$preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
$this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
}
}
return $array['data'];
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
$boolFast = $this->_fastBackend->remove($id);
$boolSlow = $this->_slowBackend->remove($id);
return $boolFast && $boolSlow;
}
/**
* 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)
* 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 => remove cache entries not {matching one of the given tags}
* ($tags can be an array of strings or a single string)
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
$boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
return $boolFast && $boolSlow;
break;
case Zend_Cache::CLEANING_MODE_OLD:
return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
$ids = $this->_slowBackend->getIdsMatchingTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
$ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
$res = true;
foreach ($ids as $id) {
$bool = $this->remove($id);
$res = $res && $bool;
}
return $res;
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
return $this->_slowBackend->getIds();
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
return $this->_slowBackend->getTags();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
return $this->_slowBackend->getIdsMatchingTags($tags);
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
return $this->_slowBackend->getIdsNotMatchingTags($tags);
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
return $this->_slowBackend->getIdsMatchingAnyTags($tags);
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
return $this->_slowBackend->getFillingPercentage();
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
return $this->_slowBackend->getMetadatas($id);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
return $this->_slowBackend->touch($id, $extraLifetime);
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
$slowBackendCapabilities = $this->_slowBackend->getCapabilities();
return array(
'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
'tags' => $slowBackendCapabilities['tags'],
'expired_read' => $slowBackendCapabilities['expired_read'],
'priority' => $slowBackendCapabilities['priority'],
'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
'get_list' => $slowBackendCapabilities['get_list']
);
}
/**
* Prepare a serialized array to store datas and metadatas informations
*
* @param string $data data to store
* @param int $lifetime original lifetime
* @param int $priority priority
* @return string serialize array to store into cache
*/
private function _prepareData($data, $lifetime, $priority)
{
$lt = $lifetime;
if ($lt === null) {
$lt = 9999999999;
}
return serialize(array(
'data' => $data,
'lifetime' => $lifetime,
'expire' => time() + $lt,
'priority' => $priority
));
}
/**
* Compute and return the lifetime for the fast backend
*
* @param int $lifetime original lifetime
* @param int $priority priority
* @param int $maxLifetime maximum lifetime
* @return int lifetime for the fast backend
*/
private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
{
if ($lifetime <= 0) {
// if no lifetime, we have an infinite lifetime
// we need to use arbitrary lifetimes
$fastLifetime = (int) (2592000 / (11 - $priority));
} else {
// prevent computed infinite lifetime (0) by ceil
$fastLifetime = (int) ceil($lifetime / (11 - $priority));
}
if ($maxLifetime >= 0 && $fastLifetime > $maxLifetime) {
return $maxLifetime;
}
return $fastLifetime;
}
/**
* PUBLIC METHOD FOR UNIT TESTING ONLY !
*
* Force a cache record to expire
*
* @param string $id cache id
*/
public function ___expire($id)
{
$this->_fastBackend->remove($id);
$this->_slowBackend->___expire($id);
}
private function _getFastFillingPercentage($mode)
{
if ($mode == 'saving') {
// mode saving
if ($this->_fastBackendFillingPercentage === null) {
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
} else {
$rand = rand(1, $this->_options['stats_update_factor']);
if ($rand == 1) {
// we force a refresh
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
}
}
} else {
// mode loading
// we compute the percentage only if it's not available in cache
if ($this->_fastBackendFillingPercentage === null) {
$this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
}
}
return $this->_fastBackendFillingPercentage;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/ExtendedInterface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_WinCache extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_WINCACHE_BACKEND = 'Zend_Cache_Backend_WinCache::clean() : tags are unsupported by the WinCache backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND = 'Zend_Cache_Backend_WinCache::save() : tags are unsupported by the WinCache backend';
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('wincache')) {
Zend_Cache::throwException('The wincache extension must be loaded for using this backend !');
}
parent::__construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* WARNING $doNotTestCacheValidity=true is unsupported by the WinCache backend
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
return $tmp[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$result = wincache_ucache_set($id, array($data, time(), $lifetime), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return wincache_ucache_delete($id);
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
return wincache_ucache_clear();
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_WinCache::clean() : CLEANING_MODE_OLD is unsupported by the WinCache backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_WINCACHE_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* DEPRECATED : use getCapabilities() instead
*
* @deprecated
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
/**
* Return the filling percentage of the backend storage
*
* @throws Zend_Cache_Exception
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
$mem = wincache_ucache_meminfo();
$memSize = $mem['memory_total'];
$memUsed = $memSize - $mem['memory_free'];
if ($memSize == 0) {
Zend_Cache::throwException('can\'t get WinCache memory size');
}
if ($memUsed > $memSize) {
return 100;
}
return ((int) (100. * ($memUsed / $memSize)));
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of any matching cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_WINCACHE_BACKEND);
return array();
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
$res = array();
$array = wincache_ucache_info();
$records = $array['ucache_entries'];
foreach ($records as $record) {
$res[] = $record['key_name'];
}
return $res;
}
/**
* Return an array of metadatas for the given cache id
*
* The array must include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
return false;
}
$lifetime = $tmp[2];
return array(
'expire' => $mtime + $lifetime,
'tags' => array(),
'mtime' => $mtime
);
}
return false;
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
$tmp = wincache_ucache_get($id);
if (is_array($tmp)) {
$data = $tmp[0];
$mtime = $tmp[1];
if (!isset($tmp[2])) {
return false;
}
$lifetime = $tmp[2];
$newLifetime = $lifetime - (time() - $mtime) + $extraLifetime;
if ($newLifetime <=0) {
return false;
}
return wincache_ucache_set($id, array($data, time(), $newLifetime), $newLifetime);
}
return false;
}
/**
* Return an associative array of capabilities (booleans) of the backend
*
* The array must include these keys :
* - automatic_cleaning (is automating cleaning necessary)
* - tags (are tags supported)
* - expired_read (is it possible to read expired cache records
* (for doNotTestCacheValidity option for example))
* - priority does the backend deal with priority when saving
* - infinite_lifetime (is infinite lifetime can work with this backend)
* - get_list (is it possible to get the list of cache ids and the complete list of tags)
*
* @return array associative of with capabilities
*/
public function getCapabilities()
{
return array(
'automatic_cleaning' => false,
'tags' => false,
'expired_read' => false,
'priority' => false,
'infinite_lifetime' => false,
'get_list' => true
);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/Interface.php';
/**
* @see Zend_Cache_Backend
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_Xcache extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Log message
*/
const TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND = 'Zend_Cache_Backend_Xcache::clean() : tags are unsupported by the Xcache backend';
const TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND = 'Zend_Cache_Backend_Xcache::save() : tags are unsupported by the Xcache backend';
/**
* Available options
*
* =====> (string) user :
* xcache.admin.user (necessary for the clean() method)
*
* =====> (string) password :
* xcache.admin.pass (clear, not MD5) (necessary for the clean() method)
*
* @var array available options
*/
protected $_options = array(
'user' => null,
'password' => null
);
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!extension_loaded('xcache')) {
Zend_Cache::throwException('The xcache extension must be loaded for using this backend !');
}
parent::__construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* WARNING $doNotTestCacheValidity=true is unsupported by the Xcache backend
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
if ($doNotTestCacheValidity) {
$this->_log("Zend_Cache_Backend_Xcache::load() : \$doNotTestCacheValidity=true is unsupported by the Xcache backend");
}
$tmp = xcache_get($id);
if (is_array($tmp)) {
return $tmp[0];
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
if (xcache_isset($id)) {
$tmp = xcache_get($id);
if (is_array($tmp)) {
return $tmp[1];
}
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$result = xcache_set($id, array($data, time()), $lifetime);
if (count($tags) > 0) {
$this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_XCACHE_BACKEND);
}
return $result;
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
return xcache_unset($id);
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_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'];
}
$cnt = xcache_count(XC_TYPE_VAR);
for ($i=0; $i < $cnt; $i++) {
xcache_clear_cache(XC_TYPE_VAR, $i);
}
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 Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_Xcache::clean() : CLEANING_MODE_OLD is unsupported by the Xcache backend");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND);
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Return true if the automatic cleaning is available for the backend
*
* @return boolean
*/
public function isAutomaticCleaningAvailable()
{
return false;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend.php';
/**
* @see Zend_Cache_Backend_Interface
*/
#require_once 'Zend/Cache/Backend/Interface.php';
/**
* Impementation of Zend Cache Backend using the Zend Platform (Output Content Caching)
*
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendPlatform extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* internal ZP prefix
*/
const TAGS_PREFIX = "internal_ZPtag:";
/**
* Constructor
* Validate that the Zend Platform is loaded and licensed
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
if (!function_exists('accelerator_license_info')) {
Zend_Cache::throwException('The Zend Platform extension must be loaded for using this backend !');
}
if (!function_exists('accelerator_get_configuration')) {
$licenseInfo = accelerator_license_info();
Zend_Cache::throwException('The Zend Platform extension is not loaded correctly: '.$licenseInfo['failure_reason']);
}
$accConf = accelerator_get_configuration();
if (@!$accConf['output_cache_licensed']) {
Zend_Cache::throwException('The Zend Platform extension does not have the proper license to use content caching features');
}
if (@!$accConf['output_cache_enabled']) {
Zend_Cache::throwException('The Zend Platform content caching feature must be enabled for using this backend, set the \'zend_accelerator.output_cache_enabled\' directive to On !');
}
if (!is_writable($accConf['output_cache_dir'])) {
Zend_Cache::throwException('The cache copies directory \''. ini_get('zend_accelerator.output_cache_dir') .'\' must be writable !');
}
parent:: __construct($options);
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @return string Cached data (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
// doNotTestCacheValidity implemented by giving zero lifetime to the cache
if ($doNotTestCacheValidity) {
$lifetime = 0;
} else {
$lifetime = $this->_directives['lifetime'];
}
$res = output_cache_get($id, $lifetime);
if($res) {
return $res[0];
} else {
return false;
}
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id Cache id
* @return mixed|false false (a cache is not available) or "last modified" timestamp (int) of the available cache record
*/
public function test($id)
{
$result = output_cache_get($id, $this->_directives['lifetime']);
if ($result) {
return $result[1];
}
return false;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data Data to cache
* @param string $id Cache id
* @param array $tags Array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
if (!($specificLifetime === false)) {
$this->_log("Zend_Cache_Backend_ZendPlatform::save() : non false specifc lifetime is unsuported for this backend");
}
$lifetime = $this->_directives['lifetime'];
$result1 = output_cache_put($id, array($data, time()));
$result2 = (count($tags) == 0);
foreach ($tags as $tag) {
$tagid = self::TAGS_PREFIX.$tag;
$old_tags = output_cache_get($tagid, $lifetime);
if ($old_tags === false) {
$old_tags = array();
}
$old_tags[$id] = $id;
output_cache_remove_key($tagid);
$result2 = output_cache_put($tagid, $old_tags);
}
return $result1 && $result2;
}
/**
* Remove a cache record
*
* @param string $id Cache id
* @return boolean True if no problem
*/
public function remove($id)
{
return output_cache_remove_key($id);
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
case Zend_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 Zend_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 Zend_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 Zend_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:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
/**
* Clean a directory and recursivly go over it's subdirectories
*
* Remove all the cached files that need to be cleaned (according to mode and files mtime)
*
* @param string $dir Path of directory ot clean
* @param string $mode The same parameter as in Zend_Cache_Backend_ZendPlatform::clean()
* @return boolean True if ok
*/
private function _clean($dir, $mode)
{
$d = @dir($dir);
if (!$d) {
return false;
}
$result = true;
while (false !== ($file = $d->read())) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $d->path . $file;
if (is_dir($file)) {
$result = ($this->_clean($file .'/', $mode)) && ($result);
} else {
if ($mode == Zend_Cache::CLEANING_MODE_ALL) {
$result = ($this->_remove($file)) && ($result);
} else if ($mode == Zend_Cache::CLEANING_MODE_OLD) {
// Files older than lifetime get deleted from cache
if ($this->_directives['lifetime'] !== null) {
if ((time() - @filemtime($file)) > $this->_directives['lifetime']) {
$result = ($this->_remove($file)) && ($result);
}
}
}
}
}
$d->close();
return $result;
}
/**
* Remove a file
*
* If we can't remove the file (because of locks or any problem), we will touch
* the file to invalidate it
*
* @param string $file Complete file path
* @return boolean True if ok
*/
private function _remove($file)
{
if (!@unlink($file)) {
# If we can't remove the file (because of locks or any problem), we will touch
# the file to invalidate it
$this->_log("Zend_Cache_Backend_ZendPlatform::_remove() : we can't remove $file => we are going to try to invalidate it");
if ($this->_directives['lifetime'] === null) {
return false;
}
if (!file_exists($file)) {
return false;
}
return @touch($file, time() - 2*abs($this->_directives['lifetime']));
}
return true;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Cache_Backend_Interface */
#require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend */
#require_once 'Zend/Cache/Backend.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Cache_Backend_ZendServer extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
/**
* Available options
*
* =====> (string) namespace :
* Namespace to be used for chaching operations
*
* @var array available options
*/
protected $_options = array(
'namespace' => 'zendframework'
);
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @throws Zend_Cache_Exception
*/
abstract protected function _store($data, $id, $timeToLive);
/**
* Fetch data
*
* @param string $id Cache id
* @throws Zend_Cache_Exception
*/
abstract protected function _fetch($id);
/**
* Unset data
*
* @param string $id Cache id
*/
abstract protected function _unset($id);
/**
* Clear cache
*/
abstract protected function _clear();
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id cache id
* @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested
* @return string cached datas (or false)
*/
public function load($id, $doNotTestCacheValidity = false)
{
$tmp = $this->_fetch($id);
if ($tmp !== null) {
return $tmp;
}
return false;
}
/**
* Test if a cache is available or not (for the given id)
*
* @param string $id cache id
* @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record
* @throws Zend_Cache_Exception
*/
public function test($id)
{
$tmp = $this->_fetch('internal-metadatas---' . $id);
if ($tmp !== false) {
if (!is_array($tmp) || !isset($tmp['mtime'])) {
Zend_Cache::throwException('Cache metadata for \'' . $id . '\' id is corrupted' );
}
return $tmp['mtime'];
}
return false;
}
/**
* Compute & return the expire time
*
* @return int expire time (unix timestamp)
*/
private function _expireTime($lifetime)
{
if ($lifetime === null) {
return 9999999999;
}
return time() + $lifetime;
}
/**
* Save some string datas into a cache record
*
* Note : $data is always "string" (serialization is done by the
* core not by the backend)
*
* @param string $data datas to cache
* @param string $id cache id
* @param array $tags array of strings, the cache record will be tagged by each string entry
* @param int $specificLifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @return boolean true if no problem
*/
public function save($data, $id, $tags = array(), $specificLifetime = false)
{
$lifetime = $this->getLifetime($specificLifetime);
$metadatas = array(
'mtime' => time(),
'expire' => $this->_expireTime($lifetime),
);
if (count($tags) > 0) {
$this->_log('Zend_Cache_Backend_ZendServer::save() : tags are unsupported by the ZendServer backends');
}
return $this->_store($data, $id, $lifetime) &&
$this->_store($metadatas, 'internal-metadatas---' . $id, $lifetime);
}
/**
* Remove a cache record
*
* @param string $id cache id
* @return boolean true if no problem
*/
public function remove($id)
{
$result1 = $this->_unset($id);
$result2 = $this->_unset('internal-metadatas---' . $id);
return $result1 && $result2;
}
/**
* 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 = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
{
switch ($mode) {
case Zend_Cache::CLEANING_MODE_ALL:
$this->_clear();
return true;
break;
case Zend_Cache::CLEANING_MODE_OLD:
$this->_log("Zend_Cache_Backend_ZendServer::clean() : CLEANING_MODE_OLD is unsupported by the Zend Server backends.");
break;
case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
$this->_clear();
$this->_log('Zend_Cache_Backend_ZendServer::clean() : tags are unsupported by the Zend Server backends.');
break;
default:
Zend_Cache::throwException('Invalid mode for clean() method');
break;
}
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Cache_Backend_Interface */
#require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend_ZendServer */
#require_once 'Zend/Cache/Backend/ZendServer.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendServer_Disk extends Zend_Cache_Backend_ZendServer implements Zend_Cache_Backend_Interface
{
/**
* 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')) {
Zend_Cache::throwException('Zend_Cache_ZendServer_Disk backend has to be used within Zend Server environment.');
}
parent::__construct($options);
}
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @return boolean true if no problem
*/
protected function _store($data, $id, $timeToLive)
{
if (zend_disk_cache_store($this->_options['namespace'] . '::' . $id,
$data,
$timeToLive) === false) {
$this->_log('Store operation failed.');
return false;
}
return true;
}
/**
* Fetch data
*
* @param string $id Cache id
* @return mixed|null
*/
protected function _fetch($id)
{
return zend_disk_cache_fetch($this->_options['namespace'] . '::' . $id);
}
/**
* Unset data
*
* @param string $id Cache id
* @return boolean true if no problem
*/
protected function _unset($id)
{
return zend_disk_cache_delete($this->_options['namespace'] . '::' . $id);
}
/**
* Clear cache
*/
protected function _clear()
{
zend_disk_cache_clear($this->_options['namespace']);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Cache_Backend_Interface */
#require_once 'Zend/Cache/Backend/Interface.php';
/** @see Zend_Cache_Backend_ZendServer */
#require_once 'Zend/Cache/Backend/ZendServer.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Backend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Backend_ZendServer_ShMem extends Zend_Cache_Backend_ZendServer implements Zend_Cache_Backend_Interface
{
/**
* Constructor
*
* @param array $options associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
if (!function_exists('zend_shm_cache_store')) {
Zend_Cache::throwException('Zend_Cache_ZendServer_ShMem backend has to be used within Zend Server environment.');
}
parent::__construct($options);
}
/**
* Store data
*
* @param mixed $data Object to store
* @param string $id Cache id
* @param int $timeToLive Time to live in seconds
* @return bool
*/
protected function _store($data, $id, $timeToLive)
{
if (zend_shm_cache_store($this->_options['namespace'] . '::' . $id,
$data,
$timeToLive) === false) {
$this->_log('Store operation failed.');
return false;
}
return true;
}
/**
* Fetch data
*
* @param string $id Cache id
* @return mixed|null
*/
protected function _fetch($id)
{
return zend_shm_cache_fetch($this->_options['namespace'] . '::' . $id);
}
/**
* Unset data
*
* @param string $id Cache id
* @return boolean true if no problem
*/
protected function _unset($id)
{
return zend_shm_cache_delete($this->_options['namespace'] . '::' . $id);
}
/**
* Clear cache
*/
protected function _clear()
{
zend_shm_cache_clear($this->_options['namespace']);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Core
{
/**
* Messages
*/
const BACKEND_NOT_SUPPORTS_TAG = 'tags are not supported by the current backend';
const BACKEND_NOT_IMPLEMENTS_EXTENDED_IF = 'Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available';
/**
* Backend Object
*
* @var Zend_Cache_Backend_Interface $_backend
*/
protected $_backend = null;
/**
* Available options
*
* ====> (boolean) write_control :
* - Enable / disable write control (the cache is read just after writing to detect corrupt entries)
* - Enable write control will lightly slow the cache writing but not the cache reading
* Write control can detect some corrupt cache files but maybe it's not a perfect control
*
* ====> (boolean) caching :
* - Enable / disable caching
* (can be very useful for the debug of cached scripts)
*
* =====> (string) cache_id_prefix :
* - prefix for cache ids (namespace)
*
* ====> (boolean) automatic_serialization :
* - Enable / disable automatic serialization
* - It can be used to save directly datas which aren't strings (but it's slower)
*
* ====> (int) automatic_cleaning_factor :
* - Disable / Tune the automatic cleaning process
* - The automatic cleaning process destroy too old (for the given life time)
* cache files when a new cache file is written :
* 0 => no automatic cache cleaning
* 1 => systematic cache cleaning
* x (integer) > 1 => automatic cleaning randomly 1 times on x cache write
*
* ====> (int) lifetime :
* - Cache lifetime (in seconds)
* - If null, the cache is valid forever.
*
* ====> (boolean) logging :
* - If set to true, logging is activated (but the system is slower)
*
* ====> (boolean) ignore_user_abort
* - If set to true, the core will set the ignore_user_abort PHP flag inside the
* save() method to avoid cache corruptions in some cases (default false)
*
* @var array $_options available options
*/
protected $_options = array(
'write_control' => true,
'caching' => true,
'cache_id_prefix' => null,
'automatic_serialization' => false,
'automatic_cleaning_factor' => 10,
'lifetime' => 3600,
'logging' => false,
'logger' => null,
'ignore_user_abort' => false
);
/**
* Array of options which have to be transfered to backend
*
* @var array $_directivesList
*/
protected static $_directivesList = array('lifetime', 'logging', 'logger');
/**
* Not used for the core, just a sort a hint to get a common setOption() method (for the core and for frontends)
*
* @var array $_specificOptions
*/
protected $_specificOptions = array();
/**
* Last used cache id
*
* @var string $_lastId
*/
private $_lastId = null;
/**
* True if the backend implements Zend_Cache_Backend_ExtendedInterface
*
* @var boolean $_extendedBackend
*/
protected $_extendedBackend = false;
/**
* Array of capabilities of the backend (only if it implements Zend_Cache_Backend_ExtendedInterface)
*
* @var array
*/
protected $_backendCapabilities = array();
/**
* Constructor
*
* @param array|Zend_Config $options Associative array of options or Zend_Config instance
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct($options = array())
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (!is_array($options)) {
Zend_Cache::throwException("Options passed were not an array"
. " or Zend_Config instance.");
}
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
$this->_loggerSanity();
}
/**
* Set options using an instance of type Zend_Config
*
* @param Zend_Config $config
* @return Zend_Cache_Core
*/
public function setConfig(Zend_Config $config)
{
$options = $config->toArray();
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
return $this;
}
/**
* Set the backend
*
* @param Zend_Cache_Backend $backendObject
* @throws Zend_Cache_Exception
* @return void
*/
public function setBackend(Zend_Cache_Backend $backendObject)
{
$this->_backend= $backendObject;
// some options (listed in $_directivesList) have to be given
// to the backend too (even if they are not "backend specific")
$directives = array();
foreach (Zend_Cache_Core::$_directivesList as $directive) {
$directives[$directive] = $this->_options[$directive];
}
$this->_backend->setDirectives($directives);
if (in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_backend))) {
$this->_extendedBackend = true;
$this->_backendCapabilities = $this->_backend->getCapabilities();
}
}
/**
* Returns the backend
*
* @return Zend_Cache_Backend backend object
*/
public function getBackend()
{
return $this->_backend;
}
/**
* Public frontend to set an option
*
* There is an additional validation (relatively to the protected _setOption method)
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if (!is_string($name)) {
Zend_Cache::throwException("Incorrect option name!");
}
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
// This is a Core option
$this->_setOption($name, $value);
return;
}
if (array_key_exists($name, $this->_specificOptions)) {
// This a specic option of this frontend
$this->_specificOptions[$name] = $value;
return;
}
}
/**
* Public frontend to get an option value
*
* @param string $name Name of the option
* @throws Zend_Cache_Exception
* @return mixed option value
*/
public function getOption($name)
{
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
// This is a Core option
return $this->_options[$name];
}
if (array_key_exists($name, $this->_specificOptions)) {
// This a specic option of this frontend
return $this->_specificOptions[$name];
}
Zend_Cache::throwException("Incorrect option name : $name");
}
/**
* Set an option
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
private function _setOption($name, $value)
{
if (!is_string($name) || !array_key_exists($name, $this->_options)) {
Zend_Cache::throwException("Incorrect option name : $name");
}
if ($name == 'lifetime' && empty($value)) {
$value = null;
}
$this->_options[$name] = $value;
}
/**
* Force a new lifetime
*
* The new value is set for the core/frontend but for the backend too (directive)
*
* @param int $newLifetime New lifetime (in seconds)
* @return void
*/
public function setLifetime($newLifetime)
{
$this->_options['lifetime'] = $newLifetime;
$this->_backend->setDirectives(array(
'lifetime' => $newLifetime
));
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @param boolean $doNotUnserialize Do not serialize (even if automatic_serialization is true) => for internal use
* @return mixed|false Cached datas
*/
public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
{
if (!$this->_options['caching']) {
return false;
}
$id = $this->_id($id); // cache id may need prefix
$this->_lastId = $id;
$this->_validateIdOrTag($id);
$this->_log("Zend_Cache_Core: load item '{$id}'", 7);
$data = $this->_backend->load($id, $doNotTestCacheValidity);
if ($data===false) {
// no cache available
return false;
}
if ((!$doNotUnserialize) && $this->_options['automatic_serialization']) {
// we need to unserialize before sending the result
return unserialize($data);
}
return $data;
}
/**
* Test if a cache is available for the given id
*
* @param string $id Cache id
* @return int|false Last modified time of cache entry if it is available, false otherwise
*/
public function test($id)
{
if (!$this->_options['caching']) {
return false;
}
$id = $this->_id($id); // cache id may need prefix
$this->_validateIdOrTag($id);
$this->_lastId = $id;
$this->_log("Zend_Cache_Core: test item '{$id}'", 7);
return $this->_backend->test($id);
}
/**
* Save some data in a cache
*
* @param mixed $data Data to put in cache (can be another type than string if automatic_serialization is on)
* @param string $id Cache id (if not set, the last cache id will be used)
* @param array $tags Cache tags
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @throws Zend_Cache_Exception
* @return boolean True if no problem
*/
public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8)
{
if (!$this->_options['caching']) {
return true;
}
if ($id === null) {
$id = $this->_lastId;
} else {
$id = $this->_id($id);
}
$this->_validateIdOrTag($id);
$this->_validateTagsArray($tags);
if ($this->_options['automatic_serialization']) {
// we need to serialize datas before storing them
$data = serialize($data);
} else {
if (!is_string($data)) {
Zend_Cache::throwException("Datas must be string or set automatic_serialization = true");
}
}
// automatic cleaning
if ($this->_options['automatic_cleaning_factor'] > 0) {
$rand = rand(1, $this->_options['automatic_cleaning_factor']);
if ($rand==1) {
// new way || deprecated way
if ($this->_extendedBackend || method_exists($this->_backend, 'isAutomaticCleaningAvailable')) {
$this->_log("Zend_Cache_Core::save(): automatic cleaning running", 7);
$this->clean(Zend_Cache::CLEANING_MODE_OLD);
} else {
$this->_log("Zend_Cache_Core::save(): automatic cleaning is not available/necessary with current backend", 4);
}
}
}
$this->_log("Zend_Cache_Core: save item '{$id}'", 7);
if ($this->_options['ignore_user_abort']) {
$abort = ignore_user_abort(true);
}
if (($this->_extendedBackend) && ($this->_backendCapabilities['priority'])) {
$result = $this->_backend->save($data, $id, $tags, $specificLifetime, $priority);
} else {
$result = $this->_backend->save($data, $id, $tags, $specificLifetime);
}
if ($this->_options['ignore_user_abort']) {
ignore_user_abort($abort);
}
if (!$result) {
// maybe the cache is corrupted, so we remove it !
$this->_log("Zend_Cache_Core::save(): failed to save item '{$id}' -> removing it", 4);
$this->_backend->remove($id);
return false;
}
if ($this->_options['write_control']) {
$data2 = $this->_backend->load($id, true);
if ($data!=$data2) {
$this->_log("Zend_Cache_Core::save(): write control of item '{$id}' failed -> removing it", 4);
$this->_backend->remove($id);
return false;
}
}
return true;
}
/**
* Remove a cache
*
* @param string $id Cache id to remove
* @return boolean True if ok
*/
public function remove($id)
{
if (!$this->_options['caching']) {
return true;
}
$id = $this->_id($id); // cache id may need prefix
$this->_validateIdOrTag($id);
$this->_log("Zend_Cache_Core: remove item '{$id}'", 7);
return $this->_backend->remove($id);
}
/**
* Clean cache entries
*
* Available modes are :
* 'all' (default) => remove all cache entries ($tags is not used)
* 'old' => remove too old cache entries ($tags is not used)
* 'matchingTag' => remove cache entries matching all given tags
* ($tags can be an array of strings or a single string)
* 'notMatchingTag' => remove cache entries not matching one of the given tags
* ($tags can be an array of strings or a single string)
* 'matchingAnyTag' => remove cache entries matching any given tags
* ($tags can be an array of strings or a single string)
*
* @param string $mode
* @param array|string $tags
* @throws Zend_Cache_Exception
* @return boolean True if ok
*/
public function clean($mode = 'all', $tags = array())
{
if (!$this->_options['caching']) {
return true;
}
if (!in_array($mode, array(Zend_Cache::CLEANING_MODE_ALL,
Zend_Cache::CLEANING_MODE_OLD,
Zend_Cache::CLEANING_MODE_MATCHING_TAG,
Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG))) {
Zend_Cache::throwException('Invalid cleaning mode');
}
$this->_validateTagsArray($tags);
return $this->_backend->clean($mode, $tags);
}
/**
* Return an array of stored cache ids which match given tags
*
* In case of multiple tags, a logical AND is made between tags
*
* @param array $tags array of tags
* @return array array of matching cache ids (string)
*/
public function getIdsMatchingTags($tags = array())
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
$ids = $this->_backend->getIdsMatchingTags($tags);
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored cache ids which don't match given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of not matching cache ids (string)
*/
public function getIdsNotMatchingTags($tags = array())
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
$ids = $this->_backend->getIdsNotMatchingTags($tags);
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored cache ids which match any given tags
*
* In case of multiple tags, a logical OR is made between tags
*
* @param array $tags array of tags
* @return array array of matching any cache ids (string)
*/
public function getIdsMatchingAnyTags($tags = array())
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
$ids = $this->_backend->getIdsMatchingAnyTags($tags);
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored cache ids
*
* @return array array of stored cache ids (string)
*/
public function getIds()
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
$ids = $this->_backend->getIds();
// we need to remove cache_id_prefix from ids (see #ZF-6178, #ZF-7600)
if (isset($this->_options['cache_id_prefix']) && $this->_options['cache_id_prefix'] !== '') {
$prefix = & $this->_options['cache_id_prefix'];
$prefixLen = strlen($prefix);
foreach ($ids as &$id) {
if (strpos($id, $prefix) === 0) {
$id = substr($id, $prefixLen);
}
}
}
return $ids;
}
/**
* Return an array of stored tags
*
* @return array array of stored tags (string)
*/
public function getTags()
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
if (!($this->_backendCapabilities['tags'])) {
Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG);
}
return $this->_backend->getTags();
}
/**
* Return the filling percentage of the backend storage
*
* @return int integer between 0 and 100
*/
public function getFillingPercentage()
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
return $this->_backend->getFillingPercentage();
}
/**
* Return an array of metadatas for the given cache id
*
* The array will include these keys :
* - expire : the expire timestamp
* - tags : a string array of tags
* - mtime : timestamp of last modification time
*
* @param string $id cache id
* @return array array of metadatas (false if the cache id is not found)
*/
public function getMetadatas($id)
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
$id = $this->_id($id); // cache id may need prefix
return $this->_backend->getMetadatas($id);
}
/**
* Give (if possible) an extra lifetime to the given cache id
*
* @param string $id cache id
* @param int $extraLifetime
* @return boolean true if ok
*/
public function touch($id, $extraLifetime)
{
if (!$this->_extendedBackend) {
Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF);
}
$id = $this->_id($id); // cache id may need prefix
$this->_log("Zend_Cache_Core: touch item '{$id}'", 7);
return $this->_backend->touch($id, $extraLifetime);
}
/**
* 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
*/
protected function _validateIdOrTag($string)
{
if (!is_string($string)) {
Zend_Cache::throwException('Invalid id or tag : must be a string');
}
if (substr($string, 0, 9) == 'internal-') {
Zend_Cache::throwException('"internal-*" ids or tags are reserved');
}
if (!preg_match('~^[a-zA-Z0-9_]+$~D', $string)) {
Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]");
}
}
/**
* Validate a tags array (security, reliable filenames, reserved prefixes...)
*
* Throw an exception if a problem is found
*
* @param array $tags Array of tags
* @throws Zend_Cache_Exception
* @return void
*/
protected function _validateTagsArray($tags)
{
if (!is_array($tags)) {
Zend_Cache::throwException('Invalid tags array : must be an array');
}
foreach($tags as $tag) {
$this->_validateIdOrTag($tag);
}
reset($tags);
}
/**
* Make sure if we enable logging that the Zend_Log class
* is available.
* Create a default log object if none is set.
*
* @throws Zend_Cache_Exception
* @return void
*/
protected function _loggerSanity()
{
if (!isset($this->_options['logging']) || !$this->_options['logging']) {
return;
}
if (isset($this->_options['logger']) && $this->_options['logger'] instanceof Zend_Log) {
return;
}
// Create a default logger to the standard output stream
#require_once 'Zend/Log.php';
#require_once 'Zend/Log/Writer/Stream.php';
#require_once 'Zend/Log/Filter/Priority.php';
$logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output'));
$logger->addFilter(new Zend_Log_Filter_Priority(Zend_Log::WARN, '<='));
$this->_options['logger'] = $logger;
}
/**
* 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 Zend_Log)) {
Zend_Cache::throwException('Logging is enabled but logger is not set');
}
$logger = $this->_options['logger'];
$logger->log($message, $priority);
}
/**
* Make and return a cache id
*
* Checks 'cache_id_prefix' and returns new id with prefix or simply the id if null
*
* @param string $id Cache id
* @return string Cache id (with or without prefix)
*/
protected function _id($id)
{
if (($id !== null) && isset($this->_options['cache_id_prefix'])) {
return $this->_options['cache_id_prefix'] . $id; // return with prefix
}
return $id; // no prefix, just return the $id passed
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Exception
*/
#require_once 'Zend/Exception.php';
/**
* @package Zend_Cache
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Exception extends Zend_Exception {}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Core
*/
#require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Capture extends Zend_Cache_Core
{
/**
* Page identifiers
* @var array
*/
protected $_idStack = array();
/**
* Tags
* @var array
*/
protected $_tags = array();
protected $_extension = null;
/**
* Start the cache
*
* @param string $id Cache id
* @return mixed True if the cache is hit (false else) with $echoData=true (default) ; string else (datas)
*/
public function start($id, array $tags, $extension = null)
{
$this->_tags = $tags;
$this->_extension = $extension;
ob_start(array($this, '_flush'));
ob_implicit_flush(false);
$this->_idStack[] = $id;
return false;
}
/**
* 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 ($id === null) {
Zend_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;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Core
*/
#require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Class extends Zend_Cache_Core
{
/**
* Available options
*
* ====> (mixed) cached_entity :
* - if set to a class name, we will cache an abstract class and will use only static calls
* - if set to an object, we will cache this object methods
*
* ====> (boolean) cache_by_default :
* - if true, method calls will be cached by default
*
* ====> (array) cached_methods :
* - an array of method names which will be cached (even if cache_by_default = false)
*
* ====> (array) non_cached_methods :
* - an array of method names which won't be cached (even if cache_by_default = true)
*
* @var array available options
*/
protected $_specificOptions = array(
'cached_entity' => null,
'cache_by_default' => true,
'cached_methods' => array(),
'non_cached_methods' => array()
);
/**
* Tags array
*
* @var array
*/
protected $_tags = array();
/**
* SpecificLifetime value
*
* false => no specific life time
*
* @var bool|int
*/
protected $_specificLifetime = false;
/**
* The cached object or the name of the cached abstract class
*
* @var mixed
*/
protected $_cachedEntity = null;
/**
* The class name of the cached object or cached abstract class
*
* Used to differentiate between different classes with the same method calls.
*
* @var string
*/
protected $_cachedEntityLabel = '';
/**
* Priority (used by some particular backends)
*
* @var int
*/
protected $_priority = 8;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
*/
public function __construct(array $options = array())
{
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
if ($this->_specificOptions['cached_entity'] === null) {
Zend_Cache::throwException('cached_entity must be set !');
}
$this->setCachedEntity($this->_specificOptions['cached_entity']);
$this->setOption('automatic_serialization', true);
}
/**
* Set a specific life time
*
* @param bool|int $specificLifetime
* @return void
*/
public function setSpecificLifetime($specificLifetime = false)
{
$this->_specificLifetime = $specificLifetime;
}
/**
* Set the priority (used by some particular backends)
*
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority)
*/
public function setPriority($priority)
{
$this->_priority = $priority;
}
/**
* Public frontend to set an option
*
* Just a wrapper to get a specific behaviour for cached_entity
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if ($name == 'cached_entity') {
$this->setCachedEntity($value);
} else {
parent::setOption($name, $value);
}
}
/**
* Specific method to set the cachedEntity
*
* if set to a class name, we will cache an abstract class and will use only static calls
* if set to an object, we will cache this object methods
*
* @param mixed $cachedEntity
*/
public function setCachedEntity($cachedEntity)
{
if (!is_string($cachedEntity) && !is_object($cachedEntity)) {
Zend_Cache::throwException(
'cached_entity must be an object or a class name'
);
}
$this->_cachedEntity = $cachedEntity;
$this->_specificOptions['cached_entity'] = $cachedEntity;
if (is_string($this->_cachedEntity)) {
$this->_cachedEntityLabel = $this->_cachedEntity;
} else {
$ro = new ReflectionObject($this->_cachedEntity);
$this->_cachedEntityLabel = $ro->getName();
}
}
/**
* Set the cache array
*
* @param array $tags
* @return void
*/
public function setTagsArray($tags = array())
{
$this->_tags = $tags;
}
/**
* Main method : call the specified method or get the result from cache
*
* @param string $name Method name
* @param array $parameters Method parameters
* @return mixed Result
* @throws Exception
*/
public function __call($name, $parameters)
{
$callback = array($this->_cachedEntity, $name);
if (!is_callable($callback, false)) {
Zend_Cache::throwException('Invalid callback');
}
$cacheBool1 = $this->_specificOptions['cache_by_default'];
$cacheBool2 = in_array($name, $this->_specificOptions['cached_methods']);
$cacheBool3 = in_array($name, $this->_specificOptions['non_cached_methods']);
$cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
if (!$cache) {
// We do not have not cache
return call_user_func_array($callback, $parameters);
}
$id = $this->makeId($name, $parameters);
if (($rs = $this->load($id)) && (array_key_exists(0, $rs))
&& (array_key_exists(1, $rs))
) {
// A cache is available
$output = $rs[0];
$return = $rs[1];
} else {
// A cache is not available (or not valid for this frontend)
ob_start();
ob_implicit_flush(false);
try {
$return = call_user_func_array($callback, $parameters);
$output = ob_get_clean();
$data = array($output, $return);
$this->save(
$data, $id, $this->_tags, $this->_specificLifetime,
$this->_priority
);
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
}
echo $output;
return $return;
}
/**
* ZF-9970
*
* @deprecated
*/
private function _makeId($name, $args)
{
return $this->makeId($name, $args);
}
/**
* Make a cache id from the method name and parameters
*
* @param string $name Method name
* @param array $args Method parameters
* @return string Cache id
*/
public function makeId($name, array $args = array())
{
return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($args));
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Core
*/
#require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_File extends Zend_Cache_Core
{
/**
* Consts for master_files_mode
*/
const MODE_AND = 'AND';
const MODE_OR = 'OR';
/**
* Available options
*
* ====> (string) master_file :
* - a complete path of the master file
* - deprecated (see master_files)
*
* ====> (array) master_files :
* - an array of complete path of master files
* - this option has to be set !
*
* ====> (string) master_files_mode :
* - Zend_Cache_Frontend_File::MODE_AND or Zend_Cache_Frontend_File::MODE_OR
* - if MODE_AND, then all master files have to be touched to get a cache invalidation
* - if MODE_OR (default), then a single touched master file is enough to get a cache invalidation
*
* ====> (boolean) ignore_missing_master_files
* - if set to true, missing master files are ignored silently
* - if set to false (default), an exception is thrown if there is a missing master file
* @var array available options
*/
protected $_specificOptions = array(
'master_file' => null,
'master_files' => null,
'master_files_mode' => 'OR',
'ignore_missing_master_files' => false
);
/**
* Master file mtimes
*
* Array of int
*
* @var array
*/
private $_masterFile_mtimes = null;
/**
* Constructor
*
* @param array $options Associative array of options
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
if (!isset($this->_specificOptions['master_files'])) {
Zend_Cache::throwException('master_files option must be set');
}
}
/**
* Change the master_files option
*
* @param array $masterFiles the complete paths and name of the master files
*/
public function setMasterFiles(array $masterFiles)
{
$this->_specificOptions['master_file'] = null; // to keep a compatibility
$this->_specificOptions['master_files'] = null;
$this->_masterFile_mtimes = array();
clearstatcache();
$i = 0;
foreach ($masterFiles as $masterFile) {
if (file_exists($masterFile)) {
$mtime = filemtime($masterFile);
} else {
$mtime = false;
}
if (!$this->_specificOptions['ignore_missing_master_files'] && !$mtime) {
Zend_Cache::throwException('Unable to read master_file : ' . $masterFile);
}
$this->_masterFile_mtimes[$i] = $mtime;
$this->_specificOptions['master_files'][$i] = $masterFile;
if ($i === 0) { // to keep a compatibility
$this->_specificOptions['master_file'] = $masterFile;
}
$i++;
}
}
/**
* Change the master_file option
*
* To keep the compatibility
*
* @deprecated
* @param string $masterFile the complete path and name of the master file
*/
public function setMasterFile($masterFile)
{
$this->setMasterFiles(array($masterFile));
}
/**
* Public frontend to set an option
*
* Just a wrapper to get a specific behaviour for master_file
*
* @param string $name Name of the option
* @param mixed $value Value of the option
* @throws Zend_Cache_Exception
* @return void
*/
public function setOption($name, $value)
{
if ($name == 'master_file') {
$this->setMasterFile($value);
} else if ($name == 'master_files') {
$this->setMasterFiles($value);
} else {
parent::setOption($name, $value);
}
}
/**
* Test if a cache is available for the given id and (if yes) return it (false else)
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @param boolean $doNotUnserialize Do not serialize (even if automatic_serialization is true) => for internal use
* @return mixed|false Cached datas
*/
public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false)
{
if (!$doNotTestCacheValidity) {
if ($this->test($id)) {
return parent::load($id, true, $doNotUnserialize);
}
return false;
}
return parent::load($id, true, $doNotUnserialize);
}
/**
* Test if a cache is available for the given id
*
* @param string $id Cache id
* @return int|false Last modified time of cache entry if it is available, false otherwise
*/
public function test($id)
{
$lastModified = parent::test($id);
if ($lastModified) {
if ($this->_specificOptions['master_files_mode'] == self::MODE_AND) {
// MODE_AND
foreach($this->_masterFile_mtimes as $masterFileMTime) {
if ($masterFileMTime) {
if ($lastModified > $masterFileMTime) {
return $lastModified;
}
}
}
} else {
// MODE_OR
$res = true;
foreach($this->_masterFile_mtimes as $masterFileMTime) {
if ($masterFileMTime) {
if ($lastModified <= $masterFileMTime) {
return false;
}
}
}
return $lastModified;
}
}
return false;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Core
*/
#require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Function extends Zend_Cache_Core
{
/**
* This frontend specific options
*
* ====> (boolean) cache_by_default :
* - if true, function calls will be cached by default
*
* ====> (array) cached_functions :
* - an array of function names which will be cached (even if cache_by_default = false)
*
* ====> (array) non_cached_functions :
* - an array of function names which won't be cached (even if cache_by_default = true)
*
* @var array options
*/
protected $_specificOptions = array(
'cache_by_default' => true,
'cached_functions' => array(),
'non_cached_functions' => array()
);
/**
* Constructor
*
* @param array $options Associative array of options
* @return void
*/
public function __construct(array $options = array())
{
foreach ($options as $name => $value) {
$this->setOption($name, $value);
}
$this->setOption('automatic_serialization', true);
}
/**
* Main method : call the specified function or get the result from cache
*
* @param callback $callback A valid callback
* @param array $parameters Function parameters
* @param array $tags Cache tags
* @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
* @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
* @return mixed Result
*/
public function call($callback, array $parameters = array(), $tags = array(), $specificLifetime = false, $priority = 8)
{
if (!is_callable($callback, true, $name)) {
Zend_Cache::throwException('Invalid callback');
}
$cacheBool1 = $this->_specificOptions['cache_by_default'];
$cacheBool2 = in_array($name, $this->_specificOptions['cached_functions']);
$cacheBool3 = in_array($name, $this->_specificOptions['non_cached_functions']);
$cache = (($cacheBool1 || $cacheBool2) && (!$cacheBool3));
if (!$cache) {
// Caching of this callback is disabled
return call_user_func_array($callback, $parameters);
}
$id = $this->_makeId($callback, $parameters);
if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) {
// A cache is available
$output = $rs[0];
$return = $rs[1];
} else {
// A cache is not available (or not valid for this frontend)
ob_start();
ob_implicit_flush(false);
$return = call_user_func_array($callback, $parameters);
$output = ob_get_clean();
$data = array($output, $return);
$this->save($data, $id, $tags, $specificLifetime, $priority);
}
echo $output;
return $return;
}
/**
* ZF-9970
*
* @deprecated
*/
private function _makeId($callback, array $args)
{
return $this->makeId($callback, $args);
}
/**
* 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)) {
Zend_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) {
Zend_Cache::throwException($e->getMessage());
}
if (!$tmp) {
$lastErr = error_get_last();
Zend_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) {
Zend_Cache::throwException($e->getMessage());
}
if (!$argsStr) {
$lastErr = error_get_last();
throw Zend_Cache::throwException("Can't serialize arguments to generate id: {$lastErr['message']}");
}
}
return md5($name . $argsStr);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Core
*/
#require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Output extends Zend_Cache_Core
{
private $_idStack = array();
/**
* Constructor
*
* @param array $options Associative array of options
* @return void
*/
public function __construct(array $options = array())
{
parent::__construct($options);
$this->_idStack = array();
}
/**
* Start the cache
*
* @param string $id Cache id
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @param boolean $echoData If set to true, datas are sent to the browser if the cache is hit (simply returned else)
* @return mixed True if the cache is hit (false else) with $echoData=true (default) ; string else (datas)
*/
public function start($id, $doNotTestCacheValidity = false, $echoData = true)
{
$data = $this->load($id, $doNotTestCacheValidity);
if ($data !== false) {
if ( $echoData ) {
echo($data);
return true;
} else {
return $data;
}
}
ob_start();
ob_implicit_flush(false);
$this->_idStack[] = $id;
return false;
}
/**
* 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_clean();
} else {
$data =& $forcedDatas;
}
$id = array_pop($this->_idStack);
if ($id === null) {
Zend_Cache::throwException('use of end() without a start()');
}
$this->save($data, $id, $tags, $specificLifetime, $priority);
if ($echoData) {
echo($data);
}
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Cache_Core
*/
#require_once 'Zend/Cache/Core.php';
/**
* @package Zend_Cache
* @subpackage Zend_Cache_Frontend
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Frontend_Page extends Zend_Cache_Core
{
/**
* This frontend specific options
*
* ====> (boolean) http_conditional :
* - if true, http conditional mode is on
* WARNING : http_conditional OPTION IS NOT IMPLEMENTED FOR THE MOMENT (TODO)
*
* ====> (boolean) debug_header :
* - if true, a debug text is added before each cached pages
*
* ====> (boolean) content_type_memorization :
* - deprecated => use memorize_headers instead
* - if the Content-Type header is sent after the cache was started, the
* corresponding value can be memorized and replayed when the cache is hit
* (if false (default), the frontend doesn't take care of Content-Type header)
*
* ====> (array) memorize_headers :
* - an array of strings corresponding to some HTTP headers name. Listed headers
* will be stored with cache datas and "replayed" when the cache is hit
*
* ====> (array) default_options :
* - an associative array of default options :
* - (boolean) cache : cache is on by default if true
* - (boolean) cacheWithXXXVariables (XXXX = 'Get', 'Post', 'Session', 'Files' or 'Cookie') :
* if true, cache is still on even if there are some variables in this superglobal array
* if false, cache is off if there are some variables in this superglobal array
* - (boolean) makeIdWithXXXVariables (XXXX = 'Get', 'Post', 'Session', 'Files' or 'Cookie') :
* if true, we have to use the content of this superglobal array to make a cache id
* if false, the cache id won't be dependent of the content of this superglobal array
* - (int) specific_lifetime : cache specific lifetime
* (false => global lifetime is used, null => infinite lifetime,
* integer => this lifetime is used), this "lifetime" is probably only
* usefull when used with "regexps" array
* - (array) tags : array of tags (strings)
* - (int) priority : integer between 0 (very low priority) and 10 (maximum priority) used by
* some particular backends
*
* ====> (array) regexps :
* - an associative array to set options only for some REQUEST_URI
* - keys are (pcre) regexps
* - values are associative array with specific options to set if the regexp matchs on $_SERVER['REQUEST_URI']
* (see default_options for the list of available options)
* - if several regexps match the $_SERVER['REQUEST_URI'], only the last one will be used
*
* @var array options
*/
protected $_specificOptions = array(
'http_conditional' => false,
'debug_header' => false,
'content_type_memorization' => false,
'memorize_headers' => array(),
'default_options' => array(
'cache_with_get_variables' => false,
'cache_with_post_variables' => false,
'cache_with_session_variables' => false,
'cache_with_files_variables' => false,
'cache_with_cookie_variables' => false,
'make_id_with_get_variables' => true,
'make_id_with_post_variables' => true,
'make_id_with_session_variables' => true,
'make_id_with_files_variables' => true,
'make_id_with_cookie_variables' => true,
'cache' => true,
'specific_lifetime' => false,
'tags' => array(),
'priority' => null
),
'regexps' => array()
);
/**
* Internal array to store some options
*
* @var array associative array of options
*/
protected $_activeOptions = array();
/**
* If true, the page won't be cached
*
* @var boolean
*/
protected $_cancel = false;
/**
* Constructor
*
* @param array $options Associative array of options
* @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
* @throws Zend_Cache_Exception
* @return void
*/
public function __construct(array $options = array())
{
foreach ($options as $name => $value) {
$name = strtolower($name);
switch ($name) {
case 'regexps':
$this->_setRegexps($value);
break;
case 'default_options':
$this->_setDefaultOptions($value);
break;
case 'content_type_memorization':
$this->_setContentTypeMemorization($value);
break;
default:
$this->setOption($name, $value);
}
}
if (isset($this->_specificOptions['http_conditional'])) {
if ($this->_specificOptions['http_conditional']) {
Zend_Cache::throwException('http_conditional is not implemented for the moment !');
}
}
$this->setOption('automatic_serialization', true);
}
/**
* Specific setter for the 'default_options' option (with some additional tests)
*
* @param array $options Associative array
* @throws Zend_Cache_Exception
* @return void
*/
protected function _setDefaultOptions($options)
{
if (!is_array($options)) {
Zend_Cache::throwException('default_options must be an array !');
}
foreach ($options as $key=>$value) {
if (!is_string($key)) {
Zend_Cache::throwException("invalid option [$key] !");
}
$key = strtolower($key);
if (isset($this->_specificOptions['default_options'][$key])) {
$this->_specificOptions['default_options'][$key] = $value;
}
}
}
/**
* Set the deprecated contentTypeMemorization option
*
* @param boolean $value value
* @return void
* @deprecated
*/
protected function _setContentTypeMemorization($value)
{
$found = null;
foreach ($this->_specificOptions['memorize_headers'] as $key => $value) {
if (strtolower($value) == 'content-type') {
$found = $key;
}
}
if ($value) {
if (!$found) {
$this->_specificOptions['memorize_headers'][] = 'Content-Type';
}
} else {
if ($found) {
unset($this->_specificOptions['memorize_headers'][$found]);
}
}
}
/**
* Specific setter for the 'regexps' option (with some additional tests)
*
* @param array $options Associative array
* @throws Zend_Cache_Exception
* @return void
*/
protected function _setRegexps($regexps)
{
if (!is_array($regexps)) {
Zend_Cache::throwException('regexps option must be an array !');
}
foreach ($regexps as $regexp=>$conf) {
if (!is_array($conf)) {
Zend_Cache::throwException('regexps option must be an array of arrays !');
}
$validKeys = array_keys($this->_specificOptions['default_options']);
foreach ($conf as $key=>$value) {
if (!is_string($key)) {
Zend_Cache::throwException("unknown option [$key] !");
}
$key = strtolower($key);
if (!in_array($key, $validKeys)) {
unset($regexps[$regexp][$key]);
}
}
}
$this->setOption('regexps', $regexps);
}
/**
* Start the cache
*
* @param string $id (optional) A cache id (if you set a value here, maybe you have to use Output frontend instead)
* @param boolean $doNotDie For unit testing only !
* @return boolean True if the cache is hit (false else)
*/
public function start($id = false, $doNotDie = false)
{
$this->_cancel = false;
$lastMatchingRegexp = null;
if (isset($_SERVER['REQUEST_URI'])) {
foreach ($this->_specificOptions['regexps'] as $regexp => $conf) {
if (preg_match("`$regexp`", $_SERVER['REQUEST_URI'])) {
$lastMatchingRegexp = $regexp;
}
}
}
$this->_activeOptions = $this->_specificOptions['default_options'];
if ($lastMatchingRegexp !== null) {
$conf = $this->_specificOptions['regexps'][$lastMatchingRegexp];
foreach ($conf as $key=>$value) {
$this->_activeOptions[$key] = $value;
}
}
if (!($this->_activeOptions['cache'])) {
return false;
}
if (!$id) {
$id = $this->_makeId();
if (!$id) {
return false;
}
}
$array = $this->load($id);
if ($array !== false) {
$data = $array['data'];
$headers = $array['headers'];
if (!headers_sent()) {
foreach ($headers as $key=>$headerCouple) {
$name = $headerCouple[0];
$value = $headerCouple[1];
header("$name: $value");
}
}
if ($this->_specificOptions['debug_header']) {
echo 'DEBUG HEADER : This is a cached page !';
}
echo $data;
if ($doNotDie) {
return true;
}
die();
}
ob_start(array($this, '_flush'));
ob_implicit_flush(false);
return false;
}
/**
* Cancel the current caching process
*/
public function cancel()
{
$this->_cancel = true;
}
/**
* 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)
{
if ($this->_cancel) {
return $data;
}
$contentType = null;
$storedHeaders = array();
$headersList = headers_list();
foreach($this->_specificOptions['memorize_headers'] as $key=>$headerName) {
foreach ($headersList as $headerSent) {
$tmp = explode(':', $headerSent);
$headerSentName = trim(array_shift($tmp));
if (strtolower($headerName) == strtolower($headerSentName)) {
$headerSentValue = trim(implode(':', $tmp));
$storedHeaders[] = array($headerSentName, $headerSentValue);
}
}
}
$array = array(
'data' => $data,
'headers' => $storedHeaders
);
$this->save($array, null, $this->_activeOptions['tags'], $this->_activeOptions['specific_lifetime'], $this->_activeOptions['priority']);
return $data;
}
/**
* Make an id depending on REQUEST_URI and superglobal arrays (depending on options)
*
* @return mixed|false a cache id (string), false if the cache should have not to be used
*/
protected function _makeId()
{
$tmp = $_SERVER['REQUEST_URI'];
$array = explode('?', $tmp, 2);
$tmp = $array[0];
foreach (array('Get', 'Post', 'Session', 'Files', 'Cookie') as $arrayName) {
$tmp2 = $this->_makePartialId($arrayName, $this->_activeOptions['cache_with_' . strtolower($arrayName) . '_variables'], $this->_activeOptions['make_id_with_' . strtolower($arrayName) . '_variables']);
if ($tmp2===false) {
return false;
}
$tmp = $tmp . $tmp2;
}
return md5($tmp);
}
/**
* Make a partial id depending on options
*
* @param string $arrayName Superglobal array name
* @param bool $bool1 If true, cache is still on even if there are some variables in the superglobal array
* @param bool $bool2 If true, we have to use the content of the superglobal array to make a partial id
* @return mixed|false Partial id (string) or false if the cache should have not to be used
*/
protected function _makePartialId($arrayName, $bool1, $bool2)
{
switch ($arrayName) {
case 'Get':
$var = $_GET;
break;
case 'Post':
$var = $_POST;
break;
case 'Session':
if (isset($_SESSION)) {
$var = $_SESSION;
} else {
$var = null;
}
break;
case 'Cookie':
if (isset($_COOKIE)) {
$var = $_COOKIE;
} else {
$var = null;
}
break;
case 'Files':
$var = $_FILES;
break;
default:
return false;
}
if ($bool1) {
if ($bool2) {
return serialize($var);
}
return '';
}
if (is_array($var) && count($var) > 0) {
return false;
}
return '';
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Cache_Exception */
#require_once 'Zend/Cache/Exception.php';
/** @see Zend_Cache */
#require_once 'Zend/Cache.php';
/**
* @category Zend
* @package Zend_Cache
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Cache_Manager
{
/**
* Constant holding reserved name for default Page Cache
*/
const PAGECACHE = 'page';
/**
* Constant holding reserved name for default Page Tag Cache
*/
const PAGETAGCACHE = 'pagetag';
/**
* Array of caches stored by the Cache Manager instance
*
* @var array
*/
protected $_caches = array();
/**
* Array of ready made configuration templates for lazy
* loading caches.
*
* @var array
*/
protected $_optionTemplates = array(
// Simple Common Default
'default' => array(
'frontend' => array(
'name' => 'Core',
'options' => array(
'automatic_serialization' => true,
),
),
'backend' => array(
'name' => 'File',
'options' => array(
// use system temp dir by default of file backend
// 'cache_dir' => '../cache',
),
),
),
// Static Page HTML Cache
'page' => array(
'frontend' => array(
'name' => 'Capture',
'options' => array(
'ignore_user_abort' => true,
),
),
'backend' => array(
'name' => 'Static',
'options' => array(
'public_dir' => '../public',
),
),
),
// Tag Cache
'pagetag' => array(
'frontend' => array(
'name' => 'Core',
'options' => array(
'automatic_serialization' => true,
'lifetime' => null
),
),
'backend' => array(
'name' => 'File',
'options' => array(
// use system temp dir by default of file backend
// 'cache_dir' => '../cache',
// use default umask of file backend
// 'cache_file_umask' => 0644
),
),
),
);
/**
* Set a new cache for the Cache Manager to contain
*
* @param string $name
* @param Zend_Cache_Core $cache
* @return Zend_Cache_Manager
*/
public function setCache($name, Zend_Cache_Core $cache)
{
$this->_caches[$name] = $cache;
return $this;
}
/**
* Check if the Cache Manager contains the named cache object, or a named
* configuration template to lazy load the cache object
*
* @param string $name
* @return bool
*/
public function hasCache($name)
{
if (isset($this->_caches[$name])
|| $this->hasCacheTemplate($name)
) {
return true;
}
return false;
}
/**
* Fetch the named cache object, or instantiate and return a cache object
* using a named configuration template
*
* @param string $name
* @return Zend_Cache_Core
*/
public function getCache($name)
{
if (isset($this->_caches[$name])) {
return $this->_caches[$name];
}
if (isset($this->_optionTemplates[$name])) {
if ($name == self::PAGECACHE
&& (!isset($this->_optionTemplates[$name]['backend']['options']['tag_cache'])
|| !$this->_optionTemplates[$name]['backend']['options']['tag_cache'] instanceof Zend_Cache_Core)
) {
$this->_optionTemplates[$name]['backend']['options']['tag_cache']
= $this->getCache(self::PAGETAGCACHE);
}
$this->_caches[$name] = Zend_Cache::factory(
$this->_optionTemplates[$name]['frontend']['name'],
$this->_optionTemplates[$name]['backend']['name'],
isset($this->_optionTemplates[$name]['frontend']['options']) ? $this->_optionTemplates[$name]['frontend']['options'] : array(),
isset($this->_optionTemplates[$name]['backend']['options']) ? $this->_optionTemplates[$name]['backend']['options'] : array(),
isset($this->_optionTemplates[$name]['frontend']['customFrontendNaming']) ? $this->_optionTemplates[$name]['frontend']['customFrontendNaming'] : false,
isset($this->_optionTemplates[$name]['backend']['customBackendNaming']) ? $this->_optionTemplates[$name]['backend']['customBackendNaming'] : false,
isset($this->_optionTemplates[$name]['frontendBackendAutoload']) ? $this->_optionTemplates[$name]['frontendBackendAutoload'] : false
);
return $this->_caches[$name];
}
}
/**
* Fetch all available caches
*
* @return array An array of all available caches with it's names as key
*/
public function getCaches()
{
$caches = $this->_caches;
foreach ($this->_optionTemplates as $name => $tmp) {
if (!isset($caches[$name])) {
$caches[$name] = $this->getCache($name);
}
}
return $caches;
}
/**
* Set a named configuration template from which a cache object can later
* be lazy loaded
*
* @param string $name
* @param array $options
* @return Zend_Cache_Manager
* @throws Zend_Cache_Exception
*/
public function setCacheTemplate($name, $options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
#require_once 'Zend/Cache/Exception.php';
throw new Zend_Cache_Exception('Options passed must be in'
. ' an associative array or instance of Zend_Config');
}
$this->_optionTemplates[$name] = $options;
return $this;
}
/**
* Check if the named configuration template
*
* @param string $name
* @return bool
*/
public function hasCacheTemplate($name)
{
if (isset($this->_optionTemplates[$name])) {
return true;
}
return false;
}
/**
* Get the named configuration template
*
* @param string $name
* @return array
*/
public function getCacheTemplate($name)
{
if (isset($this->_optionTemplates[$name])) {
return $this->_optionTemplates[$name];
}
}
/**
* Pass an array containing changes to be applied to a named
* configuration
* template
*
* @param string $name
* @param array $options
* @return Zend_Cache_Manager
* @throws Zend_Cache_Exception for invalid options format or if option templates do not have $name
*/
public function setTemplateOptions($name, $options)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
#require_once 'Zend/Cache/Exception.php';
throw new Zend_Cache_Exception('Options passed must be in'
. ' an associative array or instance of Zend_Config');
}
if (!isset($this->_optionTemplates[$name])) {
throw new Zend_Cache_Exception('A cache configuration template'
. 'does not exist with the name "' . $name . '"');
}
$this->_optionTemplates[$name]
= $this->_mergeOptions($this->_optionTemplates[$name], $options);
return $this;
}
/**
* Simple method to merge two configuration arrays
*
* @param array $current
* @param array $options
* @return array
*/
protected function _mergeOptions(array $current, array $options)
{
if (isset($options['frontend']['name'])) {
$current['frontend']['name'] = $options['frontend']['name'];
}
if (isset($options['backend']['name'])) {
$current['backend']['name'] = $options['backend']['name'];
}
if (isset($options['frontend']['options'])) {
foreach ($options['frontend']['options'] as $key => $value) {
$current['frontend']['options'][$key] = $value;
}
}
if (isset($options['backend']['options'])) {
foreach ($options['backend']['options'] as $key => $value) {
$current['backend']['options'][$key] = $value;
}
}
if (isset($options['frontend']['customFrontendNaming'])) {
$current['frontend']['customFrontendNaming'] = $options['frontend']['customFrontendNaming'];
}
if (isset($options['backend']['customBackendNaming'])) {
$current['backend']['customBackendNaming'] = $options['backend']['customBackendNaming'];
}
if (isset($options['frontendBackendAutoload'])) {
$current['frontendBackendAutoload'] = $options['frontendBackendAutoload'];
}
return $current;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Exception */
#require_once 'Zend/Exception.php';
/**
* @category Zend
* @package Zend_Log
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Exception extends Zend_Exception
{}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Zend
* @package Zend_Log
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
interface Zend_Log_FactoryInterface
{
/**
* Construct a Zend_Log driver
*
* @param array|Zend_Config $config
* @return Zend_Log_FactoryInterface
*/
static public function factory($config);
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Log_Filter_Interface */
#require_once 'Zend/Log/Filter/Interface.php';
/** @see Zend_Log_FactoryInterface */
#require_once 'Zend/Log/FactoryInterface.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
abstract class Zend_Log_Filter_Abstract
implements Zend_Log_Filter_Interface, Zend_Log_FactoryInterface
{
/**
* Validate and optionally convert the config to array
*
* @param array|Zend_Config $config Zend_Config or Array
* @return array
* @throws Zend_Log_Exception
*/
static protected function _parseConfig($config)
{
if ($config instanceof Zend_Config) {
$config = $config->toArray();
}
if (!is_array($config)) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Configuration must be an array or instance of Zend_Config');
}
return $config;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
interface Zend_Log_Filter_Interface
{
/**
* Returns TRUE to accept the message, FALSE to block it.
*
* @param array $event event data
* @return boolean accepted?
*/
public function accept($event);
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Filter_Abstract */
#require_once 'Zend/Log/Filter/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Filter_Message extends Zend_Log_Filter_Abstract
{
/**
* @var string
*/
protected $_regexp;
/**
* Filter out any log messages not matching $regexp.
*
* @param string $regexp Regular expression to test the log message
* @return void
* @throws Zend_Log_Exception
*/
public function __construct($regexp)
{
if (@preg_match($regexp, '') === false) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception("Invalid regular expression '$regexp'");
}
$this->_regexp = $regexp;
}
/**
* Create a new instance of Zend_Log_Filter_Message
*
* @param array|Zend_Config $config
* @return Zend_Log_Filter_Message
*/
static public function factory($config)
{
$config = self::_parseConfig($config);
$config = array_merge(array(
'regexp' => null
), $config);
return new self(
$config['regexp']
);
}
/**
* Returns TRUE to accept the message, FALSE to block it.
*
* @param array $event event data
* @return boolean accepted?
*/
public function accept($event)
{
return preg_match($this->_regexp, $event['message']) > 0;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Filter_Abstract */
#require_once 'Zend/Log/Filter/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Filter_Priority extends Zend_Log_Filter_Abstract
{
/**
* @var integer
*/
protected $_priority;
/**
* @var string
*/
protected $_operator;
/**
* Filter logging by $priority. By default, it will accept any log
* event whose priority value is less than or equal to $priority.
*
* @param integer $priority Priority
* @param string $operator Comparison operator
* @return void
* @throws Zend_Log_Exception
*/
public function __construct($priority, $operator = null)
{
if (! is_int($priority)) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Priority must be an integer');
}
$this->_priority = $priority;
$this->_operator = $operator === null ? '<=' : $operator;
}
/**
* Create a new instance of Zend_Log_Filter_Priority
*
* @param array|Zend_Config $config
* @return Zend_Log_Filter_Priority
*/
static public function factory($config)
{
$config = self::_parseConfig($config);
$config = array_merge(array(
'priority' => null,
'operator' => null,
), $config);
// Add support for constants
if (!is_numeric($config['priority']) && isset($config['priority']) && defined($config['priority'])) {
$config['priority'] = constant($config['priority']);
}
return new self(
(int) $config['priority'],
$config['operator']
);
}
/**
* Returns TRUE to accept the message, FALSE to block it.
*
* @param array $event event data
* @return boolean accepted?
*/
public function accept($event)
{
return version_compare($event['priority'], $this->_priority, $this->_operator);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Filter_Interface */
#require_once 'Zend/Log/Filter/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Filter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Filter_Suppress extends Zend_Log_Filter_Abstract
{
/**
* @var boolean
*/
protected $_accept = true;
/**
* This is a simple boolean filter.
*
* Call suppress(true) to suppress all log events.
* Call suppress(false) to accept all log events.
*
* @param boolean $suppress Should all log events be suppressed?
* @return void
*/
public function suppress($suppress)
{
$this->_accept = (! $suppress);
}
/**
* Returns TRUE to accept the message, FALSE to block it.
*
* @param array $event event data
* @return boolean accepted?
*/
public function accept($event)
{
return $this->_accept;
}
/**
* Create a new instance of Zend_Log_Filter_Suppress
*
* @param array|Zend_Config $config
* @return Zend_Log_Filter_Suppress
* @throws Zend_Log_Exception
*/
static public function factory($config)
{
return new self();
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** @see Zend_Log_Formatter_Interface */
#require_once 'Zend/Log/Formatter/Interface.php';
/** @see Zend_Log_FactoryInterface */
#require_once 'Zend/Log/FactoryInterface.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
abstract class Zend_Log_Formatter_Abstract
implements Zend_Log_Formatter_Interface, Zend_Log_FactoryInterface
{
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
interface Zend_Log_Formatter_Interface
{
/**
* Formats data into a single line to be written by the writer.
*
* @param array $event event data
* @return string formatted line to write to the log
*/
public function format($event);
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Formatter_Abstract */
#require_once 'Zend/Log/Formatter/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Formatter_Simple extends Zend_Log_Formatter_Abstract
{
/**
* @var string
*/
protected $_format;
const DEFAULT_FORMAT = '%timestamp% %priorityName% (%priority%): %message%';
/**
* Class constructor
*
* @param null|string $format Format specifier for log messages
* @return void
* @throws Zend_Log_Exception
*/
public function __construct($format = null)
{
if ($format === null) {
$format = self::DEFAULT_FORMAT . PHP_EOL;
}
if (!is_string($format)) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Format must be a string');
}
$this->_format = $format;
}
/**
* Factory for Zend_Log_Formatter_Simple classe
*
* @param array|Zend_Config $options
* @return Zend_Log_Formatter_Simple
*/
public static function factory($options)
{
$format = null;
if (null !== $options) {
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (array_key_exists('format', $options)) {
$format = $options['format'];
}
}
return new self($format);
}
/**
* Formats data into a single line to be written by the writer.
*
* @param array $event event data
* @return string formatted line to write to the log
*/
public function format($event)
{
$output = $this->_format;
foreach ($event as $name => $value) {
if ((is_object($value) && !method_exists($value,'__toString'))
|| is_array($value)
) {
$value = gettype($value);
}
$output = str_replace("%$name%", $value, $output);
}
return $output;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Formatter_Abstract */
#require_once 'Zend/Log/Formatter/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Formatter
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Formatter_Xml extends Zend_Log_Formatter_Abstract
{
/**
* @var string Name of root element
*/
protected $_rootElement;
/**
* @var array Relates XML elements to log data field keys.
*/
protected $_elementMap;
/**
* @var string Encoding to use in XML
*/
protected $_encoding;
/**
* Class constructor
* (the default encoding is UTF-8)
*
* @param array|Zend_Config $options
* @return void
*/
public function __construct($options = array())
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
} elseif (!is_array($options)) {
$args = func_get_args();
$options = array(
'rootElement' => array_shift($args)
);
if (count($args)) {
$options['elementMap'] = array_shift($args);
}
if (count($args)) {
$options['encoding'] = array_shift($args);
}
}
if (!array_key_exists('rootElement', $options)) {
$options['rootElement'] = 'logEntry';
}
if (!array_key_exists('encoding', $options)) {
$options['encoding'] = 'UTF-8';
}
$this->_rootElement = $options['rootElement'];
$this->setEncoding($options['encoding']);
if (array_key_exists('elementMap', $options)) {
$this->_elementMap = $options['elementMap'];
}
}
/**
* Factory for Zend_Log_Formatter_Xml classe
*
* @param array|Zend_Config $options
* @return Zend_Log_Formatter_Xml
*/
public static function factory($options)
{
return new self($options);
}
/**
* Get encoding
*
* @return string
*/
public function getEncoding()
{
return $this->_encoding;
}
/**
* Set encoding
*
* @param string $value
* @return Zend_Log_Formatter_Xml
*/
public function setEncoding($value)
{
$this->_encoding = (string) $value;
return $this;
}
/**
* Formats data into a single line to be written by the writer.
*
* @param array $event event data
* @return string formatted line to write to the log
*/
public function format($event)
{
if ($this->_elementMap === null) {
$dataToInsert = $event;
} else {
$dataToInsert = array();
foreach ($this->_elementMap as $elementName => $fieldKey) {
$dataToInsert[$elementName] = $event[$fieldKey];
}
}
$enc = $this->getEncoding();
$dom = new DOMDocument('1.0', $enc);
$elt = $dom->appendChild(new DOMElement($this->_rootElement));
foreach ($dataToInsert as $key => $value) {
if (empty($value)
|| is_scalar($value)
|| (is_object($value) && method_exists($value,'__toString'))
) {
if($key == "message") {
$value = htmlspecialchars($value, ENT_COMPAT, $enc);
}
$elt->appendChild(new DOMElement($key, (string)$value));
}
}
$xml = $dom->saveXML();
$xml = preg_replace('/<\?xml version="1.0"( encoding="[^\"]*")?\?>\n/u', '', $xml);
return $xml . PHP_EOL;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Filter_Priority */
#require_once 'Zend/Log/Filter/Priority.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
abstract class Zend_Log_Writer_Abstract implements Zend_Log_FactoryInterface
{
/**
* @var array of Zend_Log_Filter_Interface
*/
protected $_filters = array();
/**
* Formats the log message before writing.
*
* @var Zend_Log_Formatter_Interface
*/
protected $_formatter;
/**
* Add a filter specific to this writer.
*
* @param Zend_Log_Filter_Interface|int $filter Filter class or filter
* priority
* @return Zend_Log_Writer_Abstract
* @throws Zend_Log_Exception
*/
public function addFilter($filter)
{
if (is_int($filter)) {
$filter = new Zend_Log_Filter_Priority($filter);
}
if (!$filter instanceof Zend_Log_Filter_Interface) {
/** @see Zend_Log_Exception */
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Invalid filter provided');
}
$this->_filters[] = $filter;
return $this;
}
/**
* Log a message to this writer.
*
* @param array $event log data event
* @return void
*/
public function write($event)
{
/** @var Zend_Log_Filter_Interface $filter */
foreach ($this->_filters as $filter) {
if (!$filter->accept($event)) {
return;
}
}
// exception occurs on error
$this->_write($event);
}
/**
* Set a new formatter for this writer
*
* @param Zend_Log_Formatter_Interface $formatter
* @return Zend_Log_Writer_Abstract
*/
public function setFormatter(Zend_Log_Formatter_Interface $formatter)
{
$this->_formatter = $formatter;
return $this;
}
/**
* Perform shutdown activites such as closing open resources
*
* @return void
*/
public function shutdown()
{}
/**
* Write a message to the log.
*
* @param array $event log data event
* @return void
*/
abstract protected function _write($event);
/**
* Validate and optionally convert the config to array
*
* @param array|Zend_Config $config Zend_Config or Array
* @return array
* @throws Zend_Log_Exception
*/
static protected function _parseConfig($config)
{
if ($config instanceof Zend_Config) {
$config = $config->toArray();
}
if (!is_array($config)) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception(
'Configuration must be an array or instance of Zend_Config'
);
}
return $config;
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Writer_Abstract */
#require_once 'Zend/Log/Writer/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Writer_Db extends Zend_Log_Writer_Abstract
{
/**
* Database adapter instance
*
* @var Zend_Db_Adapter
*/
protected $_db;
/**
* Name of the log table in the database
*
* @var string
*/
protected $_table;
/**
* Relates database columns names to log data field keys.
*
* @var null|array
*/
protected $_columnMap;
/**
* Class constructor
*
* @param Zend_Db_Adapter $db Database adapter instance
* @param string $table Log table in database
* @param array $columnMap
* @return void
*/
public function __construct($db, $table, $columnMap = null)
{
$this->_db = $db;
$this->_table = $table;
$this->_columnMap = $columnMap;
}
/**
* Create a new instance of Zend_Log_Writer_Db
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_Db
*/
static public function factory($config)
{
$config = self::_parseConfig($config);
$config = array_merge(array(
'db' => null,
'table' => null,
'columnMap' => null,
), $config);
if (isset($config['columnmap'])) {
$config['columnMap'] = $config['columnmap'];
}
return new self(
$config['db'],
$config['table'],
$config['columnMap']
);
}
/**
* Formatting is not possible on this writer
*
* @return void
* @throws Zend_Log_Exception
*/
public function setFormatter(Zend_Log_Formatter_Interface $formatter)
{
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception(get_class($this) . ' does not support formatting');
}
/**
* Remove reference to database adapter
*
* @return void
*/
public function shutdown()
{
$this->_db = null;
}
/**
* Write a message to the log.
*
* @param array $event event data
* @return void
* @throws Zend_Log_Exception
*/
protected function _write($event)
{
if ($this->_db === null) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Database adapter is null');
}
if ($this->_columnMap === null) {
$dataToInsert = $event;
} else {
$dataToInsert = array();
foreach ($this->_columnMap as $columnName => $fieldKey) {
if (isset($event[$fieldKey])) {
$dataToInsert[$columnName] = $event[$fieldKey];
}
}
}
$this->_db->insert($this->_table, $dataToInsert);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Writer_Abstract */
#require_once 'Zend/Log/Writer/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Writer_Mock extends Zend_Log_Writer_Abstract
{
/**
* array of log events
*
* @var array
*/
public $events = array();
/**
* shutdown called?
*
* @var boolean
*/
public $shutdown = false;
/**
* Write a message to the log.
*
* @param array $event event data
* @return void
*/
public function _write($event)
{
$this->events[] = $event;
}
/**
* Record shutdown
*
* @return void
*/
public function shutdown()
{
$this->shutdown = true;
}
/**
* Create a new instance of Zend_Log_Writer_Mock
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_Mock
*/
static public function factory($config)
{
return new self();
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Writer_Abstract */
#require_once 'Zend/Log/Writer/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Writer_Null extends Zend_Log_Writer_Abstract
{
/**
* Write a message to the log.
*
* @param array $event event data
* @return void
*/
protected function _write($event)
{
}
/**
* Create a new instance of Zend_Log_Writer_Null
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_Null
*/
static public function factory($config)
{
return new self();
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Writer_Abstract */
#require_once 'Zend/Log/Writer/Abstract.php';
/** Zend_Log_Formatter_Simple */
#require_once 'Zend/Log/Formatter/Simple.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Writer_Stream extends Zend_Log_Writer_Abstract
{
/**
* Holds the PHP stream to log to.
*
* @var null|stream
*/
protected $_stream = null;
/**
* Class Constructor
*
* @param array|string|resource $streamOrUrl Stream or URL to open as a stream
* @param string|null $mode Mode, only applicable if a URL is given
* @return void
* @throws Zend_Log_Exception
*/
public function __construct($streamOrUrl, $mode = null)
{
// Setting the default
if (null === $mode) {
$mode = 'a';
}
if (is_resource($streamOrUrl)) {
if (get_resource_type($streamOrUrl) != 'stream') {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Resource is not a stream');
}
if ($mode != 'a') {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Mode cannot be changed on existing streams');
}
$this->_stream = $streamOrUrl;
} else {
if (is_array($streamOrUrl) && isset($streamOrUrl['stream'])) {
$streamOrUrl = $streamOrUrl['stream'];
}
if (! $this->_stream = @fopen($streamOrUrl, $mode, false)) {
#require_once 'Zend/Log/Exception.php';
$msg = "\"$streamOrUrl\" cannot be opened with mode \"$mode\"";
throw new Zend_Log_Exception($msg);
}
}
$this->_formatter = new Zend_Log_Formatter_Simple();
}
/**
* Create a new instance of Zend_Log_Writer_Stream
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_Stream
*/
static public function factory($config)
{
$config = self::_parseConfig($config);
$config = array_merge(array(
'stream' => null,
'mode' => null,
), $config);
$streamOrUrl = isset($config['url']) ? $config['url'] : $config['stream'];
return new self(
$streamOrUrl,
$config['mode']
);
}
/**
* Close the stream resource.
*
* @return void
*/
public function shutdown()
{
if (is_resource($this->_stream)) {
fclose($this->_stream);
}
}
/**
* Write a message to the log.
*
* @param array $event event data
* @return void
* @throws Zend_Log_Exception
*/
protected function _write($event)
{
$line = $this->_formatter->format($event);
if (false === @fwrite($this->_stream, $line)) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception("Unable to write to stream");
}
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log */
#require_once 'Zend/Log.php';
/** Zend_Log_Writer_Abstract */
#require_once 'Zend/Log/Writer/Abstract.php';
/**
* Writes log messages to syslog
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Log_Writer_Syslog extends Zend_Log_Writer_Abstract
{
/**
* Maps Zend_Log priorities to PHP's syslog priorities
*
* @var array
*/
protected $_priorities = array(
Zend_Log::EMERG => LOG_EMERG,
Zend_Log::ALERT => LOG_ALERT,
Zend_Log::CRIT => LOG_CRIT,
Zend_Log::ERR => LOG_ERR,
Zend_Log::WARN => LOG_WARNING,
Zend_Log::NOTICE => LOG_NOTICE,
Zend_Log::INFO => LOG_INFO,
Zend_Log::DEBUG => LOG_DEBUG,
);
/**
* The default log priority - for unmapped custom priorities
*
* @var string
*/
protected $_defaultPriority = LOG_NOTICE;
/**
* Last application name set by a syslog-writer instance
*
* @var string
*/
protected static $_lastApplication;
/**
* Last facility name set by a syslog-writer instance
*
* @var string
*/
protected static $_lastFacility;
/**
* Application name used by this syslog-writer instance
*
* @var string
*/
protected $_application = 'Zend_Log';
/**
* Facility used by this syslog-writer instance
*
* @var int
*/
protected $_facility = LOG_USER;
/**
* Types of program available to logging of message
*
* @var array
*/
protected $_validFacilities = array();
/**
* Class constructor
*
* @param array $params Array of options; may include "application" and "facility" keys
* @return void
*/
public function __construct(array $params = array())
{
if (isset($params['application'])) {
$this->_application = $params['application'];
}
$runInitializeSyslog = true;
if (isset($params['facility'])) {
$this->setFacility($params['facility']);
$runInitializeSyslog = false;
}
if ($runInitializeSyslog) {
$this->_initializeSyslog();
}
}
/**
* Create a new instance of Zend_Log_Writer_Syslog
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_Syslog
*/
static public function factory($config)
{
return new self(self::_parseConfig($config));
}
/**
* Initialize values facilities
*
* @return void
*/
protected function _initializeValidFacilities()
{
$constants = array(
'LOG_AUTH',
'LOG_AUTHPRIV',
'LOG_CRON',
'LOG_DAEMON',
'LOG_KERN',
'LOG_LOCAL0',
'LOG_LOCAL1',
'LOG_LOCAL2',
'LOG_LOCAL3',
'LOG_LOCAL4',
'LOG_LOCAL5',
'LOG_LOCAL6',
'LOG_LOCAL7',
'LOG_LPR',
'LOG_MAIL',
'LOG_NEWS',
'LOG_SYSLOG',
'LOG_USER',
'LOG_UUCP'
);
foreach ($constants as $constant) {
if (defined($constant)) {
$this->_validFacilities[] = constant($constant);
}
}
}
/**
* Initialize syslog / set application name and facility
*
* @return void
*/
protected function _initializeSyslog()
{
self::$_lastApplication = $this->_application;
self::$_lastFacility = $this->_facility;
openlog($this->_application, LOG_PID, $this->_facility);
}
/**
* Set syslog facility
*
* @param int $facility Syslog facility
* @return Zend_Log_Writer_Syslog
* @throws Zend_Log_Exception for invalid log facility
*/
public function setFacility($facility)
{
if ($this->_facility === $facility) {
return $this;
}
if (!count($this->_validFacilities)) {
$this->_initializeValidFacilities();
}
if (!in_array($facility, $this->_validFacilities)) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Invalid log facility provided; please see http://php.net/openlog for a list of valid facility values');
}
if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))
&& ($facility !== LOG_USER)
) {
#require_once 'Zend/Log/Exception.php';
throw new Zend_Log_Exception('Only LOG_USER is a valid log facility on Windows');
}
$this->_facility = $facility;
$this->_initializeSyslog();
return $this;
}
/**
* Set application name
*
* @param string $application Application name
* @return Zend_Log_Writer_Syslog
*/
public function setApplicationName($application)
{
if ($this->_application === $application) {
return $this;
}
$this->_application = $application;
$this->_initializeSyslog();
return $this;
}
/**
* Close syslog.
*
* @return void
*/
public function shutdown()
{
closelog();
}
/**
* Write a message to syslog.
*
* @param array $event event data
* @return void
*/
protected function _write($event)
{
if (array_key_exists($event['priority'], $this->_priorities)) {
$priority = $this->_priorities[$event['priority']];
} else {
$priority = $this->_defaultPriority;
}
if ($this->_application !== self::$_lastApplication
|| $this->_facility !== self::$_lastFacility)
{
$this->_initializeSyslog();
}
$message = $event['message'];
if ($this->_formatter instanceof Zend_Log_Formatter_Interface) {
$message = $this->_formatter->format($event);
}
syslog($priority, $message);
}
}
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/** Zend_Log_Writer_Abstract */
#require_once 'Zend/Log/Writer/Abstract.php';
/**
* @category Zend
* @package Zend_Log
* @subpackage Writer
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
class Zend_Log_Writer_ZendMonitor extends Zend_Log_Writer_Abstract
{
/**
* Is Zend Monitor enabled?
*
* @var boolean
*/
protected $_isEnabled = true;
/**
* Is this for a Zend Server intance?
*
* @var boolean
*/
protected $_isZendServer = false;
/**
* @return void
*/
public function __construct()
{
if (!function_exists('monitor_custom_event')) {
$this->_isEnabled = false;
}
if (function_exists('zend_monitor_custom_event')) {
$this->_isZendServer = true;
}
}
/**
* Create a new instance of Zend_Log_Writer_ZendMonitor
*
* @param array|Zend_Config $config
* @return Zend_Log_Writer_ZendMonitor
*/
static public function factory($config)
{
return new self();
}
/**
* Is logging to this writer enabled?
*
* If the Zend Monitor extension is not enabled, this log writer will
* fail silently. You can query this method to determine if the log
* writer is enabled.
*
* @return boolean
*/
public function isEnabled()
{
return $this->_isEnabled;
}
/**
* Log a message to this writer.
*
* @param array $event log data event
* @return void
*/
public function write($event)
{
if (!$this->isEnabled()) {
return;
}
parent::write($event);
}
/**
* Write a message to the log.
*
* @param array $event log data event
* @return void
*/
protected function _write($event)
{
$priority = $event['priority'];
$message = $event['message'];
unset($event['priority'], $event['message']);
if (!empty($event)) {
if ($this->_isZendServer) {
// On Zend Server; third argument should be the event
zend_monitor_custom_event($priority, $message, $event);
} else {
// On Zend Platform; third argument is severity -- either
// 0 or 1 -- and fourth is optional (event)
// Severity is either 0 (normal) or 1 (severe); classifying
// notice, info, and debug as "normal", and all others as
// "severe"
monitor_custom_event($priority, $message, ($priority > 4) ? 0 : 1, $event);
}
} else {
monitor_custom_event($priority, $message);
}
}
}
<?php
/*
* This file is part of Mustache.php.
*
* (c) 2010-2017 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Abstract Mustache Cache class.
*
* Provides logging support to child implementations.
*
* @abstract
*/
abstract class Mustache_Cache_AbstractCache implements Mustache_Cache
{
private $logger = null;
/**
* Get the current logger instance.
*
* @return Mustache_Logger|Psr\Log\LoggerInterface
*/
public function getLogger()
{
return $this->logger;
}
/**
* Set a logger instance.
*
* @param Mustache_Logger|Psr\Log\LoggerInterface $logger
*/
public function setLogger($logger = null)
{
if ($logger !== null && !($logger instanceof Mustache_Logger || is_a($logger, 'Psr\\Log\\LoggerInterface'))) {
throw new Mustache_Exception_InvalidArgumentException('Expected an instance of Mustache_Logger or Psr\\Log\\LoggerInterface.');
}
$this->logger = $logger;
}
/**
* Add a log record if logging is enabled.
*
* @param string $level The logging level
* @param string $message The log message
* @param array $context The log context
*/
protected function log($level, $message, array $context = array())
{
if (isset($this->logger)) {
$this->logger->log($level, $message, $context);
}
}
}
<?php
/*
* This file is part of Mustache.php.
*
* (c) 2010-2017 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Mustache Cache filesystem implementation.
*
* A FilesystemCache instance caches Mustache Template classes from the filesystem by name:
*
* $cache = new Mustache_Cache_FilesystemCache(dirname(__FILE__).'/cache');
* $cache->cache($className, $compiledSource);
*
* The FilesystemCache benefits from any opcode caching that may be setup in your environment. So do that, k?
*/
class Mustache_Cache_FilesystemCache extends Mustache_Cache_AbstractCache
{
private $baseDir;
private $fileMode;
/**
* Filesystem cache constructor.
*
* @param string $baseDir Directory for compiled templates
* @param int $fileMode Override default permissions for cache files. Defaults to using the system-defined umask
*/
public function __construct($baseDir, $fileMode = null)
{
$this->baseDir = $baseDir;
$this->fileMode = $fileMode;
}
/**
* Load the class from cache using `require_once`.
*
* @param string $key
*
* @return bool
*/
public function load($key)
{
$fileName = $this->getCacheFilename($key);
if (!is_file($fileName)) {
return false;
}
require_once $fileName;
return true;
}
/**
* Cache and load the compiled class.
*
* @param string $key
* @param string $value
*/
public function cache($key, $value)
{
$fileName = $this->getCacheFilename($key);
$this->log(
Mustache_Logger::DEBUG,
'Writing to template cache: "{fileName}"',
array('fileName' => $fileName)
);
$this->writeFile($fileName, $value);
$this->load($key);
}
/**
* Build the cache filename.
* Subclasses should override for custom cache directory structures.
*
* @param string $name
*
* @return string
*/
protected function getCacheFilename($name)
{
return sprintf('%s/%s.php', $this->baseDir, $name);
}
/**
* Create cache directory.
*
* @throws Mustache_Exception_RuntimeException If unable to create directory
*
* @param string $fileName
*
* @return string
*/
private function buildDirectoryForFilename($fileName)
{
$dirName = dirname($fileName);
if (!is_dir($dirName)) {
$this->log(
Mustache_Logger::INFO,
'Creating Mustache template cache directory: "{dirName}"',
array('dirName' => $dirName)
);
@mkdir($dirName, 0777, true);
// @codeCoverageIgnoreStart
if (!is_dir($dirName)) {
throw new Mustache_Exception_RuntimeException(sprintf('Failed to create cache directory "%s".', $dirName));
}
// @codeCoverageIgnoreEnd
}
return $dirName;
}
/**
* Write cache file.
*
* @throws Mustache_Exception_RuntimeException If unable to write file
*
* @param string $fileName
* @param string $value
*/
private function writeFile($fileName, $value)
{
$dirName = $this->buildDirectoryForFilename($fileName);
$this->log(
Mustache_Logger::DEBUG,
'Caching compiled template to "{fileName}"',
array('fileName' => $fileName)
);
$tempFile = tempnam($dirName, basename($fileName));
if (false !== @file_put_contents($tempFile, $value)) {
if (@rename($tempFile, $fileName)) {
$mode = isset($this->fileMode) ? $this->fileMode : (0666 & ~umask());
@chmod($fileName, $mode);
return;
}
// @codeCoverageIgnoreStart
$this->log(
Mustache_Logger::ERROR,
'Unable to rename Mustache temp cache file: "{tempName}" -> "{fileName}"',
array('tempName' => $tempFile, 'fileName' => $fileName)
);
// @codeCoverageIgnoreEnd
}
// @codeCoverageIgnoreStart
throw new Mustache_Exception_RuntimeException(sprintf('Failed to write cache file "%s".', $fileName));
// @codeCoverageIgnoreEnd
}
}
<?php
/*
* This file is part of Mustache.php.
*
* (c) 2010-2017 Justin Hileman
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Mustache Cache in-memory implementation.
*
* The in-memory cache is used for uncached lambda section templates. It's also useful during development, but is not
* recommended for production use.
*/
class Mustache_Cache_NoopCache extends Mustache_Cache_AbstractCache
{
/**
* Loads nothing. Move along.
*
* @param string $key
*
* @return bool
*/
public function load($key)
{
return false;
}
/**
* Loads the compiled Mustache Template class without caching.
*
* @param string $key
* @param string $value
*/
public function cache($key, $value)
{
$this->log(
Mustache_Logger::WARNING,
'Template cache disabled, evaluating "{className}" class at runtime',
array('className' => $key)
);
eval('?>' . $value);
}
}
<?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
namespace PDepend\Util\Cache;
/**
* Base interface for a concrete cache driver.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
interface CacheDriver
{
/**
* The current cache version.
*/
const VERSION = '@version:a31e9e344aac643e20751f6d915114eb:@';
/**
* Sets the type for the next <em>store()</em> or <em>restore()</em> method
* call. A type is something like a namespace or group for cache entries.
*
* Note that the cache type will be reset after each storage method call, so
* you must invoke right before every call to <em>restore()</em> or
* <em>store()</em>.
*
* @param string $type
* @return \PDepend\Util\Cache\CacheDriver
*/
public function type($type);
/**
* This method will store the given <em>$data</em> under <em>$key</em>. This
* method can be called with a third parameter that will be used as a
* verification token, when the a cache entry gets restored. If the stored
* hash and the supplied hash are not identical, that cache entry will be
* removed and not returned.
*
* @param string $key The cache key for the given data.
* @param mixed $data Any data that should be cached.
* @param string $hash Optional hash that will be used for verification.
* @return void
*/
public function store($key, $data, $hash = null);
/**
* This method tries to restore an existing cache entry for the given
* <em>$key</em>. If a matching entry exists, this method verifies that the
* given <em>$hash</em> and the the value stored with cache entry are equal.
* Then it returns the cached entry. Otherwise this method will return
* <b>NULL</b>.
*
* @param string $key The cache key for the given data.
* @param string $hash Optional hash that will be used for verification.
* @return mixed
*/
public function restore($key, $hash = null);
/**
* This method will remove an existing cache entry for the given identifier.
* It will delete all cache entries where the cache key start with the given
* <b>$pattern</b>. If no matching entry exists, this method simply does
* nothing.
*
* @param string $pattern The cache key pattern.
* @return void
*/
public function remove($pattern);
}
<?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
namespace PDepend\Util\Cache;
use PDepend\Util\Cache\Driver\FileCacheDriver;
use PDepend\Util\Cache\Driver\MemoryCacheDriver;
use PDepend\Util\Configuration;
/**
* Factory that encapsulates the creation of a concrete cache instance.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
class CacheFactory
{
/**
* The system configuration.
*
* @var \PDepend\Util\Configuration
*/
protected $configuration = null;
/**
* Singleton property that holds existing cache instances.
*
* @var \PDepend\Util\Cache\CacheDriver[]
*/
protected $caches = array();
/**
* Constructs a new cache factory instance for the given configuration.
*
* @param \PDepend\Util\Configuration $configuration The system configuration.
*/
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* Creates a new instance or returns an existing cache for the given cache
* identifier.
*
* @param string $cacheKey The name/identifier for the cache instance.
*
* @return \PDepend\Util\Cache\CacheDriver
*/
public function create($cacheKey = null)
{
if (false === isset($this->caches[$cacheKey])) {
$this->caches[$cacheKey] = $this->createCache($cacheKey);
}
return $this->caches[$cacheKey];
}
/**
* Creates a cache instance based on the supplied configuration.
*
* @param string $cacheKey The name/identifier for the cache instance.
* @return \PDepend\Util\Cache\CacheDriver
* @throws \InvalidArgumentException If the configured cache driver is unknown.
*/
protected function createCache($cacheKey)
{
switch ($this->configuration->cache->driver) {
case 'file':
return $this->createFileCache(
$this->configuration->cache->location,
$cacheKey
);
case 'memory':
return $this->createMemoryCache();
}
throw new \InvalidArgumentException(
"Unknown cache driver '{$this->configuration->cache->driver}' given."
);
}
/**
* Creates a new file system based cache instance.
*
* @param string $location Cache root directory.
* @param string $cacheKey The name/identifier for the cache instance.
* @return \PDepend\Util\Cache\Driver\FileCacheDriver
*/
protected function createFileCache($location, $cacheKey)
{
return new FileCacheDriver($location, $cacheKey);
}
/**
* Creates an in memory cache instance.
*
* @return \PDepend\Util\Cache\Driver\MemoryCacheDriver
*/
protected function createMemoryCache()
{
return new MemoryCacheDriver();
}
}
<?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
namespace PDepend\Util\Cache\Driver\File;
use PDepend\Util\Cache\CacheDriver;
/**
* Directory helper for the file system based cache implementation.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
class FileCacheDirectory
{
/**
* The current cache version/hash number.
*/
const VERSION = CacheDriver::VERSION;
/**
* The cache root directory.
*
* @var string
*/
protected $cacheDir = null;
/**
* Constructs a new cache directory helper instance.
*
* @param string $cacheDir The cache root directory.
*/
public function __construct($cacheDir)
{
$this->cacheDir = $this->ensureExists($cacheDir);
if (false === $this->isValidVersion()) {
$this->flush();
}
}
/**
* Creates a cache directory for the given cache entry key and returns the
* full qualified path for that cache directory.
*
* @param string $key The cache for an entry.
* @return string
*/
public function createCacheDirectory($key)
{
return $this->createOrReturnCacheDirectory($key);
}
/**
* Returns the full qualified path for an existing cache directory or
* creates a new cache directory for the given cache entry key and returns
* the full qualified path for that cache directory.
*
* @param string $key The cache for an entry.
* @return string
*/
protected function createOrReturnCacheDirectory($key)
{
$path = $this->getCacheDir() . '/' . substr($key, 0, 2);
if (false === file_exists($path)) {
@mkdir($path, 0775, true);
}
return $path;
}
/**
* Ensures that the given <b>$cacheDir</b> really exists.
*
* @param string $cacheDir The cache root directory.
* @return string
*/
protected function ensureExists($cacheDir)
{
if (false === file_exists($cacheDir)) {
@mkdir($cacheDir, 0775, true);
}
return $cacheDir;
}
/**
* Tests if the current software cache version is similar to the stored
* file system cache version.
*
* @return boolean
*/
protected function isValidVersion()
{
return (self::VERSION === $this->readVersion());
}
/**
* Reads the stored cache version number from the cache root directory.
*
* @return string|null
*/
protected function readVersion()
{
if (file_exists($this->getVersionFile())) {
return trim(file_get_contents($this->getVersionFile()));
}
return null;
}
/**
* Writes the current software cache version into a file in the cache root
* directory.
*
* @return void
*/
protected function writeVersion()
{
file_put_contents($this->getVersionFile(), self::VERSION, LOCK_EX);
}
/**
* Returns the file name for the used version file.
*
* @return string
*/
protected function getVersionFile()
{
return $this->getCacheDir() . '/_version';
}
/**
* Returns the cache root directory.
*
* @return string
*/
protected function getCacheDir()
{
return $this->cacheDir;
}
/**
* Flushes all contents below the configured cache root directory and writes
* a version file with the current software version.
*
* @return void
*/
protected function flush()
{
$this->flushDirectory($this->getCacheDir());
$this->writeVersion();
}
/**
* Deletes all files and directories below the given <b>$cacheDir</b>.
*
* @param string $cacheDir A cache directory.
*
* @return void
*/
protected function flushDirectory($cacheDir)
{
foreach (new \DirectoryIterator($cacheDir) as $child) {
$this->flushEntry($child);
}
}
/**
* Flushes the cache record for the given file info instance, independent if
* it is a file, directory or symlink.
*
* @param \SplFileInfo $file
* @return void
*/
protected function flushEntry(\SplFileInfo $file)
{
$path = $file->getRealPath();
if ($file->isDot()) {
return;
} elseif ($file->isFile()) {
@unlink($path);
} else {
$this->flushDirectory($path);
@rmdir($path);
}
}
}
<?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
namespace PDepend\Util\Cache\Driver\File;
use PDepend\Util\Log;
/**
* Simple garbage collector for PDepend's file cache.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
class FileCacheGarbageCollector
{
/**
* @var string
*/
private $cacheDir;
/**
* @var integer
*/
private $minTime;
/**
* @param string $cacheDir
* @param integer $maxDays
*/
public function __construct($cacheDir, $maxDays = 30)
{
$this->cacheDir = $cacheDir;
$this->minTime = time() - ($maxDays * 86400);
}
/**
* Removes all outdated cache files and returns the number of garbage
* collected files.
*
* @return integer
*/
public function garbageCollect()
{
if (false === file_exists($this->cacheDir)) {
return 0;
}
$count = 0;
try {
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->cacheDir)
);
foreach ($files as $file) {
if ($this->isCollectibleFile($file)) {
$this->garbageCollectFile($file);
$count += 1;
}
}
return $count;
} catch (\UnexpectedValueException $e) {
/* This may happen if PHPMD and PDepend run in parallel */
return $count;
}
}
/**
* Checks if the given file can be removed.
*
* @param \SplFileInfo $file
* @return boolean
*/
private function isCollectibleFile(\SplFileInfo $file)
{
if (false === $file->isFile()) {
return false;
}
$time = $file->getATime();
if ($time > $this->minTime) {
return false;
}
$time = $file->getMTime();
if ($time > $this->minTime) {
return false;
}
return true;
}
/**
* Removes the given cache file.
*
* @param \SplFileInfo $file
* @return void
*/
private function garbageCollectFile(\SplFileInfo $file)
{
Log::debug("Removing file '{$file->getPathname()}' from cache.");
@unlink($file->getPathname());
}
}
<?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
namespace PDepend\Util\Cache\Driver;
use PDepend\Util\Cache\CacheDriver;
use PDepend\Util\Cache\Driver\File\FileCacheDirectory;
use PDepend\Util\Cache\Driver\File\FileCacheGarbageCollector;
/**
* A file system based cache implementation.
*
* This class implements the {@link \PDepend\Util\Cache\CacheDriver} interface
* based on the local file system. It creates a special directory structure and
* stores all cache entries in files under this directory structure.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
class FileCacheDriver implements CacheDriver
{
/**
* Default cache entry type.
*/
const ENTRY_TYPE = 'cache';
/**
* The cache directory handler
*
* @var FileCacheDirectory
*/
protected $directory;
/**
* The current cache entry type.
*
* @var string
*/
protected $type = self::ENTRY_TYPE;
/**
* Major and minor version of the currently used PHP.
*
* @var string
*/
protected $version;
/**
* Unique key for this cache instance.
*
* @var string
* @since 1.0.0
*/
private $cacheKey;
/**
* @var \PDepend\Util\Cache\Driver\File\FileCacheGarbageCollector
*/
private $garbageCollector;
/**
* This method constructs a new file cache instance for the given root
* directory.
*
* @param string $root The cache root directory.
* @param string $cacheKey Unique key for this cache instance.
*/
public function __construct($root, $cacheKey = null)
{
$this->directory = new FileCacheDirectory($root);
$this->version = preg_replace('(^(\d+\.\d+).*)', '\\1', phpversion());
$this->cacheKey = $cacheKey;
$this->garbageCollect($root);
}
/**
* Sets the type for the next <em>store()</em> or <em>restore()</em> method
* call. A type is something like a namespace or group for cache entries.
*
* Note that the cache type will be reset after each storage method call, so
* you must invoke right before every call to <em>restore()</em> or
* <em>store()</em>.
*
* @param string $type The name or object type for the next storage method call.
* @return \PDepend\Util\Cache\CacheDriver
*/
public function type($type)
{
$this->type = $type;
return $this;
}
/**
* This method will store the given <em>$data</em> under <em>$key</em>. This
* method can be called with a third parameter that will be used as a
* verification token, when the a cache entry gets restored. If the stored
* hash and the supplied hash are not identical, that cache entry will be
* removed and not returned.
*
* @param string $key The cache key for the given data.
* @param mixed $data Any data that should be cached.
* @param string $hash Optional hash that will be used for verification.
* @return void
*/
public function store($key, $data, $hash = null)
{
$file = $this->getCacheFile($key);
$this->write($file, serialize(array('hash' => $hash, 'data' => $data)));
}
/**
* This method writes the given <em>$data</em> into <em>$file</em>.
*
* @param string $file The cache file name.
* @param string $data Serialized cache data.
* @return void
*/
protected function write($file, $data)
{
$handle = fopen($file, 'wb');
flock($handle, LOCK_EX);
fwrite($handle, $data);
flock($handle, LOCK_UN);
fclose($handle);
}
/**
* This method tries to restore an existing cache entry for the given
* <em>$key</em>. If a matching entry exists, this method verifies that the
* given <em>$hash</em> and the the value stored with cache entry are equal.
* Then it returns the cached entry. Otherwise this method will return
* <b>NULL</b>.
*
* @param string $key The cache key for the given data.
* @param string $hash Optional hash that will be used for verification.
* @return mixed
*/
public function restore($key, $hash = null)
{
$file = $this->getCacheFile($key);
if (file_exists($file)) {
return $this->restoreFile($file, $hash);
}
return null;
}
/**
* This method restores a cache entry, when the given <em>$hash</em> is equal
* to stored hash value. If both hashes are equal this method returns the
* cached entry. Otherwise this method returns <b>NULL</b>.
*
* @param string $file The cache file name.
* @param string $hash The verification hash.
* @return mixed
*/
protected function restoreFile($file, $hash)
{
// unserialize() throws E_NOTICE when data is corrupt
$data = @unserialize($this->read($file));
if ($data !== false && $data['hash'] === $hash) {
return $data['data'];
}
return null;
}
/**
* This method reads the raw data from the given <em>$file</em>.
*
* @param string $file The cache file name.
* @return string
*/
protected function read($file)
{
$handle = fopen($file, 'rb');
flock($handle, LOCK_EX);
$data = fread($handle, filesize($file));
flock($handle, LOCK_UN);
fclose($handle);
return $data;
}
/**
* This method will remove an existing cache entry for the given identifier.
* It will delete all cache entries where the cache key start with the given
* <b>$pattern</b>. If no matching entry exists, this method simply does
* nothing.
*
* @param string $pattern The cache key pattern.
* @return void
*/
public function remove($pattern)
{
$file = $this->getCacheFileWithoutExtension($pattern);
$glob = glob("{$file}*.*");
// avoid error if we dont find files
if ($glob !== false) {
foreach (glob("{$file}*.*") as $f) {
@unlink($f);
}
}
}
/**
* This method creates the full qualified file name for a cache entry. This
* file name is a combination of the given <em>$key</em>, the cache root
* directory and the current entry type.
*
* @param string $key The cache key for the given data.
* @return string
*/
protected function getCacheFile($key)
{
$cacheFile = $this->getCacheFileWithoutExtension($key) .
'.' . $this->version .
'.' . $this->type;
$this->type = self::ENTRY_TYPE;
return $cacheFile;
}
/**
* This method creates the full qualified file name for a cache entry. This
* file name is a combination of the given <em>$key</em>, the cache root
* directory and the current entry type, but without the used cache file
* extension.
*
* @param string $key The cache key for the given data.
* @return string
*/
protected function getCacheFileWithoutExtension($key)
{
if (is_string($this->cacheKey)) {
$key = md5($key . $this->cacheKey);
}
$path = $this->directory->createCacheDirectory($key);
return "{$path}/{$key}";
}
/**
* Cleans old cache files.
*
* @param string $root
* @return void
*/
protected function garbageCollect($root)
{
$garbageCollector = new FileCacheGarbageCollector($root);
$garbageCollector->garbageCollect();
}
}
<?php
/**
* This file is part of PDepend.
*
* PHP Version 5
*
* Copyright (c) 2008-2017 Manuel Pichler <mapi@pdepend.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Manuel Pichler nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
namespace PDepend\Util\Cache\Driver;
use PDepend\Util\Cache\CacheDriver;
/**
* A memory based cache implementation.
*
* This class implements the {@link \PDepend\Util\Cache\CacheDriver} interface based
* on an in memory data structure. This means that all cached entries will get
* lost when the php process exits.
*
* @copyright 2008-2017 Manuel Pichler. All rights reserved.
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @since 0.10.0
*/
class MemoryCacheDriver implements CacheDriver
{
/**
* Default cache entry type.
*/
const ENTRY_TYPE = 'cache';
/**
* The in memory cache.
*
* @var array<string, array>
*/
protected $cache = array();
/**
* Current cache entry type.
*
* @var string
*/
protected $type = self::ENTRY_TYPE;
/**
* Unique identifier within the same cache instance.
*
* @var string
*/
protected $staticId = null;
/**
* Global stack, mainly used during testing.
*
* @var array
*/
protected static $staticCache = array();
/**
* Instantiates a new in memory cache instance.
*/
public function __construct()
{
$this->staticId = sha1(uniqid(rand(0, PHP_INT_MAX)));
}
/**
* Sets the type for the next <em>store()</em> or <em>restore()</em> method
* call. A type is something like a namespace or group for cache entries.
*
* Note that the cache type will be reset after each storage method call, so
* you must invoke right before every call to <em>restore()</em> or
* <em>store()</em>.
*
* @param string $type The name or object type for the next storage method call.
* @return \PDepend\Util\Cache\CacheDriver
*/
public function type($type)
{
$this->type = $type;
return $this;
}
/**
* This method will store the given <em>$data</em> under <em>$key</em>. This
* method can be called with a third parameter that will be used as a
* verification token, when the a cache entry gets restored. If the stored
* hash and the supplied hash are not identical, that cache entry will be
* removed and not returned.
*
* @param string $key The cache key for the given data.
* @param mixed $data Any data that should be cached.
* @param string $hash Optional hash that will be used for verification.
* @return void
*/
public function store($key, $data, $hash = null)
{
$this->cache[$this->getCacheKey($key)] = array($hash, $data);
}
/**
* This method tries to restore an existing cache entry for the given
* <em>$key</em>. If a matching entry exists, this method verifies that the
* given <em>$hash</em> and the the value stored with cache entry are equal.
* Then it returns the cached entry. Otherwise this method will return
* <b>NULL</b>.
*
* @param string $key The cache key for the given data.
* @param string $hash Optional hash that will be used for verification.
* @return mixed
*/
public function restore($key, $hash = null)
{
$cacheKey = $this->getCacheKey($key);
if (isset($this->cache[$cacheKey]) && $this->cache[$cacheKey][0] === $hash) {
return $this->cache[$cacheKey][1];
}
return null;
}
/**
* This method will remove an existing cache entry for the given identifier.
* It will delete all cache entries where the cache key start with the given
* <b>$pattern</b>. If no matching entry exists, this method simply does
* nothing.
*
* @param string $pattern The cache key pattern.
* @return void
*/
public function remove($pattern)
{
foreach (array_keys($this->cache) as $key) {
if (0 === strpos($key, $pattern)) {
unset($this->cache[$key]);
}
}
}
/**
* Creates a prepared cache entry identifier, based on the given <em>$key</em>
* and the <em>$type</em> property. Note that this method resets the cache
* type, so that it is only valid for a single call.
*
* @param string $key The concrete object key.
* @return string
*/
protected function getCacheKey($key)
{
$type = $this->type;
$this->type = self::ENTRY_TYPE;
return "{$key}.{$type}";
}
/**
* PHP's magic serialize sleep method.
*
* @return array
* @since 1.0.2
*/
public function __sleep()
{
self::$staticCache[$this->staticId] = $this->cache;
return array('staticId');
}
/**
* PHP's magic serialize wakeup method.
*
* @return void
* @since 1.0.2
*/
public function __wakeup()
{
$this->cache = self::$staticCache[$this->staticId];
}
}
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util\Log;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExceptionWrapper;
use PHPUnit\Framework\SelfDescribing;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\Util\Exception;
use PHPUnit\Util\Filter;
use PHPUnit\Util\Printer;
use PHPUnit\Util\Xml;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class JUnit extends Printer implements TestListener
{
/**
* @var \DOMDocument
*/
private $document;
/**
* @var \DOMElement
*/
private $root;
/**
* @var bool
*/
private $reportRiskyTests = false;
/**
* @var \DOMElement[]
*/
private $testSuites = [];
/**
* @var int[]
*/
private $testSuiteTests = [0];
/**
* @var int[]
*/
private $testSuiteAssertions = [0];
/**
* @var int[]
*/
private $testSuiteErrors = [0];
/**
* @var int[]
*/
private $testSuiteWarnings = [0];
/**
* @var int[]
*/
private $testSuiteFailures = [0];
/**
* @var int[]
*/
private $testSuiteSkipped = [0];
/**
* @var int[]
*/
private $testSuiteTimes = [0];
/**
* @var int
*/
private $testSuiteLevel = 0;
/**
* @var \DOMElement
*/
private $currentTestCase;
/**
* @param null|mixed $out
*/
public function __construct($out = null, bool $reportRiskyTests = false)
{
$this->document = new \DOMDocument('1.0', 'UTF-8');
$this->document->formatOutput = true;
$this->root = $this->document->createElement('testsuites');
$this->document->appendChild($this->root);
parent::__construct($out);
$this->reportRiskyTests = $reportRiskyTests;
}
/**
* Flush buffer and close output.
*/
public function flush(): void
{
$this->write($this->getXML());
parent::flush();
}
/**
* An error occurred.
*/
public function addError(Test $test, \Throwable $t, float $time): void
{
$this->doAddFault($test, $t, 'error');
$this->testSuiteErrors[$this->testSuiteLevel]++;
}
/**
* A warning occurred.
*/
public function addWarning(Test $test, Warning $e, float $time): void
{
$this->doAddFault($test, $e, 'warning');
$this->testSuiteWarnings[$this->testSuiteLevel]++;
}
/**
* A failure occurred.
*/
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
$this->doAddFault($test, $e, 'failure');
$this->testSuiteFailures[$this->testSuiteLevel]++;
}
/**
* Incomplete test.
*/
public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
{
$this->doAddSkipped();
}
/**
* Risky test.
*/
public function addRiskyTest(Test $test, \Throwable $t, float $time): void
{
if (!$this->reportRiskyTests || $this->currentTestCase === null) {
return;
}
$error = $this->document->createElement(
'error',
Xml::prepareString(
"Risky Test\n" .
Filter::getFilteredStacktrace($t)
)
);
$error->setAttribute('type', \get_class($t));
$this->currentTestCase->appendChild($error);
$this->testSuiteErrors[$this->testSuiteLevel]++;
}
/**
* Skipped test.
*/
public function addSkippedTest(Test $test, \Throwable $t, float $time): void
{
$this->doAddSkipped();
}
/**
* A testsuite started.
*/
public function startTestSuite(TestSuite $suite): void
{
$testSuite = $this->document->createElement('testsuite');
$testSuite->setAttribute('name', $suite->getName());
if (\class_exists($suite->getName(), false)) {
try {
$class = new \ReflectionClass($suite->getName());
$testSuite->setAttribute('file', $class->getFileName());
} catch (\ReflectionException $e) {
}
}
if ($this->testSuiteLevel > 0) {
$this->testSuites[$this->testSuiteLevel]->appendChild($testSuite);
} else {
$this->root->appendChild($testSuite);
}
$this->testSuiteLevel++;
$this->testSuites[$this->testSuiteLevel] = $testSuite;
$this->testSuiteTests[$this->testSuiteLevel] = 0;
$this->testSuiteAssertions[$this->testSuiteLevel] = 0;
$this->testSuiteErrors[$this->testSuiteLevel] = 0;
$this->testSuiteWarnings[$this->testSuiteLevel] = 0;
$this->testSuiteFailures[$this->testSuiteLevel] = 0;
$this->testSuiteSkipped[$this->testSuiteLevel] = 0;
$this->testSuiteTimes[$this->testSuiteLevel] = 0;
}
/**
* A testsuite ended.
*/
public function endTestSuite(TestSuite $suite): void
{
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'tests',
(string) $this->testSuiteTests[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'assertions',
(string) $this->testSuiteAssertions[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'errors',
(string) $this->testSuiteErrors[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'warnings',
(string) $this->testSuiteWarnings[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'failures',
(string) $this->testSuiteFailures[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'skipped',
(string) $this->testSuiteSkipped[$this->testSuiteLevel]
);
$this->testSuites[$this->testSuiteLevel]->setAttribute(
'time',
\sprintf('%F', $this->testSuiteTimes[$this->testSuiteLevel])
);
if ($this->testSuiteLevel > 1) {
$this->testSuiteTests[$this->testSuiteLevel - 1] += $this->testSuiteTests[$this->testSuiteLevel];
$this->testSuiteAssertions[$this->testSuiteLevel - 1] += $this->testSuiteAssertions[$this->testSuiteLevel];
$this->testSuiteErrors[$this->testSuiteLevel - 1] += $this->testSuiteErrors[$this->testSuiteLevel];
$this->testSuiteWarnings[$this->testSuiteLevel - 1] += $this->testSuiteWarnings[$this->testSuiteLevel];
$this->testSuiteFailures[$this->testSuiteLevel - 1] += $this->testSuiteFailures[$this->testSuiteLevel];
$this->testSuiteSkipped[$this->testSuiteLevel - 1] += $this->testSuiteSkipped[$this->testSuiteLevel];
$this->testSuiteTimes[$this->testSuiteLevel - 1] += $this->testSuiteTimes[$this->testSuiteLevel];
}
$this->testSuiteLevel--;
}
/**
* A test started.
*/
public function startTest(Test $test): void
{
$usesDataprovider = false;
if (\method_exists($test, 'usesDataProvider')) {
$usesDataprovider = $test->usesDataProvider();
}
$testCase = $this->document->createElement('testcase');
$testCase->setAttribute('name', $test->getName());
try {
$class = new \ReflectionClass($test);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
$e
);
}
// @codeCoverageIgnoreEnd
$methodName = $test->getName(!$usesDataprovider);
if ($class->hasMethod($methodName)) {
try {
$method = $class->getMethod($methodName);
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
$e
);
}
// @codeCoverageIgnoreEnd
$testCase->setAttribute('class', $class->getName());
$testCase->setAttribute('classname', \str_replace('\\', '.', $class->getName()));
$testCase->setAttribute('file', $class->getFileName());
$testCase->setAttribute('line', (string) $method->getStartLine());
}
$this->currentTestCase = $testCase;
}
/**
* A test ended.
*/
public function endTest(Test $test, float $time): void
{
$numAssertions = 0;
if (\method_exists($test, 'getNumAssertions')) {
$numAssertions = $test->getNumAssertions();
}
$this->testSuiteAssertions[$this->testSuiteLevel] += $numAssertions;
$this->currentTestCase->setAttribute(
'assertions',
(string) $numAssertions
);
$this->currentTestCase->setAttribute(
'time',
\sprintf('%F', $time)
);
$this->testSuites[$this->testSuiteLevel]->appendChild(
$this->currentTestCase
);
$this->testSuiteTests[$this->testSuiteLevel]++;
$this->testSuiteTimes[$this->testSuiteLevel] += $time;
$testOutput = '';
if (\method_exists($test, 'hasOutput') && \method_exists($test, 'getActualOutput')) {
$testOutput = $test->hasOutput() ? $test->getActualOutput() : '';
}
if (!empty($testOutput)) {
$systemOut = $this->document->createElement(
'system-out',
Xml::prepareString($testOutput)
);
$this->currentTestCase->appendChild($systemOut);
}
$this->currentTestCase = null;
}
/**
* Returns the XML as a string.
*/
public function getXML(): string
{
return $this->document->saveXML();
}
private function doAddFault(Test $test, \Throwable $t, string $type): void
{
if ($this->currentTestCase === null) {
return;
}
if ($test instanceof SelfDescribing) {
$buffer = $test->toString() . "\n";
} else {
$buffer = '';
}
$buffer .= TestFailure::exceptionToString($t) . "\n" .
Filter::getFilteredStacktrace($t);
$fault = $this->document->createElement(
$type,
Xml::prepareString($buffer)
);
if ($t instanceof ExceptionWrapper) {
$fault->setAttribute('type', $t->getClassName());
} else {
$fault->setAttribute('type', \get_class($t));
}
$this->currentTestCase->appendChild($fault);
}
private function doAddSkipped(): void
{
if ($this->currentTestCase === null) {
return;
}
$skipped = $this->document->createElement('skipped');
$this->currentTestCase->appendChild($skipped);
$this->testSuiteSkipped[$this->testSuiteLevel]++;
}
}
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Util\Log;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExceptionWrapper;
use PHPUnit\Framework\ExpectationFailedException;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestFailure;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;
use PHPUnit\TextUI\DefaultResultPrinter;
use PHPUnit\Util\Exception;
use PHPUnit\Util\Filter;
use SebastianBergmann\Comparator\ComparisonFailure;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class TeamCity extends DefaultResultPrinter
{
/**
* @var bool
*/
private $isSummaryTestCountPrinted = false;
/**
* @var string
*/
private $startedTestName;
/**
* @var false|int
*/
private $flowId;
public function printResult(TestResult $result): void
{
$this->printHeader($result);
$this->printFooter($result);
}
/**
* An error occurred.
*/
public function addError(Test $test, \Throwable $t, float $time): void
{
$this->printEvent(
'testFailed',
[
'name' => $test->getName(),
'message' => self::getMessage($t),
'details' => self::getDetails($t),
'duration' => self::toMilliseconds($time),
]
);
}
/**
* A warning occurred.
*/
public function addWarning(Test $test, Warning $e, float $time): void
{
$this->printEvent(
'testFailed',
[
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
'duration' => self::toMilliseconds($time),
]
);
}
/**
* A failure occurred.
*/
public function addFailure(Test $test, AssertionFailedError $e, float $time): void
{
$parameters = [
'name' => $test->getName(),
'message' => self::getMessage($e),
'details' => self::getDetails($e),
'duration' => self::toMilliseconds($time),
];
if ($e instanceof ExpectationFailedException) {
$comparisonFailure = $e->getComparisonFailure();
if ($comparisonFailure instanceof ComparisonFailure) {
$expectedString = $comparisonFailure->getExpectedAsString();
if ($expectedString === null || empty($expectedString)) {
$expectedString = self::getPrimitiveValueAsString($comparisonFailure->getExpected());
}
$actualString = $comparisonFailure->getActualAsString();
if ($actualString === null || empty($actualString)) {
$actualString = self::getPrimitiveValueAsString($comparisonFailure->getActual());
}
if ($actualString !== null && $expectedString !== null) {
$parameters['type'] = 'comparisonFailure';
$parameters['actual'] = $actualString;
$parameters['expected'] = $expectedString;
}
}
}
$this->printEvent('testFailed', $parameters);
}
/**
* Incomplete test.
*/
public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
{
$this->printIgnoredTest($test->getName(), $t, $time);
}
/**
* Risky test.
*/
public function addRiskyTest(Test $test, \Throwable $t, float $time): void
{
$this->addError($test, $t, $time);
}
/**
* Skipped test.
*/
public function addSkippedTest(Test $test, \Throwable $t, float $time): void
{
$testName = $test->getName();
if ($this->startedTestName !== $testName) {
$this->startTest($test);
$this->printIgnoredTest($testName, $t, $time);
$this->endTest($test, $time);
} else {
$this->printIgnoredTest($testName, $t, $time);
}
}
public function printIgnoredTest(string $testName, \Throwable $t, float $time): void
{
$this->printEvent(
'testIgnored',
[
'name' => $testName,
'message' => self::getMessage($t),
'details' => self::getDetails($t),
'duration' => self::toMilliseconds($time),
]
);
}
/**
* A testsuite started.
*/
public function startTestSuite(TestSuite $suite): void
{
if (\stripos(\ini_get('disable_functions'), 'getmypid') === false) {
$this->flowId = \getmypid();
} else {
$this->flowId = false;
}
if (!$this->isSummaryTestCountPrinted) {
$this->isSummaryTestCountPrinted = true;
$this->printEvent(
'testCount',
['count' => \count($suite)]
);
}
$suiteName = $suite->getName();
if (empty($suiteName)) {
return;
}
$parameters = ['name' => $suiteName];
if (\class_exists($suiteName, false)) {
$fileName = self::getFileName($suiteName);
$parameters['locationHint'] = "php_qn://{$fileName}::\\{$suiteName}";
} else {
$split = \explode('::', $suiteName);
if (\count($split) === 2 && \class_exists($split[0]) && \method_exists($split[0], $split[1])) {
$fileName = self::getFileName($split[0]);
$parameters['locationHint'] = "php_qn://{$fileName}::\\{$suiteName}";
$parameters['name'] = $split[1];
}
}
$this->printEvent('testSuiteStarted', $parameters);
}
/**
* A testsuite ended.
*/
public function endTestSuite(TestSuite $suite): void
{
$suiteName = $suite->getName();
if (empty($suiteName)) {
return;
}
$parameters = ['name' => $suiteName];
if (!\class_exists($suiteName, false)) {
$split = \explode('::', $suiteName);
if (\count($split) === 2 && \class_exists($split[0]) && \method_exists($split[0], $split[1])) {
$parameters['name'] = $split[1];
}
}
$this->printEvent('testSuiteFinished', $parameters);
}
/**
* A test started.
*/
public function startTest(Test $test): void
{
$testName = $test->getName();
$this->startedTestName = $testName;
$params = ['name' => $testName];
if ($test instanceof TestCase) {
$className = \get_class($test);
$fileName = self::getFileName($className);
$params['locationHint'] = "php_qn://{$fileName}::\\{$className}::{$testName}";
}
$this->printEvent('testStarted', $params);
}
/**
* A test ended.
*/
public function endTest(Test $test, float $time): void
{
parent::endTest($test, $time);
$this->printEvent(
'testFinished',
[
'name' => $test->getName(),
'duration' => self::toMilliseconds($time),
]
);
}
protected function writeProgress(string $progress): void
{
}
private function printEvent(string $eventName, array $params = []): void
{
$this->write("\n##teamcity[{$eventName}");
if ($this->flowId) {
$params['flowId'] = $this->flowId;
}
foreach ($params as $key => $value) {
$escapedValue = self::escapeValue((string) $value);
$this->write(" {$key}='{$escapedValue}'");
}
$this->write("]\n");
}
private static function getMessage(\Throwable $t): string
{
$message = '';
if ($t instanceof ExceptionWrapper) {
if ($t->getClassName() !== '') {
$message .= $t->getClassName();
}
if ($message !== '' && $t->getMessage() !== '') {
$message .= ' : ';
}
}
return $message . $t->getMessage();
}
private static function getDetails(\Throwable $t): string
{
$stackTrace = Filter::getFilteredStacktrace($t);
$previous = $t instanceof ExceptionWrapper ? $t->getPreviousWrapped() : $t->getPrevious();
while ($previous) {
$stackTrace .= "\nCaused by\n" .
TestFailure::exceptionToString($previous) . "\n" .
Filter::getFilteredStacktrace($previous);
$previous = $previous instanceof ExceptionWrapper ?
$previous->getPreviousWrapped() : $previous->getPrevious();
}
return ' ' . \str_replace("\n", "\n ", $stackTrace);
}
private static function getPrimitiveValueAsString($value): ?string
{
if ($value === null) {
return 'null';
}
if (\is_bool($value)) {
return $value ? 'true' : 'false';
}
if (\is_scalar($value)) {
return \print_r($value, true);
}
return null;
}
private static function escapeValue(string $text): string
{
return \str_replace(
['|', "'", "\n", "\r", ']', '['],
['||', "|'", '|n', '|r', '|]', '|['],
$text
);
}
/**
* @param string $className
*/
private static function getFileName($className): string
{
try {
return (new \ReflectionClass($className))->getFileName();
// @codeCoverageIgnoreStart
} catch (\ReflectionException $e) {
throw new Exception(
$e->getMessage(),
(int) $e->getCode(),
$e
);
}
// @codeCoverageIgnoreEnd
}
/**
* @param float $time microseconds
*/
private static function toMilliseconds(float $time): int
{
return (int) \round($time * 1000);
}
}
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 1.0.1 - 2016-08-06
### Fixed
- Make spacing consistent in phpdoc annotations php-fig/cache#9 - chalasr
- Fix grammar in phpdoc annotations php-fig/cache#10 - chalasr
- Be more specific in docblocks that `getItems()` and `deleteItems()` take an array of strings (`string[]`) compared to just `array` php-fig/cache#8 - GrahamCampbell
- For `expiresAt()` and `expiresAfter()` in CacheItemInterface fix docblock to specify null as a valid parameters as well as an implementation of DateTimeInterface php-fig/cache#7 - GrahamCampbell
## 1.0.0 - 2015-12-11
Initial stable release; reflects accepted PSR-6 specification
Copyright (c) 2015 PHP Framework Interoperability Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
PSR Cache
=========
This repository holds all interfaces defined by
[PSR-6](http://www.php-fig.org/psr/psr-6/).
Note that this is not a Cache implementation of its own. It is merely an
interface that describes a Cache implementation. See the specification for more
details.
{
"name": "psr/cache",
"description": "Common interface for caching libraries",
"keywords": ["psr", "psr-6", "cache"],
"license": "MIT",
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"require": {
"php": ">=5.3.0"
},
"autoload": {
"psr-4": {
"Psr\\Cache\\": "src/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}
<?php
namespace Psr\Cache;
/**
* Exception interface for all exceptions thrown by an Implementing Library.
*/
interface CacheException
{
}
<?php
namespace Psr\Cache;
/**
* CacheItemInterface defines an interface for interacting with objects inside a cache.
*
* Each Item object MUST be associated with a specific key, which can be set
* according to the implementing system and is typically passed by the
* Cache\CacheItemPoolInterface object.
*
* The Cache\CacheItemInterface object encapsulates the storage and retrieval of
* cache items. Each Cache\CacheItemInterface is generated by a
* Cache\CacheItemPoolInterface object, which is responsible for any required
* setup as well as associating the object with a unique Key.
* Cache\CacheItemInterface objects MUST be able to store and retrieve any type
* of PHP value defined in the Data section of the specification.
*
* Calling Libraries MUST NOT instantiate Item objects themselves. They may only
* be requested from a Pool object via the getItem() method. Calling Libraries
* SHOULD NOT assume that an Item created by one Implementing Library is
* compatible with a Pool from another Implementing Library.
*/
interface CacheItemInterface
{
/**
* Returns the key for the current cache item.
*
* The key is loaded by the Implementing Library, but should be available to
* the higher level callers when needed.
*
* @return string
* The key string for this cache item.
*/
public function getKey();
/**
* Retrieves the value of the item from the cache associated with this object's key.
*
* The value returned must be identical to the value originally stored by set().
*
* If isHit() returns false, this method MUST return null. Note that null
* is a legitimate cached value, so the isHit() method SHOULD be used to
* differentiate between "null value was found" and "no value was found."
*
* @return mixed
* The value corresponding to this cache item's key, or null if not found.
*/
public function get();
/**
* Confirms if the cache item lookup resulted in a cache hit.
*
* Note: This method MUST NOT have a race condition between calling isHit()
* and calling get().
*
* @return bool
* True if the request resulted in a cache hit. False otherwise.
*/
public function isHit();
/**
* Sets the value represented by this cache item.
*
* The $value argument may be any item that can be serialized by PHP,
* although the method of serialization is left up to the Implementing
* Library.
*
* @param mixed $value
* The serializable value to be stored.
*
* @return static
* The invoked object.
*/
public function set($value);
/**
* Sets the expiration time for this cache item.
*
* @param \DateTimeInterface|null $expiration
* The point in time after which the item MUST be considered expired.
* If null is passed explicitly, a default value MAY be used. If none is set,
* the value should be stored permanently or for as long as the
* implementation allows.
*
* @return static
* The called object.
*/
public function expiresAt($expiration);
/**
* Sets the expiration time for this cache item.
*
* @param int|\DateInterval|null $time
* The period of time from the present after which the item MUST be considered
* expired. An integer parameter is understood to be the time in seconds until
* expiration. If null is passed explicitly, a default value MAY be used.
* If none is set, the value should be stored permanently or for as long as the
* implementation allows.
*
* @return static
* The called object.
*/
public function expiresAfter($time);
}
<?php
namespace Psr\Cache;
/**
* CacheItemPoolInterface generates CacheItemInterface objects.
*
* The primary purpose of Cache\CacheItemPoolInterface is to accept a key from
* the Calling Library and return the associated Cache\CacheItemInterface object.
* It is also the primary point of interaction with the entire cache collection.
* All configuration and initialization of the Pool is left up to an
* Implementing Library.
*/
interface CacheItemPoolInterface
{
/**
* Returns a Cache Item representing the specified key.
*
* This method must always return a CacheItemInterface object, even in case of
* a cache miss. It MUST NOT return null.
*
* @param string $key
* The key for which to return the corresponding Cache Item.
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return CacheItemInterface
* The corresponding Cache Item.
*/
public function getItem($key);
/**
* Returns a traversable set of cache items.
*
* @param string[] $keys
* An indexed array of keys of items to retrieve.
*
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return array|\Traversable
* A traversable collection of Cache Items keyed by the cache keys of
* each item. A Cache item will be returned for each key, even if that
* key is not found. However, if no keys are specified then an empty
* traversable MUST be returned instead.
*/
public function getItems(array $keys = array());
/**
* Confirms if the cache contains specified cache item.
*
* Note: This method MAY avoid retrieving the cached value for performance reasons.
* This could result in a race condition with CacheItemInterface::get(). To avoid
* such situation use CacheItemInterface::isHit() instead.
*
* @param string $key
* The key for which to check existence.
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if item exists in the cache, false otherwise.
*/
public function hasItem($key);
/**
* Deletes all items in the pool.
*
* @return bool
* True if the pool was successfully cleared. False if there was an error.
*/
public function clear();
/**
* Removes the item from the pool.
*
* @param string $key
* The key to delete.
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the item was successfully removed. False if there was an error.
*/
public function deleteItem($key);
/**
* Removes multiple items from the pool.
*
* @param string[] $keys
* An array of keys that should be removed from the pool.
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\InvalidArgumentException
* MUST be thrown.
*
* @return bool
* True if the items were successfully removed. False if there was an error.
*/
public function deleteItems(array $keys);
/**
* Persists a cache item immediately.
*
* @param CacheItemInterface $item
* The cache item to save.
*
* @return bool
* True if the item was successfully persisted. False if there was an error.
*/
public function save(CacheItemInterface $item);
/**
* Sets a cache item to be persisted later.
*
* @param CacheItemInterface $item
* The cache item to save.
*
* @return bool
* False if the item could not be queued or if a commit was attempted and failed. True otherwise.
*/
public function saveDeferred(CacheItemInterface $item);
/**
* Persists any deferred cache items.
*
* @return bool
* True if all not-yet-saved items were successfully saved or there were none. False otherwise.
*/
public function commit();
}
<?php
namespace Psr\Cache;
/**
* Exception interface for invalid cache arguments.
*
* Any time an invalid argument is passed into a method it must throw an
* exception class which implements Psr\Cache\InvalidArgumentException.
*/
interface InvalidArgumentException extends CacheException
{
}
Copyright (c) 2012 PHP Framework Interoperability Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
<?php
namespace Psr\Log;
/**
* This is a simple Logger implementation that other Loggers can inherit from.
*
* It simply delegates all log-level-specific methods to the `log` method to
* reduce boilerplate code that a simple Logger that does the same thing with
* messages regardless of the error level has to implement.
*/
abstract class AbstractLogger implements LoggerInterface
{
/**
* System is unusable.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
}
<?php
namespace Psr\Log;
class InvalidArgumentException extends \InvalidArgumentException
{
}
<?php
namespace Psr\Log;
/**
* Describes log levels.
*/
class LogLevel
{
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
}
<?php
namespace Psr\Log;
/**
* Describes a logger-aware instance.
*/
interface LoggerAwareInterface
{
/**
* Sets a logger instance on the object.
*
* @param LoggerInterface $logger
*
* @return void
*/
public function setLogger(LoggerInterface $logger);
}
<?php
namespace Psr\Log;
/**
* Basic Implementation of LoggerAwareInterface.
*/
trait LoggerAwareTrait
{
/**
* The logger instance.
*
* @var LoggerInterface|null
*/
protected $logger;
/**
* Sets a logger.
*
* @param LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
}
<?php
namespace Psr\Log;
/**
* Describes a logger instance.
*
* The message MUST be a string or object implementing __toString().
*
* The message MAY contain placeholders in the form: {foo} where foo
* will be replaced by the context data in key "foo".
*
* The context array can contain arbitrary data. The only assumption that
* can be made by implementors is that if an Exception instance is given
* to produce a stack trace, it MUST be in a key named "exception".
*
* See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
* for the full interface specification.
*/
interface LoggerInterface
{
/**
* System is unusable.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function emergency($message, array $context = array());
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function alert($message, array $context = array());
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function critical($message, array $context = array());
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function error($message, array $context = array());
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function warning($message, array $context = array());
/**
* Normal but significant events.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function notice($message, array $context = array());
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function info($message, array $context = array());
/**
* Detailed debug information.
*
* @param string $message
* @param mixed[] $context
*
* @return void
*/
public function debug($message, array $context = array());
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param mixed[] $context
*
* @return void
*
* @throws \Psr\Log\InvalidArgumentException
*/
public function log($level, $message, array $context = array());
}
<?php
namespace Psr\Log;
/**
* This is a simple Logger trait that classes unable to extend AbstractLogger
* (because they extend another class, etc) can include.
*
* It simply delegates all log-level-specific methods to the `log` method to
* reduce boilerplate code that a simple Logger that does the same thing with
* messages regardless of the error level has to implement.
*/
trait LoggerTrait
{
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*
* @throws \Psr\Log\InvalidArgumentException
*/
abstract public function log($level, $message, array $context = array());
}
<?php
namespace Psr\Log;
/**
* This Logger can be used to avoid conditional log calls.
*
* Logging should always be optional, and if no logger is provided to your
* library creating a NullLogger instance to have something to throw logs at
* is a good way to avoid littering your code with `if ($this->logger) { }`
* blocks.
*/
class NullLogger extends AbstractLogger
{
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*
* @throws \Psr\Log\InvalidArgumentException
*/
public function log($level, $message, array $context = array())
{
// noop
}
}
<?php
namespace Psr\Log\Test;
/**
* This class is internal and does not follow the BC promise.
*
* Do NOT use this class in any way.
*
* @internal
*/
class DummyTest
{
public function __toString()
{
return 'DummyTest';
}
}
<?php
namespace Psr\Log\Test;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use PHPUnit\Framework\TestCase;
/**
* Provides a base test class for ensuring compliance with the LoggerInterface.
*
* Implementors can extend the class and implement abstract methods to run this
* as part of their test suite.
*/
abstract class LoggerInterfaceTest extends TestCase
{
/**
* @return LoggerInterface
*/
abstract public function getLogger();
/**
* This must return the log messages in order.
*
* The simple formatting of the messages is: "<LOG LEVEL> <MESSAGE>".
*
* Example ->error('Foo') would yield "error Foo".
*
* @return string[]
*/
abstract public function getLogs();
public function testImplements()
{
$this->assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger());
}
/**
* @dataProvider provideLevelsAndMessages
*/
public function testLogsAtAllLevels($level, $message)
{
$logger = $this->getLogger();
$logger->{$level}($message, array('user' => 'Bob'));
$logger->log($level, $message, array('user' => 'Bob'));
$expected = array(
$level.' message of level '.$level.' with context: Bob',
$level.' message of level '.$level.' with context: Bob',
);
$this->assertEquals($expected, $this->getLogs());
}
public function provideLevelsAndMessages()
{
return array(
LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
);
}
/**
* @expectedException \Psr\Log\InvalidArgumentException
*/
public function testThrowsOnInvalidLevel()
{
$logger = $this->getLogger();
$logger->log('invalid level', 'Foo');
}
public function testContextReplacement()
{
$logger = $this->getLogger();
$logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
$expected = array('info {Message {nothing} Bob Bar a}');
$this->assertEquals($expected, $this->getLogs());
}
public function testObjectCastToString()
{
if (method_exists($this, 'createPartialMock')) {
$dummy = $this->createPartialMock('Psr\Log\Test\DummyTest', array('__toString'));
} else {
$dummy = $this->getMock('Psr\Log\Test\DummyTest', array('__toString'));
}
$dummy->expects($this->once())
->method('__toString')
->will($this->returnValue('DUMMY'));
$this->getLogger()->warning($dummy);
$expected = array('warning DUMMY');
$this->assertEquals($expected, $this->getLogs());
}
public function testContextCanContainAnything()
{
$closed = fopen('php://memory', 'r');
fclose($closed);
$context = array(
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => array('with object' => new DummyTest),
'object' => new \DateTime,
'resource' => fopen('php://memory', 'r'),
'closed' => $closed,
);
$this->getLogger()->warning('Crazy context data', $context);
$expected = array('warning Crazy context data');
$this->assertEquals($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->getLogger();
$logger->warning('Random message', array('exception' => 'oops'));
$logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
$expected = array(
'warning Random message',
'critical Uncaught Exception!'
);
$this->assertEquals($expected, $this->getLogs());
}
}
<?php
namespace Psr\Log\Test;
use Psr\Log\AbstractLogger;
/**
* Used for testing purposes.
*
* It records all records and gives you access to them for verification.
*
* @method bool hasEmergency($record)
* @method bool hasAlert($record)
* @method bool hasCritical($record)
* @method bool hasError($record)
* @method bool hasWarning($record)
* @method bool hasNotice($record)
* @method bool hasInfo($record)
* @method bool hasDebug($record)
*
* @method bool hasEmergencyRecords()
* @method bool hasAlertRecords()
* @method bool hasCriticalRecords()
* @method bool hasErrorRecords()
* @method bool hasWarningRecords()
* @method bool hasNoticeRecords()
* @method bool hasInfoRecords()
* @method bool hasDebugRecords()
*
* @method bool hasEmergencyThatContains($message)
* @method bool hasAlertThatContains($message)
* @method bool hasCriticalThatContains($message)
* @method bool hasErrorThatContains($message)
* @method bool hasWarningThatContains($message)
* @method bool hasNoticeThatContains($message)
* @method bool hasInfoThatContains($message)
* @method bool hasDebugThatContains($message)
*
* @method bool hasEmergencyThatMatches($message)
* @method bool hasAlertThatMatches($message)
* @method bool hasCriticalThatMatches($message)
* @method bool hasErrorThatMatches($message)
* @method bool hasWarningThatMatches($message)
* @method bool hasNoticeThatMatches($message)
* @method bool hasInfoThatMatches($message)
* @method bool hasDebugThatMatches($message)
*
* @method bool hasEmergencyThatPasses($message)
* @method bool hasAlertThatPasses($message)
* @method bool hasCriticalThatPasses($message)
* @method bool hasErrorThatPasses($message)
* @method bool hasWarningThatPasses($message)
* @method bool hasNoticeThatPasses($message)
* @method bool hasInfoThatPasses($message)
* @method bool hasDebugThatPasses($message)
*/
class TestLogger extends AbstractLogger
{
/**
* @var array
*/
public $records = [];
public $recordsByLevel = [];
/**
* @inheritdoc
*/
public function log($level, $message, array $context = [])
{
$record = [
'level' => $level,
'message' => $message,
'context' => $context,
];
$this->recordsByLevel[$record['level']][] = $record;
$this->records[] = $record;
}
public function hasRecords($level)
{
return isset($this->recordsByLevel[$level]);
}
public function hasRecord($record, $level)
{
if (is_string($record)) {
$record = ['message' => $record];
}
return $this->hasRecordThatPasses(function ($rec) use ($record) {
if ($rec['message'] !== $record['message']) {
return false;
}
if (isset($record['context']) && $rec['context'] !== $record['context']) {
return false;
}
return true;
}, $level);
}
public function hasRecordThatContains($message, $level)
{
return $this->hasRecordThatPasses(function ($rec) use ($message) {
return strpos($rec['message'], $message) !== false;
}, $level);
}
public function hasRecordThatMatches($regex, $level)
{
return $this->hasRecordThatPasses(function ($rec) use ($regex) {
return preg_match($regex, $rec['message']) > 0;
}, $level);
}
public function hasRecordThatPasses(callable $predicate, $level)
{
if (!isset($this->recordsByLevel[$level])) {
return false;
}
foreach ($this->recordsByLevel[$level] as $i => $rec) {
if (call_user_func($predicate, $rec, $i)) {
return true;
}
}
return false;
}
public function __call($method, $args)
{
if (preg_match('/(.*)(Debug|Info|Notice|Warning|Error|Critical|Alert|Emergency)(.*)/', $method, $matches) > 0) {
$genericMethod = $matches[1] . ('Records' !== $matches[3] ? 'Record' : '') . $matches[3];
$level = strtolower($matches[2]);
if (method_exists($this, $genericMethod)) {
$args[] = $level;
return call_user_func_array([$this, $genericMethod], $args);
}
}
throw new \BadMethodCallException('Call to undefined method ' . get_class($this) . '::' . $method . '()');
}
public function reset()
{
$this->records = [];
$this->recordsByLevel = [];
}
}
PSR Log
=======
This repository holds all interfaces/classes/traits related to
[PSR-3](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md).
Note that this is not a logger of its own. It is merely an interface that
describes a logger. See the specification for more details.
Installation
------------
```bash
composer require psr/log
```
Usage
-----
If you need a logger, you can use the interface like this:
```php
<?php
use Psr\Log\LoggerInterface;
class Foo
{
private $logger;
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
public function doSomething()
{
if ($this->logger) {
$this->logger->info('Doing work');
}
try {
$this->doSomethingElse();
} catch (Exception $exception) {
$this->logger->error('Oh no!', array('exception' => $exception));
}
// do something useful
}
}
```
You can then pick one of the implementations of the interface to get a logger.
If you want to implement the interface, you can require this package and
implement `Psr\Log\LoggerInterface` in your code. Please read the
[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md)
for details.
{
"name": "psr/log",
"description": "Common interface for logging libraries",
"keywords": ["psr", "psr-3", "log"],
"homepage": "https://github.com/php-fig/log",
"license": "MIT",
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"require": {
"php": ">=5.3.0"
},
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
}
}
<?php declare(strict_types=1);
/*
* This file is part of PHP Copy/Paste Detector (PHPCPD).
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\PHPCPD\Log;
use const ENT_COMPAT;
use function file_put_contents;
use function function_exists;
use function htmlspecialchars;
use function mb_convert_encoding;
use function ord;
use function preg_replace;
use function strlen;
use function utf8_encode;
use DOMDocument;
use SebastianBergmann\PHPCPD\CodeCloneMap;
abstract class AbstractXmlLogger
{
/**
* @var DOMDocument
*/
protected $document;
/**
* @var string
*/
private $filename;
public function __construct(string $filename)
{
$this->document = new DOMDocument('1.0', 'UTF-8');
$this->document->formatOutput = true;
$this->filename = $filename;
}
abstract public function processClones(CodeCloneMap $clones);
protected function flush(): void
{
file_put_contents($this->filename, $this->document->saveXML());
}
protected function convertToUtf8(string $string): string
{
if (!$this->isUtf8($string)) {
if (function_exists('mb_convert_encoding')) {
$string = mb_convert_encoding($string, 'UTF-8');
} else {
$string = utf8_encode($string);
}
}
return $string;
}
protected function isUtf8(string $string): bool
{
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
if (ord($string[$i]) < 0x80) {
$n = 0;
} elseif ((ord($string[$i]) & 0xE0) === 0xC0) {
$n = 1;
} elseif ((ord($string[$i]) & 0xF0) === 0xE0) {
$n = 2;
} elseif ((ord($string[$i]) & 0xF0) === 0xF0) {
$n = 3;
} else {
return false;
}
for ($j = 0; $j < $n; $j++) {
if ((++$i === $length) || ((ord($string[$i]) & 0xC0) !== 0x80)) {
return false;
}
}
}
return true;
}
protected function escapeForXml(string $string): string
{
$string = $this->convertToUtf8($string);
$string = preg_replace(
'/[^\x09\x0A\x0D\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]/u',
"\xEF\xBF\xBD",
$string
);
return htmlspecialchars($string, ENT_COMPAT, 'UTF-8');
}
}
<?php declare(strict_types=1);
/*
* This file is part of PHP Copy/Paste Detector (PHPCPD).
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\PHPCPD\Log;
use SebastianBergmann\PHPCPD\CodeCloneMap;
final class PMD extends AbstractXmlLogger
{
/** @noinspection UnusedFunctionResultInspection */
public function processClones(CodeCloneMap $clones): void
{
$cpd = $this->document->createElement('pmd-cpd');
$this->document->appendChild($cpd);
foreach ($clones as $clone) {
$duplication = $cpd->appendChild(
$this->document->createElement('duplication')
);
$duplication->setAttribute('lines', (string) $clone->numberOfLines());
$duplication->setAttribute('tokens', (string) $clone->numberOfTokens());
foreach ($clone->files() as $codeCloneFile) {
$file = $duplication->appendChild(
$this->document->createElement('file')
);
$file->setAttribute('path', $codeCloneFile->name());
$file->setAttribute('line', (string) $codeCloneFile->startLine());
}
$duplication->appendChild(
$this->document->createElement(
'codefragment',
$this->escapeForXml($clone->lines())
)
);
}
$this->flush();
}
}
<?php declare(strict_types=1);
/*
* This file is part of PHP Copy/Paste Detector (PHPCPD).
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace SebastianBergmann\PHPCPD\Log;
use const PHP_EOL;
use function count;
use function printf;
use SebastianBergmann\PHPCPD\CodeCloneMap;
final class Text
{
public function printResult(CodeCloneMap $clones, bool $verbose): void
{
if (count($clones) > 0) {
printf(
'Found %d clones with %d duplicated lines in %d files:' . PHP_EOL . PHP_EOL,
count($clones),
$clones->numberOfDuplicatedLines(),
$clones->numberOfFilesWithClones()
);
}
foreach ($clones as $clone) {
$firstOccurrence = true;
foreach ($clone->files() as $file) {
printf(
' %s%s:%d-%d%s' . PHP_EOL,
$firstOccurrence ? '- ' : ' ',
$file->name(),
$file->startLine(),
$file->startLine() + $clone->numberOfLines(),
$firstOccurrence ? ' (' . $clone->numberOfLines() . ' lines)' : ''
);
$firstOccurrence = false;
}
if ($verbose) {
print PHP_EOL . $clone->lines(' ');
}
print PHP_EOL;
}
if ($clones->isEmpty()) {
print 'No clones found.' . PHP_EOL . PHP_EOL;
return;
}
printf(
'%s duplicated lines out of %d total lines of code.' . PHP_EOL .
'Average size of duplication is %d lines, largest clone has %d of lines' . PHP_EOL . PHP_EOL,
$clones->percentage(),
$clones->numberOfLines(),
$clones->averageSize(),
$clones->largestSize()
);
}
}
<?php
$phpCodeSnifferConfig = array (
'installed_paths' => '../../magento/magento-coding-standard,../../phpcompatibility/php-compatibility',
)
?>
\ No newline at end of file
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Log;
use Symfony\Component\HttpFoundation\Request;
/**
* DebugLoggerInterface.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface DebugLoggerInterface
{
/**
* Returns an array of logs.
*
* A log is an array with the following mandatory keys:
* timestamp, message, priority, and priorityName.
* It can also have an optional context key containing an array.
*
* @param Request|null $request The request to get logs for
*
* @return array An array of logs
*/
public function getLogs(/* Request $request = null */);
/**
* Returns the number of errors.
*
* @param Request|null $request The request to count logs for
*
* @return int The number of errors
*/
public function countErrors(/* Request $request = null */);
/**
* Removes all log records.
*/
public function clear();
}
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Log;
use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LogLevel;
/**
* Minimalist PSR-3 logger designed to write in stderr or any other stream.
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class Logger extends AbstractLogger
{
private const LEVELS = [
LogLevel::DEBUG => 0,
LogLevel::INFO => 1,
LogLevel::NOTICE => 2,
LogLevel::WARNING => 3,
LogLevel::ERROR => 4,
LogLevel::CRITICAL => 5,
LogLevel::ALERT => 6,
LogLevel::EMERGENCY => 7,
];
private $minLevelIndex;
private $formatter;
private $handle;
public function __construct(string $minLevel = null, $output = null, callable $formatter = null)
{
if (null === $minLevel) {
$minLevel = null === $output || 'php://stdout' === $output || 'php://stderr' === $output ? LogLevel::ERROR : LogLevel::WARNING;
if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
switch ((int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'])) {
case -1: $minLevel = LogLevel::ERROR; break;
case 1: $minLevel = LogLevel::NOTICE; break;
case 2: $minLevel = LogLevel::INFO; break;
case 3: $minLevel = LogLevel::DEBUG; break;
}
}
}
if (!isset(self::LEVELS[$minLevel])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel));
}
$this->minLevelIndex = self::LEVELS[$minLevel];
$this->formatter = $formatter ?: [$this, 'format'];
if ($output && false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) {
throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output));
}
}
/**
* {@inheritdoc}
*
* @return void
*/
public function log($level, $message, array $context = [])
{
if (!isset(self::LEVELS[$level])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
}
if (self::LEVELS[$level] < $this->minLevelIndex) {
return;
}
$formatter = $this->formatter;
if ($this->handle) {
@fwrite($this->handle, $formatter($level, $message, $context));
} else {
error_log($formatter($level, $message, $context, false));
}
}
private function format(string $level, string $message, array $context, bool $prefixDate = true): string
{
if (str_contains($message, '{')) {
$replacements = [];
foreach ($context as $key => $val) {
if (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
$replacements["{{$key}}"] = $val;
} elseif ($val instanceof \DateTimeInterface) {
$replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
} elseif (\is_object($val)) {
$replacements["{{$key}}"] = '[object '.\get_class($val).']';
} else {
$replacements["{{$key}}"] = '['.\gettype($val).']';
}
}
$message = strtr($message, $replacements);
}
$log = sprintf('[%s] %s', $level, $message).\PHP_EOL;
if ($prefixDate) {
$log = date(\DateTime::RFC3339).' '.$log;
}
return $log;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment