From 375cfd90e2550c845a6f32327e611799556975e8 Mon Sep 17 00:00:00 2001 From: thomas Date: Tue, 28 Apr 2009 10:23:49 +0000 Subject: [PATCH 001/311] [DOCUMENTATION] English: - fixed title tags git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@15234 44c647ce-9c0f-0410-b52a-842ac1e357ba --- .coveralls.yml | 3 + .gitattributes | 6 + .gitignore | 14 + .php_cs | 43 ++ .travis.yml | 35 + CONTRIBUTING.md | 229 +++++++ LICENSE.txt | 27 + README.md | 9 + composer.json | 49 ++ phpunit.xml.dist | 62 ++ phpunit.xml.travis | 64 ++ src/Backend.php | 228 +++++++ src/Backend/Apc.php | 354 ++++++++++ src/Backend/ExtendedInterface.php | 125 ++++ src/Backend/File.php | 1003 ++++++++++++++++++++++++++++ src/Backend/Interface.php | 98 +++ src/Backend/Memcached.php | 501 ++++++++++++++ src/Backend/Sqlite.php | 678 +++++++++++++++++++ src/Backend/Test.php | 269 ++++++++ src/Backend/TwoLevels.php | 501 ++++++++++++++ src/Backend/Xcache.php | 215 ++++++ src/Backend/ZendPlatform.php | 316 +++++++++ src/Backend/ZendServer.php | 208 ++++++ src/Backend/ZendServer/Disk.php | 101 +++ src/Backend/ZendServer/ShMem.php | 101 +++ src/Core.php | 660 ++++++++++++++++++ src/Exception.php | 31 + src/Frontend/Class.php | 242 +++++++ src/Frontend/File.php | 208 ++++++ src/Frontend/Function.php | 130 ++++ src/Frontend/Output.php | 105 +++ src/Frontend/Page.php | 401 +++++++++++ test/AllTests.php | 204 ++++++ test/ApcBackendTest.php | 117 ++++ test/ClassFrontendTest.php | 222 ++++++ test/CommonBackendTest.php | 270 ++++++++ test/CommonExtendedBackendTest.php | 194 ++++++ test/CoreTest.php | 441 ++++++++++++ test/FactoryException.php | 35 + test/FactoryTest.php | 102 +++ test/FileBackendTest.php | 111 +++ test/FileFrontendTest.php | 205 ++++++ test/FunctionFrontendTest.php | 159 +++++ test/MemcachedBackendTest.php | 141 ++++ test/OutputFrontendTest.php | 74 ++ test/PageFrontendTest.php | 187 ++++++ test/SkipTests.php | 85 +++ test/SqliteBackendTest.php | 97 +++ test/TwoLevelsBackendTest.php | 82 +++ test/XcacheBackendTest.php | 106 +++ test/ZendPlatformBackendTest.php | 81 +++ test/ZendServerDiskTest.php | 102 +++ test/ZendServerShMemTest.php | 101 +++ test/bootstrap.php | 34 + 54 files changed, 10166 insertions(+) create mode 100644 .coveralls.yml create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .php_cs create mode 100644 .travis.yml create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 composer.json create mode 100644 phpunit.xml.dist create mode 100644 phpunit.xml.travis create mode 100644 src/Backend.php create mode 100644 src/Backend/Apc.php create mode 100644 src/Backend/ExtendedInterface.php create mode 100644 src/Backend/File.php create mode 100644 src/Backend/Interface.php create mode 100644 src/Backend/Memcached.php create mode 100644 src/Backend/Sqlite.php create mode 100644 src/Backend/Test.php create mode 100644 src/Backend/TwoLevels.php create mode 100644 src/Backend/Xcache.php create mode 100644 src/Backend/ZendPlatform.php create mode 100755 src/Backend/ZendServer.php create mode 100755 src/Backend/ZendServer/Disk.php create mode 100755 src/Backend/ZendServer/ShMem.php create mode 100644 src/Core.php create mode 100644 src/Exception.php create mode 100644 src/Frontend/Class.php create mode 100644 src/Frontend/File.php create mode 100644 src/Frontend/Function.php create mode 100644 src/Frontend/Output.php create mode 100644 src/Frontend/Page.php create mode 100644 test/AllTests.php create mode 100644 test/ApcBackendTest.php create mode 100644 test/ClassFrontendTest.php create mode 100644 test/CommonBackendTest.php create mode 100644 test/CommonExtendedBackendTest.php create mode 100644 test/CoreTest.php create mode 100644 test/FactoryException.php create mode 100644 test/FactoryTest.php create mode 100644 test/FileBackendTest.php create mode 100644 test/FileFrontendTest.php create mode 100644 test/FunctionFrontendTest.php create mode 100644 test/MemcachedBackendTest.php create mode 100644 test/OutputFrontendTest.php create mode 100644 test/PageFrontendTest.php create mode 100644 test/SkipTests.php create mode 100644 test/SqliteBackendTest.php create mode 100644 test/TwoLevelsBackendTest.php create mode 100644 test/XcacheBackendTest.php create mode 100644 test/ZendPlatformBackendTest.php create mode 100755 test/ZendServerDiskTest.php create mode 100755 test/ZendServerShMemTest.php create mode 100644 test/bootstrap.php diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 000000000..53bda829c --- /dev/null +++ b/.coveralls.yml @@ -0,0 +1,3 @@ +coverage_clover: clover.xml +json_path: coveralls-upload.json +src_dir: src diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..85dc9a8c8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +/test export-ignore +/vendor export-ignore +.gitattributes export-ignore +.gitignore export-ignore +.travis.yml export-ignore +.php_cs export-ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..4cac0a218 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.buildpath +.DS_Store +.idea +.project +.settings/ +.*.sw* +.*.un~ +nbproject +tmp/ + +clover.xml +coveralls-upload.json +phpunit.xml +vendor diff --git a/.php_cs b/.php_cs new file mode 100644 index 000000000..bf4b799f3 --- /dev/null +++ b/.php_cs @@ -0,0 +1,43 @@ +notPath('TestAsset') + ->notPath('_files') + ->filter(function (SplFileInfo $file) { + if (strstr($file->getPath(), 'compatibility')) { + return false; + } + }); +$config = Symfony\CS\Config\Config::create(); +$config->level(null); +$config->fixers( + array( + 'braces', + 'duplicate_semicolon', + 'elseif', + 'empty_return', + 'encoding', + 'eof_ending', + 'function_call_space', + 'function_declaration', + 'indentation', + 'join_function', + 'line_after_namespace', + 'linefeed', + 'lowercase_keywords', + 'parenthesis', + 'multiple_use', + 'method_argument_space', + 'object_operator', + 'php_closing_tag', + 'psr0', + 'remove_lines_between_uses', + 'short_tag', + 'standardize_not_equal', + 'trailing_spaces', + 'unused_use', + 'visibility', + 'whitespacy_lines', + ) +); +$config->finder($finder); +return $config; diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..fe909ecb1 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,35 @@ +sudo: false + +language: php + +matrix: + fast_finish: true + include: + - php: 5.5 + - php: 5.6 + env: + - EXECUTE_TEST_COVERALLS=true + - EXECUTE_CS_CHECK=true + - php: 7 + - php: hhvm + allow_failures: + - php: 7 + - php: hhvm + +notifications: + irc: "irc.freenode.org#zftalk.dev" + email: false + +before_install: + - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi + +install: + - composer install --no-interaction --prefer-source + +script: + - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/phpunit -c phpunit.xml.travis --coverage-clover clover.xml ; fi + - if [[ $EXECUTE_TEST_COVERALLS != 'true' ]]; then ./vendor/bin/phpunit -c phpunit.xml.travis ; fi + - if [[ $EXECUTE_CS_CHECK == 'true' ]]; then ./vendor/bin/php-cs-fixer fix -v --diff --dry-run --config-file=.php_cs ; fi + +after_script: + - if [[ $EXECUTE_TEST_COVERALLS == 'true' ]]; then ./vendor/bin/coveralls ; fi diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..77852065b --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,229 @@ +# CONTRIBUTING + +## RESOURCES + +If you wish to contribute to Zend Framework, please be sure to +read/subscribe to the following resources: + + - [Coding Standards](https://github.com/zendframework/zf2/wiki/Coding-Standards) + - [Contributor's Guide](http://framework.zend.com/participate/contributor-guide) + - ZF Contributor's mailing list: + Archives: http://zend-framework-community.634137.n4.nabble.com/ZF-Contributor-f680267.html + Subscribe: zf-contributors-subscribe@lists.zend.com + - ZF Contributor's IRC channel: + #zftalk.dev on Freenode.net + +If you are working on new features or refactoring [create a proposal](https://github.com/zendframework/zend-cache/issues/new). + +## Reporting Potential Security Issues + +If you have encountered a potential security vulnerability, please **DO NOT** report it on the public +issue tracker: send it to us at [zf-security@zend.com](mailto:zf-security@zend.com) instead. +We will work with you to verify the vulnerability and patch it as soon as possible. + +When reporting issues, please provide the following information: + +- Component(s) affected +- A description indicating how to reproduce the issue +- A summary of the security vulnerability and impact + +We request that you contact us via the email address above and give the project +contributors a chance to resolve the vulnerability and issue a new release prior +to any public exposure; this helps protect users and provides them with a chance +to upgrade and/or update in order to protect their applications. + +For sensitive email communications, please use [our PGP key](http://framework.zend.com/zf-security-pgp-key.asc). + +## RUNNING TESTS + +> ### Note: testing versions prior to 2.4 +> +> This component originates with Zend Framework 2. During the lifetime of ZF2, +> testing infrastructure migrated from PHPUnit 3 to PHPUnit 4. In most cases, no +> changes were necessary. However, due to the migration, tests may not run on +> versions < 2.4. As such, you may need to change the PHPUnit dependency if +> attempting a fix on such a version. + +To run tests: + +- Clone the repository: + + ```console + $ git clone git@github.com:zendframework/zend-cache.git + $ cd + ``` + +- Install dependencies via composer: + + ```console + $ curl -sS https://getcomposer.org/installer | php -- + $ ./composer.phar install + ``` + + If you don't have `curl` installed, you can also download `composer.phar` from https://getcomposer.org/ + +- Run the tests via `phpunit` and the provided PHPUnit config, like in this example: + + ```console + $ ./vendor/bin/phpunit + ``` + +You can turn on conditional tests with the phpunit.xml file. +To do so: + + - Copy `phpunit.xml.dist` file to `phpunit.xml` + - Edit `phpunit.xml` to enable any specific functionality you + want to test, as well as to provide test values to utilize. + +## Running Coding Standards Checks + +This component uses [php-cs-fixer](http://cs.sensiolabs.org/) for coding +standards checks, and provides configuration for our selected checks. +`php-cs-fixer` is installed by default via Composer. + +To run checks only: + +```console +$ ./vendor/bin/php-cs-fixer fix . -v --diff --dry-run --config-file=.php_cs +``` + +To have `php-cs-fixer` attempt to fix problems for you, omit the `--dry-run` +flag: + +```console +$ ./vendor/bin/php-cs-fixer fix . -v --diff --config-file=.php_cs +``` + +If you allow php-cs-fixer to fix CS issues, please re-run the tests to ensure +they pass, and make sure you add and commit the changes after verification. + +## Recommended Workflow for Contributions + +Your first step is to establish a public repository from which we can +pull your work into the master repository. We recommend using +[GitHub](https://github.com), as that is where the component is already hosted. + +1. Setup a [GitHub account](http://github.com/), if you haven't yet +2. Fork the repository (http://github.com/zendframework/zend-cache) +3. Clone the canonical repository locally and enter it. + + ```console + $ git clone git://github.com:zendframework/zend-cache.git + $ cd zend-cache + ``` + +4. Add a remote to your fork; substitute your GitHub username in the command + below. + + ```console + $ git remote add {username} git@github.com:{username}/zend-cache.git + $ git fetch {username} + ``` + +### Keeping Up-to-Date + +Periodically, you should update your fork or personal repository to +match the canonical ZF repository. Assuming you have setup your local repository +per the instructions above, you can do the following: + + +```console +$ git checkout master +$ git fetch origin +$ git rebase origin/master +# OPTIONALLY, to keep your remote up-to-date - +$ git push {username} master:master +``` + +If you're tracking other branches -- for example, the "develop" branch, where +new feature development occurs -- you'll want to do the same operations for that +branch; simply substitute "develop" for "master". + +### Working on a patch + +We recommend you do each new feature or bugfix in a new branch. This simplifies +the task of code review as well as the task of merging your changes into the +canonical repository. + +A typical workflow will then consist of the following: + +1. Create a new local branch based off either your master or develop branch. +2. Switch to your new local branch. (This step can be combined with the + previous step with the use of `git checkout -b`.) +3. Do some work, commit, repeat as necessary. +4. Push the local branch to your remote repository. +5. Send a pull request. + +The mechanics of this process are actually quite trivial. Below, we will +create a branch for fixing an issue in the tracker. + +```console +$ git checkout -b hotfix/9295 +Switched to a new branch 'hotfix/9295' +``` + +... do some work ... + + +```console +$ git commit +``` + +... write your log message ... + + +```console +$ git push {username} hotfix/9295:hotfix/9295 +Counting objects: 38, done. +Delta compression using up to 2 threads. +Compression objects: 100% (18/18), done. +Writing objects: 100% (20/20), 8.19KiB, done. +Total 20 (delta 12), reused 0 (delta 0) +To ssh://git@github.com/{username}/zend-cache.git + b5583aa..4f51698 HEAD -> master +``` + +To send a pull request, you have two options. + +If using GitHub, you can do the pull request from there. Navigate to +your repository, select the branch you just created, and then select the +"Pull Request" button in the upper right. Select the user/organization +"zendframework" as the recipient. + +If using your own repository - or even if using GitHub - you can use `git +format-patch` to create a patchset for us to apply; in fact, this is +**recommended** for security-related patches. If you use `format-patch`, please +send the patches as attachments to: + +- zf-devteam@zend.com for patches without security implications +- zf-security@zend.com for security patches + +#### What branch to issue the pull request against? + +Which branch should you issue a pull request against? + +- For fixes against the stable release, issue the pull request against the + "master" branch. +- For new features, or fixes that introduce new elements to the public API (such + as new public methods or properties), issue the pull request against the + "develop" branch. + +### Branch Cleanup + +As you might imagine, if you are a frequent contributor, you'll start to +get a ton of branches both locally and on your remote. + +Once you know that your changes have been accepted to the master +repository, we suggest doing some cleanup of these branches. + +- Local branch cleanup + + ```console + $ git branch -d + ``` + +- Remote branch removal + + ```console + $ git push {username} : + ``` diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 000000000..6eab5aa14 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,27 @@ +Copyright (c) 2005-2015, Zend Technologies USA, Inc. +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 Zend Technologies USA, Inc. nor the names of its + 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. diff --git a/README.md b/README.md new file mode 100644 index 000000000..46d27859d --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +# zend-cache + +`Zend\Cache` provides a general cache system for PHP. The `Zend\Cache` component +is able to cache different patterns (class, object, output, etc) using different +storage adapters (DB, File, Memcache, etc). + + +- File issues at https://github.com/zendframework/zend-cache/issues +- Documentation is at http://framework.zend.com/manual/current/en/index.html#zend-cache diff --git a/composer.json b/composer.json new file mode 100644 index 000000000..80e6c3bf9 --- /dev/null +++ b/composer.json @@ -0,0 +1,49 @@ +{ + "name": "zendframework/zend-cache", + "description": "Zend\\Cache component", + "license": "BSD-3-Clause", + "keywords": [ + "zf2", + "cache" + ], + "homepage": "https://github.com/zendframework/zend-cache", + "autoload": { + "psr-4": { + "Zend\\Cache\\": "src/" + } + }, + "require": { + "php": ">=5.3.23", + "zendframework/zend-stdlib": "self.version", + "zendframework/zend-servicemanager": "self.version", + "zendframework/zend-serializer": "self.version", + "zendframework/zend-eventmanager": "self.version" + }, + "require-dev": { + "zendframework/zend-session": "self.version", + "fabpot/php-cs-fixer": "1.7.*", + "satooshi/php-coveralls": "dev-master", + "phpunit/PHPUnit": "~4.0" + }, + "suggest": { + "zendframework/zend-serializer": "Zend\\Serializer component", + "zendframework/zend-session": "Zend\\Session component", + "ext-apc": "APC >= 3.1.6 to use the APC storage adapter", + "ext-dba": "DBA, to use the DBA storage adapter", + "ext-memcached": "Memcached >= 1.0.0 to use the Memcached storage adapter", + "ext-mongo": "Mongo, to use MongoDb storage adapter", + "ext-wincache": "WinCache, to use the WinCache storage adapter", + "mongofill/mongofill": "Alternative to ext-mongo - a pure PHP implementation designed as a drop in replacement" + }, + "extra": { + "branch-alias": { + "dev-master": "2.4-dev", + "dev-develop": "2.5-dev" + } + }, + "autoload-dev": { + "psr-4": { + "ZendTest\\Cache\\": "test/" + } + } +} \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 000000000..9fd3f75d3 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,62 @@ + + + + + ./test/ + + + + + + disable + + + + + + ./src + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/phpunit.xml.travis b/phpunit.xml.travis new file mode 100644 index 000000000..8b5e0202e --- /dev/null +++ b/phpunit.xml.travis @@ -0,0 +1,64 @@ + + + + + ./test/ + + + + + + disable + + + + + + ./src + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Backend.php b/src/Backend.php new file mode 100644 index 000000000..c0500327a --- /dev/null +++ b/src/Backend.php @@ -0,0 +1,228 @@ + (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 + * @throws Zend_Cache_Exception + * @return void + */ + public function __construct(array $options = array()) + { + while (list($name, $value) = each($options)) { + $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'); + while (list($name, $value) = each($directives)) { + 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; + } + } + + /** + * 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; + } + + /** + * Return a system-wide tmp directory + * + * @return string System-wide tmp directory + */ + static function getTmpDir() + { + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + // windows... + foreach (array($_ENV, $_SERVER) as $tab) { + foreach (array('TEMP', 'TMP', 'windir', 'SystemRoot') as $key) { + if (isset($tab[$key])) { + $result = $tab[$key]; + if (($key == 'windir') or ($key == 'SystemRoot')) { + $result = $result . '\\temp'; + } + return $result; + } + } + } + return '\\temp'; + } else { + // unix... + if (isset($_ENV['TMPDIR'])) return $_ENV['TMPDIR']; + if (isset($_SERVER['TMPDIR'])) return $_SERVER['TMPDIR']; + return '/tmp'; + } + } + + /** + * 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; + } + try { + /** + * @see Zend_Log + */ + require_once 'Zend/Log.php'; + } catch (Zend_Exception $e) { + Zend_Cache::throwException('Logging feature is enabled but the Zend_Log class is not available'); + } + if (isset($this->_directives['logger'])) { + if ($this->_directives['logger'] instanceof Zend_Log) { + return; + } else { + 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/Writer/Stream.php'; + $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); + $this->_directives['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->_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); + } +} diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php new file mode 100644 index 000000000..39481639c --- /dev/null +++ b/src/Backend/Apc.php @@ -0,0 +1,354 @@ + 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() + { + $res = array(); + $array = apc_cache_info('user', false); + $records = $array['cache_list']; + foreach ($records as $record) { + $res[] = $record['info']; + } + 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 = 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 + ); + } + +} diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php new file mode 100644 index 000000000..43d40eeb8 --- /dev/null +++ b/src/Backend/ExtendedInterface.php @@ -0,0 +1,125 @@ + (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 : + * - Umask 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 : + * - Umask 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_umask' => 0700, + 'file_name_prefix' => 'zend_cache', + 'cache_file_umask' => 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 + * @return void + */ + 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('~^[\w]+$~', $this->_options['file_name_prefix'])) { + Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-A0-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']) && is_string($options['hashed_directory_umask'])) { + // See #ZF-4422 + $this->_options['hashed_directory_umask'] = octdec($this->_options['hashed_directory_umask']); + } + if (isset($options['cache_file_umask']) && is_string($options['cache_file_umask'])) { + // See #ZF-4422 + $this->_options['cache_file_umask'] = octdec($this->_options['cache_file_umask']); + } + } + + /** + * 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('cache_dir must be a directory'); + } + if (!is_writable($value)) { + Zend_Cache::throwException('cache_dir is not writable'); + } + 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 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); + return ($this->_delMetadatas($id) && $this->_remove($file)); + } + + /** + * 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()) + { + // 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) { + return true; + } + 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 + if ($mode != Zend_Cache::CLEANING_MODE_ALL) { + 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: + $res = $this->remove($id); + if (!$res) { + // in this case only, we accept a problem with the metadatas file drop + $res = $this->_remove($file); + } + $result = $result && $res; + break; + case Zend_Cache::CLEANING_MODE_OLD: + if (time() > $metadatas['expire']) { + $result = ($result) && ($this->remove($id)); + } + 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 = ($result) && ($this->remove($id)); + } + 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 = ($result) && $this->remove($id); + } + 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 = ($result) && ($this->remove($id)); + } + 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 = ($result) && ($this->_clean($file . DIRECTORY_SEPARATOR, $mode, $tags)); + if ($mode=='all') { + // if mode=='all', we try to drop the structure too + @rmdir($file); + } + } + } + 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) { + return true; + } + 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 + $result = array_unique(array_merge($result, $this->_get($file . DIRECTORY_SEPARATOR, $mode, $tags))); + } + } + return array_unique($result); + } + + /** + * Compute & return the expire time + * + * @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_umask']); + @chmod($part, $this->_options['hashed_directory_umask']); // 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; + } + if (function_exists('get_magic_quotes_runtime')) { + $mqr = @get_magic_quotes_runtime(); + @set_magic_quotes_runtime(0); + } + $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); + } + if (function_exists('set_magic_quotes_runtime')) { + @set_magic_quotes_runtime($mqr); + } + 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_umask']); + 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); + } + +} diff --git a/src/Backend/Interface.php b/src/Backend/Interface.php new file mode 100644 index 000000000..09798b1cc --- /dev/null +++ b/src/Backend/Interface.php @@ -0,0 +1,98 @@ + 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()); + +} diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php new file mode 100644 index 000000000..33c2accb4 --- /dev/null +++ b/src/Backend/Memcached.php @@ -0,0 +1,501 @@ + (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)) { + 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-5702 : we try add() first becase set() seems to be slower + if (!($result = $this->_memcache->add($id, array($data, time(), $lifetime), $flag, $lifetime))) { + $result = $this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime); + } + if (count($tags) > 0) { + $this->_log("Zend_Cache_Backend_Memcached::save() : tags are unsupported by the 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); + } + + /** + * 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 = 0; + $memUsed = 0; + foreach ($mems as $key => $mem) { + if ($mem === false) { + Zend_Cache::throwException('can\'t get stat from ' . $key); + } else { + $eachSize = $mem['limit_maxbytes']; + if ($eachSize == 0) { + Zend_Cache::throwException('can\'t get memory size from ' . $key); + } + + $eachUsed = $mem['bytes']; + if ($eachUsed > $eachSize) { + $eachUsed = $eachSize; + } + + $memSize += $eachSize; + $memUsed += $eachUsed; + } + } + + 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 + ); + } + +} diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php new file mode 100644 index 000000000..595d5de1d --- /dev/null +++ b/src/Backend/Sqlite.php @@ -0,0 +1,678 @@ + (string) cache_db_complete_path : + * - the complete path (filename included) of the SQLITE database + * + * ====> (int) automatic_vacuum_factor : + * - Disable / Tune the automatic vacuum process + * - The automatic vacuum process defragment the database file (and make it smaller) + * when a clean() or delete() is called + * 0 => no automatic vacuum + * 1 => systematic vacuum (when delete() or clean() methods are called) + * x (integer) > 1 => automatic vacuum randomly 1 times on x clean() or delete() + * + * @var array Available options + */ + protected $_options = array( + 'cache_db_complete_path' => null, + 'automatic_vacuum_factor' => 10 + ); + + /** + * DB ressource + * + * @var mixed $_db + */ + private $_db = null; + + /** + * Boolean to store if the structure has benn checked or not + * + * @var boolean $_structureChecked + */ + private $_structureChecked = false; + + /** + * 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['cache_db_complete_path'] === null) { + Zend_Cache::throwException('cache_db_complete_path option has to set'); + } + if (!extension_loaded('sqlite')) { + Zend_Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment"); + } + $this->_getConnection(); + } + + /** + * Destructor + * + * @return void + */ + public function __destruct() + { + @sqlite_close($this->_getConnection()); + } + + /** + * 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) + { + $this->_checkAndBuildStructure(); + $sql = "SELECT content FROM cache WHERE id='$id'"; + if (!$doNotTestCacheValidity) { + $sql = $sql . " AND (expire=0 OR expire>" . time() . ')'; + } + $result = $this->_query($sql); + $row = @sqlite_fetch_array($result); + if ($row) { + return $row['content']; + } + 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) + { + $this->_checkAndBuildStructure(); + $sql = "SELECT lastModified FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')'; + $result = $this->_query($sql); + $row = @sqlite_fetch_array($result); + if ($row) { + return ((int) $row['lastModified']); + } + 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) + * @throws Zend_Cache_Exception + * @return boolean True if no problem + */ + public function save($data, $id, $tags = array(), $specificLifetime = false) + { + $this->_checkAndBuildStructure(); + $lifetime = $this->getLifetime($specificLifetime); + $data = @sqlite_escape_string($data); + $mktime = time(); + if ($lifetime === null) { + $expire = 0; + } else { + $expire = $mktime + $lifetime; + } + $this->_query("DELETE FROM cache WHERE id='$id'"); + $sql = "INSERT INTO cache (id, content, lastModified, expire) VALUES ('$id', '$data', $mktime, $expire)"; + $res = $this->_query($sql); + if (!$res) { + $this->_log("Zend_Cache_Backend_Sqlite::save() : impossible to store the cache id=$id"); + return false; + } + $res = true; + foreach ($tags as $tag) { + $res = $res && $this->_registerTag($id, $tag); + } + return $res; + } + + /** + * Remove a cache record + * + * @param string $id Cache id + * @return boolean True if no problem + */ + public function remove($id) + { + $this->_checkAndBuildStructure(); + $res = $this->_query("SELECT COUNT(*) AS nbr FROM cache WHERE id='$id'"); + $result1 = @sqlite_fetch_single($res); + $result2 = $this->_query("DELETE FROM cache WHERE id='$id'"); + $result3 = $this->_query("DELETE FROM tag WHERE id='$id'"); + $this->_automaticVacuum(); + return ($result1 && $result2 && $result3); + } + + /** + * 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()) + { + $this->_checkAndBuildStructure(); + $return = $this->_clean($mode, $tags); + $this->_automaticVacuum(); + return $return; + } + + /** + * Return an array of stored cache ids + * + * @return array array of stored cache ids (string) + */ + public function getIds() + { + $this->_checkAndBuildStructure(); + $res = $this->_query("SELECT id FROM cache WHERE (expire=0 OR expire>" . time() . ")"); + $result = array(); + while ($id = @sqlite_fetch_single($res)) { + $result[] = $id; + } + return $result; + } + + /** + * Return an array of stored tags + * + * @return array array of stored tags (string) + */ + public function getTags() + { + $this->_checkAndBuildStructure(); + $res = $this->_query("SELECT DISTINCT(name) AS name FROM tag"); + $result = array(); + while ($id = @sqlite_fetch_single($res)) { + $result[] = $id; + } + return $result; + } + + /** + * 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()) + { + $first = true; + $ids = array(); + foreach ($tags as $tag) { + $res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'"); + if (!$res) { + return array(); + } + $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); + $ids2 = array(); + foreach ($rows as $row) { + $ids2[] = $row['id']; + } + if ($first) { + $ids = $ids2; + $first = false; + } else { + $ids = array_intersect($ids, $ids2); + } + } + $result = array(); + foreach ($ids as $id) { + $result[] = $id; + } + return $result; + } + + /** + * 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()) + { + $res = $this->_query("SELECT id FROM cache"); + $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); + $result = array(); + foreach ($rows as $row) { + $id = $row['id']; + $matching = false; + foreach ($tags as $tag) { + $res = $this->_query("SELECT COUNT(*) AS nbr FROM tag WHERE name='$tag' AND id='$id'"); + if (!$res) { + return array(); + } + $nbr = (int) @sqlite_fetch_single($res); + if ($nbr > 0) { + $matching = true; + } + } + if (!$matching) { + $result[] = $id; + } + } + return $result; + } + + /** + * 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()) + { + $first = true; + $ids = array(); + foreach ($tags as $tag) { + $res = $this->_query("SELECT DISTINCT(id) AS id FROM tag WHERE name='$tag'"); + if (!$res) { + return array(); + } + $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); + $ids2 = array(); + foreach ($rows as $row) { + $ids2[] = $row['id']; + } + if ($first) { + $ids = $ids2; + $first = false; + } else { + $ids = array_merge($ids, $ids2); + } + } + $result = array(); + foreach ($ids as $id) { + $result[] = $id; + } + return $result; + } + + /** + * Return the filling percentage of the backend storage + * + * @throws Zend_Cache_Exception + * @return int integer between 0 and 100 + */ + public function getFillingPercentage() + { + $dir = dirname($this->_options['cache_db_complete_path']); + $free = disk_free_space($dir); + $total = disk_total_space($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) + { + $tags = array(); + $res = $this->_query("SELECT name FROM tag WHERE id='$id'"); + if ($res) { + $rows = @sqlite_fetch_all($res, SQLITE_ASSOC); + foreach ($rows as $row) { + $tags[] = $row['name']; + } + } + $this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)'); + $res = $this->_query("SELECT lastModified,expire FROM cache WHERE id='$id'"); + if (!$res) { + return false; + } + $row = @sqlite_fetch_array($res, SQLITE_ASSOC); + return array( + 'tags' => $tags, + 'mtime' => $row['lastModified'], + 'expire' => $row['expire'] + ); + } + + /** + * 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) + { + $sql = "SELECT expire FROM cache WHERE id='$id' AND (expire=0 OR expire>" . time() . ')'; + $res = $this->_query($sql); + if (!$res) { + return false; + } + $expire = @sqlite_fetch_single($res); + $newExpire = $expire + $extraLifetime; + $res = $this->_query("UPDATE cache SET lastModified=" . time() . ", expire=$newExpire WHERE id='$id'"); + if ($res) { + return true; + } else { + 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' => 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) + { + $time = time() - 1; + $this->_query("UPDATE cache SET lastModified=$time, expire=$time WHERE id='$id'"); + } + + /** + * Return the connection resource + * + * If we are not connected, the connection is made + * + * @throws Zend_Cache_Exception + * @return resource Connection resource + */ + private function _getConnection() + { + if (is_resource($this->_db)) { + return $this->_db; + } else { + $this->_db = @sqlite_open($this->_options['cache_db_complete_path']); + if (!(is_resource($this->_db))) { + Zend_Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file"); + } + return $this->_db; + } + } + + /** + * Execute an SQL query silently + * + * @param string $query SQL query + * @return mixed|false query results + */ + private function _query($query) + { + $db = $this->_getConnection(); + if (is_resource($db)) { + $res = @sqlite_query($db, $query); + if ($res === false) { + return false; + } else { + return $res; + } + } + return false; + } + + /** + * Deal with the automatic vacuum process + * + * @return void + */ + private function _automaticVacuum() + { + if ($this->_options['automatic_vacuum_factor'] > 0) { + $rand = rand(1, $this->_options['automatic_vacuum_factor']); + if ($rand == 1) { + $this->_query('VACUUM'); + @sqlite_close($this->_getConnection()); + } + } + } + + /** + * Register a cache id with the given tag + * + * @param string $id Cache id + * @param string $tag Tag + * @return boolean True if no problem + */ + private function _registerTag($id, $tag) { + $res = $this->_query("DELETE FROM TAG WHERE name='$tag' AND id='$id'"); + $res = $this->_query("INSERT INTO tag (name, id) VALUES ('$tag', '$id')"); + if (!$res) { + $this->_log("Zend_Cache_Backend_Sqlite::_registerTag() : impossible to register tag=$tag on id=$id"); + return false; + } + return true; + } + + /** + * Build the database structure + * + * @return false + */ + private function _buildStructure() + { + $this->_query('DROP INDEX tag_id_index'); + $this->_query('DROP INDEX tag_name_index'); + $this->_query('DROP INDEX cache_id_expire_index'); + $this->_query('DROP TABLE version'); + $this->_query('DROP TABLE cache'); + $this->_query('DROP TABLE tag'); + $this->_query('CREATE TABLE version (num INTEGER PRIMARY KEY)'); + $this->_query('CREATE TABLE cache (id TEXT PRIMARY KEY, content BLOB, lastModified INTEGER, expire INTEGER)'); + $this->_query('CREATE TABLE tag (name TEXT, id TEXT)'); + $this->_query('CREATE INDEX tag_id_index ON tag(id)'); + $this->_query('CREATE INDEX tag_name_index ON tag(name)'); + $this->_query('CREATE INDEX cache_id_expire_index ON cache(id, expire)'); + $this->_query('INSERT INTO version (num) VALUES (1)'); + } + + /** + * Check if the database structure is ok (with the good version) + * + * @return boolean True if ok + */ + private function _checkStructureVersion() + { + $result = $this->_query("SELECT num FROM version"); + if (!$result) return false; + $row = @sqlite_fetch_array($result); + if (!$row) { + return false; + } + if (((int) $row['num']) != 1) { + // old cache structure + $this->_log('Zend_Cache_Backend_Sqlite::_checkStructureVersion() : old cache structure version detected => the cache is going to be dropped'); + return false; + } + 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 + */ + private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + { + switch ($mode) { + case Zend_Cache::CLEANING_MODE_ALL: + $res1 = $this->_query('DELETE FROM cache'); + $res2 = $this->_query('DELETE FROM tag'); + return $res1 && $res2; + break; + case Zend_Cache::CLEANING_MODE_OLD: + $mktime = time(); + $res1 = $this->_query("DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)"); + $res2 = $this->_query("DELETE FROM cache WHERE expire>0 AND expire<=$mktime"); + return $res1 && $res2; + break; + case Zend_Cache::CLEANING_MODE_MATCHING_TAG: + $ids = $this->getIdsMatchingTags($tags); + $result = true; + foreach ($ids as $id) { + $result = $result && ($this->remove($id)); + } + return $result; + break; + case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: + $ids = $this->getIdsNotMatchingTags($tags); + $result = true; + foreach ($ids as $id) { + $result = $result && ($this->remove($id)); + } + return $result; + break; + case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: + $ids = $this->getIdsMatchingAnyTags($tags); + $result = true; + foreach ($ids as $id) { + $result = $result && ($this->remove($id)); + } + return $result; + break; + default: + break; + } + return false; + } + + /** + * Check if the database structure is ok (with the good version), if no : build it + * + * @throws Zend_Cache_Exception + * @return boolean True if ok + */ + private function _checkAndBuildStructure() + { + if (!($this->_structureChecked)) { + if (!$this->_checkStructureVersion()) { + $this->_buildStructure(); + if (!$this->_checkStructureVersion()) { + Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']); + } + } + $this->_structureChecked = true; + } + return true; + } + +} diff --git a/src/Backend/Test.php b/src/Backend/Test.php new file mode 100644 index 000000000..b2146121a --- /dev/null +++ b/src/Backend/Test.php @@ -0,0 +1,269 @@ +_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') { + return false; + } + if ($id=='serialized') { + return serialize(array('foo')); + } + if ($id=='serialized2') { + return serialize(array('headers' => array(), 'data' => 'foo')); + } + if (($id=='71769f39054f75894288e397df04e445') or ($id=='615d222619fb20b527168340cebd0578')) { + return serialize(array('foo', 'bar')); + } + if (($id=='8a02d218a5165c467e7a5747cc6bd4b6') or ($id=='648aca1366211d17cbf48e65dc570bee')) { + return serialize(array('foo', 'bar')); + } + 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=='d8523b3ee441006261eeffa5c3d3a0a7') or ($id=='3c439c922209e2cb0b54d6deffccd75a')) { + return false; + } + if (($id=='40f649b94977c0a6e76902e2a0b43587') or ($id=='e83249ea22178277d5befc2c5e2e9ace')) { + 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 ($id=='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 ($id=='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; + } + + /** + * 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; + } + +} diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php new file mode 100644 index 000000000..bcdaff97a --- /dev/null +++ b/src/Backend/TwoLevels.php @@ -0,0 +1,501 @@ + (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_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_refresh_fast_cache' => true + ); + + /** + * Slow Backend + * + * @var Zend_Cache_Backend + */ + private $_slowBackend; + + /** + * Fast Backend + * + * @var Zend_Cache_Backend + */ + private $_fastBackend; + + /** + * Cache for the fast backend filling percentage + * + * @var int + */ + private $_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'); + } + if ($this->_options['fast_backend'] === null) { + Zend_Cache::throwException('fast_backend option has to set'); + } + $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']); + $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->_slowBackend))) { + Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); + } + if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) { + Zend_Cache::throwException('slow_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); + 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) + { + $res = $this->_fastBackend->load($id, $doNotTestCacheValidity); + if ($res === false) { + $res = $this->_slowBackend->load($id, $doNotTestCacheValidity); + if ($res === false) { + // there is no cache at all for this id + return false; + } + } + $array = unserialize($res); + // maybe, we have to refresh the fast cache ? + if ($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) + { + $this->_fastBackend->remove($id); + return $this->_slowBackend->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 + * @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) { + $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id); + } + return $res; + break; + case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: + $ids = $this->_slowBackend->getIdsNotMatchingTags($tags); + $res = true; + foreach ($ids as $id) { + $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id); + } + return $res; + break; + case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: + $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags); + $res = true; + foreach ($ids as $id) { + $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id); + } + 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 === null) { + // if lifetime is null, we have an infinite lifetime + // we need to use arbitrary lifetimes + $fastLifetime = (int) (2592000 / (11 - $priority)); + } else { + $fastLifetime = (int) ($lifetime / (11 - $priority)); + } + if (($maxLifetime !== null) && ($maxLifetime >= 0)) { + if ($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; + } + +} diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php new file mode 100644 index 000000000..e6064ba85 --- /dev/null +++ b/src/Backend/Xcache.php @@ -0,0 +1,215 @@ + (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']; + } + xcache_clear_cache(XC_TYPE_VAR, 0); + if (isset($backup['PHP_AUTH_USER'])) { + $_SERVER['PHP_AUTH_USER'] = $backup['PHP_AUTH_USER']; + $_SERVER['PHP_AUTH_PW'] = $backup['PHP_AUTH_PW']; + } + return true; + break; + case 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; + } + +} diff --git a/src/Backend/ZendPlatform.php b/src/Backend/ZendPlatform.php new file mode 100644 index 000000000..1f0585eeb --- /dev/null +++ b/src/Backend/ZendPlatform.php @@ -0,0 +1,316 @@ +_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; + } + +} diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php new file mode 100755 index 000000000..5b9853ce1 --- /dev/null +++ b/src/Backend/ZendServer.php @@ -0,0 +1,208 @@ + (string) namespace : + * Namespace to be used for chaching operations + * + * @var array available options + */ + protected $_options = array( + 'namespace' => 'zendframework' + ); + + /** + * Store data + * + * @var mixed $data Object to store + * @var string $id Cache id + * @var int $timeToLive Time to live in seconds + * @throws Zend_Cache_Exception + */ + abstract protected function _store($data, $id, $timeToLive); + + /** + * Fetch data + * + * @var mixed $data Object to store + * @var string $id Cache id + * @var int $timeToLive Time to live in seconds + * @throws Zend_Cache_Exception + */ + abstract protected function _fetch($id); + + /** + * Unset data + * + * @var 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 !== null) { + 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; + } + } +} diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php new file mode 100755 index 000000000..ed64335ef --- /dev/null +++ b/src/Backend/ZendServer/Disk.php @@ -0,0 +1,101 @@ +_options['namespace'] . '::' . $id, + $data, + $timeToLive) === false) { + $this->_log('Store operation failed.'); + return false; + } + return true; + } + + /** + * Fetch data + * + * @var mixed $data Object to store + * @var string $id Cache id + * @var int $timeToLive Time to live in seconds + */ + protected function _fetch($id) + { + return zend_disk_cache_fetch($this->_options['namespace'] . '::' . $id); + } + + /** + * Unset data + * + * @var 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']); + } +} diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php new file mode 100755 index 000000000..9cd18e524 --- /dev/null +++ b/src/Backend/ZendServer/ShMem.php @@ -0,0 +1,101 @@ +_options['namespace'] . '::' . $id, + $data, + $timeToLive) === false) { + $this->_log('Store operation failed.'); + return false; + } + return true; + } + + /** + * Fetch data + * + * @var mixed $data Object to store + * @var string $id Cache id + * @var int $timeToLive Time to live in seconds + */ + protected function _fetch($id) + { + return zend_shm_cache_fetch($this->_options['namespace'] . '::' . $id); + } + + /** + * Unset data + * + * @var 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']); + } +} diff --git a/src/Core.php b/src/Core.php new file mode 100644 index 000000000..143b89ef9 --- /dev/null +++ b/src/Core.php @@ -0,0 +1,660 @@ + (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 $options Associative array of options + * @throws Zend_Cache_Exception + * @return void + */ + public function __construct(array $options = array()) + { + while (list($name, $value) = each($options)) { + $this->setOption($name, $value); + } + $this->_loggerSanity(); + } + + /** + * Set the backend + * + * @param object $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 object 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"); + } + $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) + { + if (is_string($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"); + } + $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; + self::_validateIdOrTag($id); + $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 boolean True is a cache is available, false else + */ + public function test($id) + { + if (!$this->_options['caching']) { + return false; + } + $id = $this->_id($id); // cache id may need prefix + self::_validateIdOrTag($id); + $this->_lastId = $id; + 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); + } + self::_validateIdOrTag($id); + self::_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) { + if ($this->_extendedBackend) { + // New way + if ($this->_backendCapabilities['automatic_cleaning']) { + $this->clean(Zend_Cache::CLEANING_MODE_OLD); + } else { + $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend'); + } + } else { + // Deprecated way (will be removed in next major version) + if (method_exists($this->_backend, 'isAutomaticCleaningAvailable') && ($this->_backend->isAutomaticCleaningAvailable())) { + $this->clean(Zend_Cache::CLEANING_MODE_OLD); + } else { + $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend'); + } + } + } + } + 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 ! + if ($this->_options['logging']) { + $this->_log("Zend_Cache_Core::save() : impossible to save cache (id=$id)"); + } + $this->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 : written and read data do not match'); + $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 + self::_validateIdOrTag($id); + 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'); + } + self::_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('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + if (!($this->_backendCapabilities['tags'])) { + Zend_Cache::throwException('tags are not supported by the current backend'); + } + return $this->_backend->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()) + { + if (!$this->_extendedBackend) { + Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + if (!($this->_backendCapabilities['tags'])) { + Zend_Cache::throwException('tags are not supported by the current backend'); + } + return $this->_backend->getIdsNotMatchingTags($tags); + } + + /** + * Return an array of stored cache ids + * + * @return array array of stored cache ids (string) + */ + public function getIds() + { + if (!$this->_extendedBackend) { + Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + $array = $this->_backend->getIds(); + if ((!isset($this->_options['cache_id_prefix'])) || ($this->_options['cache_id_prefix'] == '')) return $array; + // we need to remove cache_id_prefix from ids (see #ZF-6178) + $res = array(); + while (list(,$id) = each($array)) { + if (strpos($id, $this->_options['cache_id_prefix']) === 0) { + $res[] = preg_replace("~^{$this->_options['cache_id_prefix']}~", '', $id); + } else { + $res[] = $id; + } + } + return $res; + } + + /** + * Return an array of stored tags + * + * @return array array of stored tags (string) + */ + public function getTags() + { + if (!$this->_extendedBackend) { + Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + if (!($this->_backendCapabilities['tags'])) { + Zend_Cache::throwException('tags are not supported by the current backend'); + } + 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('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + 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('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + $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('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + } + $id = $this->_id($id); // cache id may need prefix + 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 static 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('~^[\w]+$~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 static function _validateTagsArray($tags) + { + if (!is_array($tags)) { + Zend_Cache::throwException('Invalid tags array : must be an array'); + } + foreach($tags as $tag) { + self::_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/Writer/Stream.php'; + $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); + $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 + } + +} diff --git a/src/Exception.php b/src/Exception.php new file mode 100644 index 000000000..a46d8ca25 --- /dev/null +++ b/src/Exception.php @@ -0,0 +1,31 @@ + (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 + */ + private $_tags = array(); + + /** + * SpecificLifetime value + * + * false => no specific life time + * + * @var int + */ + private $_specificLifetime = false; + + /** + * The cached object or the name of the cached abstract class + * + * @var mixed + */ + private $_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 + */ + private $_cachedEntityLabel = ''; + + /** + * Priority (used by some particular backends) + * + * @var int + */ + private $_priority = 8; + + /** + * Constructor + * + * @param array $options Associative array of options + * @throws Zend_Cache_Exception + * @return void + */ + public function __construct(array $options = array()) + { + while (list($name, $value) = each($options)) { + $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 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 + */ + public function __call($name, $parameters) + { + $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(array($this->_cachedEntity, $name), $parameters); + } + $id = $this->_makeId($name, $parameters); + if ($this->test($id)) { + // A cache is available + $result = $this->load($id); + $output = $result[0]; + $return = $result[1]; + } else { + // A cache is not available + ob_start(); + ob_implicit_flush(false); + $return = call_user_func_array(array($this->_cachedEntity, $name), $parameters); + $output = ob_get_contents(); + ob_end_clean(); + $data = array($output, $return); + $this->save($data, $id, $this->_tags, $this->_specificLifetime, $this->_priority); + } + echo $output; + return $return; + } + + /** + * Make a cache id from the method name and parameters + * + * @param string $name Method name + * @param array $parameters Method parameters + * @return string Cache id + */ + private function _makeId($name, $parameters) + { + return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($parameters)); + } + +} diff --git a/src/Frontend/File.php b/src/Frontend/File.php new file mode 100644 index 000000000..8b905d093 --- /dev/null +++ b/src/Frontend/File.php @@ -0,0 +1,208 @@ + (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()) + { + while (list($name, $value) = each($options)) { + $this->setOption($name, $value); + } + if (!isset($this->_specificOptions['master_files'])) { + Zend_Cache::throwException('master_files option must be set'); + } + } + + /** + * Change the master_file option + * + * @param string $masterFile the complete path and name of the master file + */ + public function setMasterFiles($masterFiles) + { + clearstatcache(); + $this->_specificOptions['master_file'] = $masterFiles[0]; // to keep a compatibility + $this->_specificOptions['master_files'] = $masterFiles; + $this->_masterFile_mtimes = array(); + $i = 0; + foreach ($masterFiles as $masterFile) { + $this->_masterFile_mtimes[$i] = @filemtime($masterFile); + if ((!($this->_specificOptions['ignore_missing_master_files'])) && (!($this->_masterFile_mtimes[$i]))) { + Zend_Cache::throwException('Unable to read 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(0 => $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 boolean True is a cache is available, false else + */ + 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; + } + +} + diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php new file mode 100644 index 000000000..b059b30ff --- /dev/null +++ b/src/Frontend/Function.php @@ -0,0 +1,130 @@ + (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()) + { + while (list($name, $value) = each($options)) { + $this->setOption($name, $value); + } + $this->setOption('automatic_serialization', true); + } + + /** + * Main method : call the specified function or get the result from cache + * + * @param string $name Function name + * @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($name, $parameters = array(), $tags = array(), $specificLifetime = false, $priority = 8) + { + $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) { + // We do not have not cache + return call_user_func_array($name, $parameters); + } + $id = $this->_makeId($name, $parameters); + if ($this->test($id)) { + // A cache is available + $result = $this->load($id); + $output = $result[0]; + $return = $result[1]; + } else { + // A cache is not available + ob_start(); + ob_implicit_flush(false); + $return = call_user_func_array($name, $parameters); + $output = ob_get_contents(); + ob_end_clean(); + $data = array($output, $return); + $this->save($data, $id, $tags, $specificLifetime, $priority); + } + echo $output; + return $return; + } + + /** + * Make a cache id from the function name and parameters + * + * @param string $name Function name + * @param array $parameters Function parameters + * @throws Zend_Cache_Exception + * @return string Cache id + */ + private function _makeId($name, $parameters) + { + if (!is_string($name)) { + Zend_Cache::throwException('Incorrect function name'); + } + if (!is_array($parameters)) { + Zend_Cache::throwException('parameters argument must be an array'); + } + return md5($name . serialize($parameters)); + } + +} diff --git a/src/Frontend/Output.php b/src/Frontend/Output.php new file mode 100644 index 000000000..6896dfb6c --- /dev/null +++ b/src/Frontend/Output.php @@ -0,0 +1,105 @@ +_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 (simpy 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_contents(); + ob_end_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); + } + } + +} diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php new file mode 100644 index 000000000..c31a5c2c8 --- /dev/null +++ b/src/Frontend/Page.php @@ -0,0 +1,401 @@ + (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()) + { + while (list($name, $value) = each($options)) { + $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; + 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 = split(':', $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 (count($var) > 0) { + return false; + } + return ''; + } + +} diff --git a/test/AllTests.php b/test/AllTests.php new file mode 100644 index 000000000..269522a9c --- /dev/null +++ b/test/AllTests.php @@ -0,0 +1,204 @@ +addTestSuite('Zend_Cache_FactoryTest'); + $suite->addTestSuite('Zend_Cache_CoreTest'); + $suite->addTestSuite('Zend_Cache_FileBackendTest'); + $suite->addTestSuite('Zend_Cache_OutputFrontendTest'); + $suite->addTestSuite('Zend_Cache_FunctionFrontendTest'); + $suite->addTestSuite('Zend_Cache_ClassFrontendTest'); + $suite->addTestSuite('Zend_Cache_FileFrontendTest'); + $suite->addTestSuite('Zend_Cache_PageFrontendTest'); + + /* + * Check if SQLite tests are enabled, and if extension and driver are available. + */ + if (!defined('TESTS_ZEND_CACHE_SQLITE_ENABLED') || + constant('TESTS_ZEND_CACHE_SQLITE_ENABLED') === false) { + $skipTest = new Zend_Cache_SqliteBackendTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!extension_loaded('sqlite')) { + $skipTest = new Zend_Cache_SqliteBackendTest_SkipTests(); + $skipTest->message = "Extension 'sqlite' is not loaded"; + $suite->addTest($skipTest); + } else { + $suite->addTestSuite('Zend_Cache_SqliteBackendTest'); + } + + /* + * Check if APC tests are enabled, and if extension is available. + */ + if (!defined('TESTS_ZEND_CACHE_APC_ENABLED') || + constant('TESTS_ZEND_CACHE_APC_ENABLED') === false) { + $skipTest = new Zend_Cache_ApcBackendTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!extension_loaded('apc')) { + $skipTest = new Zend_Cache_ApcBackendTest_SkipTests(); + $skipTest->message = "Extension 'APC' is not loaded"; + $suite->addTest($skipTest); + } else { + $suite->addTestSuite('Zend_Cache_ApcBackendTest'); + } + + /* + * Check if Xcache tests are enabled, and if extension is available. + */ + if (!defined('TESTS_ZEND_CACHE_XCACHE_ENABLED') || + constant('TESTS_ZEND_CACHE_XCACHE_ENABLED') === false) { + $skipTest = new Zend_Cache_XCacheBackendTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!extension_loaded('xcache')) { + $skipTest = new Zend_Cache_XCacheBackendTest_SkipTests(); + $skipTest->message = "Extension 'XCache' is not loaded"; + $suite->addTest($skipTest); + } else { + $suite->addTestSuite('Zend_Cache_XCacheBackendTest'); + } + + /* + * Check if Memcached tests are enabled, and if extension is available. + */ + if (!defined('TESTS_ZEND_CACHE_MEMCACHED_ENABLED') || + constant('TESTS_ZEND_CACHE_MEMCACHED_ENABLED') === false) { + $skipTest = new Zend_Cache_MemcachedBackendTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!extension_loaded('memcache')) { + $skipTest = new Zend_Cache_MemcachedBackendTest_SkipTests(); + $skipTest->message = "Extension 'APC' is not loaded"; + $suite->addTest($skipTest); + } else { + if (!defined('TESTS_ZEND_CACHE_MEMCACHED_HOST')) { + define('TESTS_ZEND_CACHE_MEMCACHED_HOST', '127.0.0.1'); + } + if (!defined('TESTS_ZEND_CACHE_MEMCACHED_PORT')) { + define('TESTS_ZEND_CACHE_MEMCACHED_PORT', 11211); + } + if (!defined('TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT')) { + define('TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT', true); + } + $suite->addTestSuite('Zend_Cache_MemcachedBackendTest'); + } + + /* + * Check if Zend Platform tests are enabled, and if extension is available. + */ + if (!defined('TESTS_ZEND_CACHE_PLATFORM_ENABLED') || + constant('TESTS_ZEND_CACHE_PLATFORM_ENABLED') === false) { + $skipTest = new Zend_Cache_ZendPlatformBackendTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!function_exists('accelerator_license_info')) { + $skipTest = new Zend_Cache_ZendPlatformBackendTest_SkipTests(); + $skipTest->message = 'Extension for Zend Platform is not loaded'; + $suite->addTest($skipTest); + } else { + $suite->addTestSuite('Zend_Cache_ZendPlatformBackendTest'); + } + + /* + * Check if APC tests are enabled, and if extension is available. + */ + if (!defined('TESTS_ZEND_CACHE_APC_ENABLED') || + constant('TESTS_ZEND_CACHE_APC_ENABLED') === false) { + $skipTest = new Zend_Cache_TwoLevelsBackendTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!extension_loaded('apc')) { + $skipTest = new Zend_Cache_TwoLevelsBackendTest_SkipTests(); + $skipTest->message = "Extension 'APC' is not loaded"; + $suite->addTest($skipTest); + } else { + $suite->addTestSuite('Zend_Cache_TwoLevelsBackendTest'); + } + + /* + * Check if Zend Server tests are enabled, and appropriate functions are available. + */ + if (!defined('TESTS_ZEND_CACHE_ZENDSERVER_ENABLED') || + constant('TESTS_ZEND_CACHE_ZENDSERVER_ENABLED') === false) { + $skipTest = new Zend_Cache_ZendServerTest_SkipTests(); + $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; + $suite->addTest($skipTest); + } else if (!function_exists('zend_shm_cache_store')) { + $skipTest = new Zend_Cache_ZendServerTest_SkipTests(); + $skipTest->message = "Zend Server caching environment is not available"; + $suite->addTest($skipTest); + } else { + $suite->addTestSuite('Zend_Cache_ZendServerDiskTest'); + $suite->addTestSuite('Zend_Cache_ZendServerShMemTest'); + } + + return $suite; + } +} + +if (PHPUnit_MAIN_METHOD == 'Zend_Cache_AllTests::main') { + Zend_Cache_AllTests::main(); +} diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php new file mode 100644 index 000000000..902ef80dd --- /dev/null +++ b/test/ApcBackendTest.php @@ -0,0 +1,117 @@ +_instance = new Zend_Cache_Backend_Apc(array()); + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_Apc(); + } + + public function testCleanModeOld() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testGetIdsMatchingTags() {} + public function testGetIdsMatchingTags2() {} + public function testGetIdsMatchingTags3() {} + public function testGetIdsMatchingTags4() {} + public function testGetIdsNotMatchingTags() {} + public function testGetIdsNotMatchingTags2() {} + public function testGetIdsNotMatchingTags3() {} + public function testGetTags() {} + + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testGetMetadatas($notag = true) + { + parent::testGetMetadatas($notag); + } + +} + + diff --git a/test/ClassFrontendTest.php b/test/ClassFrontendTest.php new file mode 100644 index 000000000..2b4b70179 --- /dev/null +++ b/test/ClassFrontendTest.php @@ -0,0 +1,222 @@ +_string); + echo "foobar2_output($param1, $param2)"; + return "foobar2_return($param1, $param2)"; + } + +} + +/** + * @package Zend_Cache + * @subpackage UnitTests + */ +class Zend_Cache_ClassFrontendTest extends PHPUnit_Framework_TestCase { + + private $_instance1; + private $_instance2; + + public function setUp() + { + if (!$this->_instance1) { + $options1 = array( + 'cached_entity' => 'test' + ); + $this->_instance1 = new Zend_Cache_Frontend_Class($options1); + $this->_backend1 = new Zend_Cache_Backend_Test(); + $this->_instance1->setBackend($this->_backend1); + } + if (!$this->_instance2) { + $options2 = array( + 'cached_entity' => new test() + ); + $this->_instance2 = new Zend_Cache_Frontend_Class($options2); + $this->_backend2 = new Zend_Cache_Backend_Test(); + $this->_instance2->setBackend($this->_backend2); + } + } + + public function tearDown() + { + unset($this->_instance1); + unset($this->_instance2); + } + + public function testConstructorCorrectCall1() + { + $options = array( + 'cache_by_default' => false, + 'cached_entity' => 'test' + ); + $test = new Zend_Cache_Frontend_Class($options); + } + + public function testConstructorCorrectCall2() + { + $options = array( + 'cache_by_default' => false, + 'cached_entity' => new test() + ); + $test = new Zend_Cache_Frontend_Class($options); + } + + public function testConstructorBadCall() + { + $options = array( + 'cached_entity' => new test(), + 0 => true, + ); + try { + $test = new Zend_Cache_Frontend_Class($options); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testCallCorrectCall1() + { + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance1->foobar('param1', 'param2'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('bar', $return); + $this->assertEquals('foo', $data); + } + + public function testCallCorrectCall2() + { + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance1->foobar('param3', 'param4'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param3, param4)', $return); + $this->assertEquals('foobar_output(param3, param4)', $data); + } + + public function testCallCorrectCall3() + { + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance2->foobar2('param1', 'param2'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('bar', $return); + $this->assertEquals('foo', $data); + } + + public function testCallCorrectCall4() + { + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance2->foobar2('param3', 'param4'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar2_return(param3, param4)', $return); + $this->assertEquals('hello !foobar2_output(param3, param4)', $data); + } + + public function testCallCorrectCall5() + { + // cacheByDefault = false + $this->_instance1->setOption('cache_by_default', false); + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance1->foobar('param1', 'param2'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param1, param2)', $return); + $this->assertEquals('foobar_output(param1, param2)', $data); + } + + public function testCallCorrectCall6() + { + // cacheByDefault = false + // cachedMethods = array('foobar') + $this->_instance1->setOption('cache_by_default', false); + $this->_instance1->setOption('cached_methods', array('foobar')); + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance1->foobar('param1', 'param2'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('bar', $return); + $this->assertEquals('foo', $data); + } + + public function testCallCorrectCall7() + { + // cacheByDefault = true + // nonCachedMethods = array('foobar') + $this->_instance1->setOption('cache_by_default', true); + $this->_instance1->setOption('non_cached_methods', array('foobar')); + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance1->foobar('param1', 'param2'); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param1, param2)', $return); + $this->assertEquals('foobar_output(param1, param2)', $data); + } + + public function testConstructorWithABadCachedEntity() + { + try { + $options = array( + 'cached_entity' => array() + ); + $instance = new Zend_Cache_Frontend_Class($options); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + /** + * @group ZF-5034 + */ + public function testCallingConstructorWithInvalidOptionShouldNotRaiseException() + { + $options = array( + 'cached_entity' => new test(), + 'this_key_does_not_exist' => true + ); + $test = new Zend_Cache_Frontend_Class($options); + } +} + diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php new file mode 100644 index 000000000..c93a45125 --- /dev/null +++ b/test/CommonBackendTest.php @@ -0,0 +1,270 @@ +_className = $name; + $this->_root = dirname(__FILE__); + date_default_timezone_set('UTC'); + parent::__construct($name, $data, $dataName); + } + + public function setUp($notag = false) + { + $this->mkdir(); + $this->_instance->setDirectives(array('logging' => true)); + if ($notag) { + $this->_instance->save('bar : data to cache', 'bar'); + $this->_instance->save('bar2 : data to cache', 'bar2'); + $this->_instance->save('bar3 : data to cache', 'bar3'); + } else { + $this->_instance->save('bar : data to cache', 'bar', array('tag3', 'tag4')); + $this->_instance->save('bar2 : data to cache', 'bar2', array('tag3', 'tag1')); + $this->_instance->save('bar3 : data to cache', 'bar3', array('tag2', 'tag3')); + } + } + + public function mkdir() + { + @mkdir($this->getTmpDir()); + } + + public function rmdir() + { + $tmpDir = $this->getTmpDir(false); + foreach (glob("$tmpDir*") as $dirname) { + @rmdir($dirname); + } + } + + public function getTmpDir($date = true) + { + $suffix = ''; + if ($date) { + $suffix = date('mdyHis'); + } + if (is_writeable($this->_root)) { + return $this->_root . DIRECTORY_SEPARATOR . 'zend_cache_tmp_dir_' . $suffix; + } else { + if (getenv('TMPDIR')){ + return getenv('TMPDIR') . DIRECTORY_SEPARATOR . 'zend_cache_tmp_dir_' . $suffix; + } else { + die("no writable tmpdir found"); + } + } + } + + public function tearDown() + { + $this->_instance->clean(); + $this->rmdir(); + } + + public function testConstructorCorrectCall() + { + $this->fail('PLEASE IMPLEMENT A testConstructorCorrectCall !!!'); + } + + public function testConstructorBadOption() + { + try { + $class = $this->_className; + $test = new $class(array(1 => 'bar')); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSetDirectivesCorrectCall() + { + $this->_instance->setDirectives(array('lifetime' => 3600, 'logging' => true)); + } + + public function testSetDirectivesBadArgument() + { + try { + $this->_instance->setDirectives('foo'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSetDirectivesBadDirective() + { + // A bad directive (not known by a specific backend) is possible + // => so no exception here + $this->_instance->setDirectives(array('foo' => true, 'lifetime' => 3600)); + } + + public function testSetDirectivesBadDirective2() + { + try { + $this->_instance->setDirectives(array('foo' => true, 12 => 3600)); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveCorrectCall() + { + $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2')); + $this->assertTrue($res); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => null)); + $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2')); + $this->assertTrue($res); + } + + public function testSaveWithSpecificLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => 3600)); + $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2'), 10); + $this->assertTrue($res); + } + + public function testRemoveCorrectCall() + { + $this->assertTrue($this->_instance->remove('bar')); + $this->assertFalse($this->_instance->test('bar')); + + $this->_instance->remove('barbar'); + $this->assertFalse($this->_instance->test('barbar')); + } + + public function testTestWithAnExistingCacheId() + { + $res = $this->_instance->test('bar'); + if (!$res) { + $this->fail('test() return false'); + } + if (!($res > 999999)) { + $this->fail('test() return an incorrect integer'); + } + return; + } + + public function testTestWithANonExistingCacheId() + { + $this->assertFalse($this->_instance->test('barbar')); + } + + public function testTestWithAnExistingCacheIdAndANullLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => null)); + $res = $this->_instance->test('bar'); + if (!$res) { + $this->fail('test() return false'); + } + if (!($res > 999999)) { + $this->fail('test() return an incorrect integer'); + } + return; + } + + public function testGetWithANonExistingCacheId() + { + $this->assertFalse($this->_instance->load('barbar')); + } + + public function testGetWithAnExistingCacheId() + { + $this->assertEquals('bar : data to cache', $this->_instance->load('bar')); + } + + public function testGetWithAnExistingCacheIdAndUTFCharacters() + { + $data = '"""""' . "'" . '\n' . 'ééééé'; + $this->_instance->save($data, 'foo'); + $this->assertEquals($data, $this->_instance->load('foo')); + } + + public function testGetWithAnExpiredCacheId() + { + $this->_instance->___expire('bar'); + $this->_instance->setDirectives(array('lifetime' => -1)); + $this->assertFalse($this->_instance->load('bar')); + $this->assertEquals('bar : data to cache', $this->_instance->load('bar', true)); + } + + public function testCleanModeAll() + { + $this->assertTrue($this->_instance->clean('all')); + $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->test('bar2')); + } + + public function testCleanModeOld() + { + $this->_instance->___expire('bar2'); + $this->assertTrue($this->_instance->clean('old')); + $this->assertTrue($this->_instance->test('bar') > 999999); + $this->assertFalse($this->_instance->test('bar2')); + } + + public function testCleanModeMatchingTags() + { + $this->assertTrue($this->_instance->clean('matchingTag', array('tag3'))); + $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->test('bar2')); + } + + public function testCleanModeMatchingTags2() + { + $this->assertTrue($this->_instance->clean('matchingTag', array('tag3', 'tag4'))); + $this->assertFalse($this->_instance->test('bar')); + $this->assertTrue($this->_instance->test('bar2') > 999999); + } + + public function testCleanModeNotMatchingTags() + { + $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag3'))); + $this->assertTrue($this->_instance->test('bar') > 999999); + $this->assertTrue($this->_instance->test('bar2') > 999999); + } + + public function testCleanModeNotMatchingTags2() + { + $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag4'))); + $this->assertTrue($this->_instance->test('bar') > 999999); + $this->assertFalse($this->_instance->test('bar2')); + } + + public function testCleanModeNotMatchingTags3() + { + $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag4', 'tag1'))); + $this->assertTrue($this->_instance->test('bar') > 999999); + $this->assertTrue($this->_instance->test('bar2') > 999999); + $this->assertFalse($this->_instance->test('bar3')); + } + +} + + diff --git a/test/CommonExtendedBackendTest.php b/test/CommonExtendedBackendTest.php new file mode 100644 index 000000000..e095403dd --- /dev/null +++ b/test/CommonExtendedBackendTest.php @@ -0,0 +1,194 @@ +_capabilities = $this->_instance->getCapabilities(); + } + + public function testGetFillingPercentage() + { + $res = $this->_instance->getFillingPercentage(); + $this->assertTrue(is_integer($res)); + $this->assertTrue($res >= 0); + $this->assertTrue($res <= 100); + } + + public function testGetIds() + { + if (!($this->_capabilities['get_list'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIds(); + $this->assertTrue(count($res) == 3); + $this->assertTrue(in_array('bar', $res)); + $this->assertTrue(in_array('bar2', $res)); + $this->assertTrue(in_array('bar3', $res)); + } + + public function testGetTags() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getTags(); + $this->assertTrue(count($res) == 4); + $this->assertTrue(in_array('tag1', $res)); + $this->assertTrue(in_array('tag2', $res)); + $this->assertTrue(in_array('tag3', $res)); + $this->assertTrue(in_array('tag4', $res)); + } + + public function testGetIdsMatchingTags() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsMatchingTags(array('tag3')); + $this->assertTrue(count($res) == 3); + $this->assertTrue(in_array('bar', $res)); + $this->assertTrue(in_array('bar2', $res)); + $this->assertTrue(in_array('bar3', $res)); + } + + public function testGetIdsMatchingTags2() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsMatchingTags(array('tag2')); + $this->assertTrue(count($res) == 1); + $this->assertTrue(in_array('bar3', $res)); + } + + public function testGetIdsMatchingTags3() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsMatchingTags(array('tag9999')); + $this->assertTrue(count($res) == 0); + } + + + public function testGetIdsMatchingTags4() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsMatchingTags(array('tag3', 'tag4')); + $this->assertTrue(count($res) == 1); + $this->assertTrue(in_array('bar', $res)); + } + + public function testGetIdsNotMatchingTags() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsNotMatchingTags(array('tag3')); + $this->assertTrue(count($res) == 0); + } + + public function testGetIdsNotMatchingTags2() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsNotMatchingTags(array('tag1')); + $this->assertTrue(count($res) == 2); + $this->assertTrue(in_array('bar', $res)); + $this->assertTrue(in_array('bar3', $res)); + } + + public function testGetIdsNotMatchingTags3() + { + if (!($this->_capabilities['tags'])) { + # unsupported by this backend + return; + } + $res = $this->_instance->getIdsNotMatchingTags(array('tag1', 'tag4')); + $this->assertTrue(count($res) == 1); + $this->assertTrue(in_array('bar3', $res)); + } + + public function testGetMetadatas($notag = false) + { + $res = $this->_instance->getMetadatas('bar'); + $this->assertTrue(isset($res['tags'])); + $this->assertTrue(isset($res['mtime'])); + $this->assertTrue(isset($res['expire'])); + if ($notag) { + $this->assertTrue(count($res['tags']) == 0); + } else { + $this->assertTrue(count($res['tags']) == 2); + $this->assertTrue(in_array('tag3', $res['tags'])); + $this->assertTrue(in_array('tag4', $res['tags'])); + } + $this->assertTrue($res['expire'] > time()); + $this->assertTrue($res['mtime'] <= time()); + } + + public function testTouch() + { + $res = $this->_instance->getMetadatas('bar'); + $bool = $this->_instance->touch('bar', 30); + $this->assertTrue($bool); + $res2 = $this->_instance->getMetadatas('bar'); + $this->assertTrue(($res2['expire'] - $res['expire']) == 30); + $this->assertTrue(($res2['mtime'] >= $res['mtime'])); + } + + public function testGetCapabilities() + { + $res = $this->_instance->getCapabilities(); + $this->assertTrue(isset($res['tags'])); + $this->assertTrue(isset($res['automatic_cleaning'])); + $this->assertTrue(isset($res['expired_read'])); + $this->assertTrue(isset($res['priority'])); + $this->assertTrue(isset($res['infinite_lifetime'])); + $this->assertTrue(isset($res['get_list'])); + } + +} + + diff --git a/test/CoreTest.php b/test/CoreTest.php new file mode 100644 index 000000000..65d305542 --- /dev/null +++ b/test/CoreTest.php @@ -0,0 +1,441 @@ +_instance) { + $this->_instance = new Zend_Cache_Core(array()); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance->setBackend($this->_backend); + } + } + + public function tearDown() + { + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Core(array('lifetime' => 3600, 'caching' => true)); + } + + public function testConstructorBadOption() + { + try { + $test = new Zend_Cache_Core(array(0 => 'bar', 'lifetime' => 3600)); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSetLifeTime() + { + $this->_instance->setLifeTime(3600); + } + + public function testSetBackendCorrectCall1() + { + $backend = new Zend_Cache_Backend_File(array()); + $this->_instance->setBackend($backend); + } + + public function testSetBackendCorrectCall2() + { + $backend = new Zend_Cache_Backend_Test(array()); + $this->_instance->setBackend($backend); + $log = $backend->getLastLog(); + $this->assertEquals('setDirectives', $log['methodName']); + $this->assertType('array', $log['args'][0]); + } + + public function testSetOptionCorrectCall() + { + $this->_instance->setOption('caching', false); + } + + public function testSetOptionBadCall() + { + try { + $this->_instance->setOption(array('lifetime'), 1200); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + /** + * Unknown options are okay and should be silently ignored. Non-string + * options, however, should throw exceptions. + * + * @group ZF-5034 + */ + public function testSetOptionUnknownOption() + { + try { + $this->_instance->setOption(0, 1200); + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } catch (Zend_Cache_Exception $e) { + } + + try { + $this->_instance->setOption('foo', 1200); + } catch (Zend_Cache_Exception $e) { + $this->fail('Zend_Cache_Exception was thrown but should not have been'); + } + } + + public function testSaveCorrectBadCall1() + { + try { + $this->_instance->save('data', 'foo bar'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveCorrectBadCall2() + { + try { + $this->_instance->save('data', 'foobar', array('tag1', 'foo bar')); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveCorrectBadCall3() + { + try { + $this->_instance->save(array('data'), 'foobar'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveWithABadCacheId() + { + try { + $this->_instance->save(array('data'), true); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveWithABadCacheId2() + { + try { + $this->_instance->save(array('data'), 'internal_foo'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveWithABadTags() + { + try { + $this->_instance->save(array('data'), 'foo', 'foobar'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testSaveCorrectCallNoCaching() + { + $i1 = $this->_backend->getLogIndex(); + $this->_instance->setOption('caching', false); + $res = $this->_instance->save('data', 'foo'); + $i2 = $this->_backend->getLogIndex(); + $this->assertTrue($res); + $this->assertEquals($i1, $i2); + } + + public function testSaveCorrectCallNoWriteControl() + { + $this->_instance->setOption('write_control', false); + $res = $this->_instance->save('data', 'foo', array('tag1', 'tag2')); + $log = $this->_backend->getLastLog(); + $expected = array( + 'methodName' => 'save', + 'args' => array( + 0 => 'data', + 1 => 'foo', + 2 => array( + 0 => 'tag1', + 1 => 'tag2' + ) + ) + ); + $this->assertEquals($expected, $log); + } + + public function testSaveCorrectCall() + { + $res = $this->_instance->save('data', 'foo', array('tag1', 'tag2')); + $logs = $this->_backend->getAllLogs(); + $expected1 = array( + 'methodName' => 'save', + 'args' => array( + 0 => 'data', + 1 => 'foo', + 2 => array( + 0 => 'tag1', + 1 => 'tag2' + ) + ) + ); + $expected2 = array( + 'methodName' => 'get', + 'args' => array( + 0 => 'foo', + 1 => true + ) + ); + $expected3 = array( + 'methodName' => 'remove', + 'args' => array( + 0 => 'foo' + ) + ); + $this->assertFalse($res); + $this->assertEquals($expected1, $logs[count($logs) - 3]); + $this->assertEquals($expected2, $logs[count($logs) - 2]); + $this->assertEquals($expected3, $logs[count($logs) - 1]); + } + + public function testSaveCorrectCallButFileCorruption() + { + $res = $this->_instance->save('data', 'false', array('tag1', 'tag2')); + $logs = $this->_backend->getAllLogs(); + $expected1 = array( + 'methodName' => 'save', + 'args' => array( + 0 => 'data', + 1 => 'false', + 2 => array( + 0 => 'tag1', + 1 => 'tag2' + ) + ) + ); + $expected2 = array( + 'methodName' => 'remove', + 'args' => array( + 0 => 'false' + ) + ); + $this->assertFalse($res); + $this->assertEquals($expected1, $logs[count($logs) - 2]); + $this->assertEquals($expected2, $logs[count($logs) - 1]); + } + + public function testSaveCorrectCallWithAutomaticCleaning() + { + $this->_instance->setOption('automatic_cleaning_factor', 1); + $res = $this->_instance->save('data', 'false', array('tag1', 'tag2')); + $logs = $this->_backend->getAllLogs(); + $expected = array( + 'methodName' => 'clean', + 'args' => array( + 0 => 'old', + 1 => array() + ) + ); + $this->assertFalse($res); + $this->assertEquals($expected, $logs[count($logs) - 3]); + } + + public function testTestCorrectCallNoCaching() + { + $i1 = $this->_backend->getLogIndex(); + $this->_instance->setOption('caching', false); + $res = $this->_instance->test('foo'); + $i2 = $this->_backend->getLogIndex(); + $this->assertFalse($res); + $this->assertEquals($i1, $i2); + } + + public function testTestBadCall() + { + try { + $this->_instance->test('foo bar'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testTestCorrectCall1() + { + $res = $this->_instance->test('foo'); + $log = $this->_backend->getLastLog(); + $expected = array( + 'methodName' => 'test', + 'args' => array( + 0 => 'foo' + ) + ); + $this->assertEquals(123456, $res); + $this->assertEquals($expected, $log); + } + + public function testTestCorrectCall2() + { + $res = $this->_instance->test('false'); + $this->assertFalse($res); + } + + public function testGetCorrectCallNoCaching() + { + $i1 = $this->_backend->getLogIndex(); + $this->_instance->setOption('caching', false); + $res = $this->_instance->load('foo'); + $i2 = $this->_backend->getLogIndex(); + $this->assertFalse($res); + $this->assertEquals($i1, $i2); + } + + public function testGetBadCall() + { + try { + $res = $this->_instance->load('foo bar'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testGetCorrectCall1() + { + $res = $this->_instance->load('false'); + $this->assertFalse($res); + } + + public function testGetCorrectCall2() + { + $res = $this->_instance->load('bar'); + $this->assertEquals('foo', 'foo'); + } + + public function testGetCorrectCallWithAutomaticSerialization() + { + $this->_instance->setOption('automatic_serialization', true); + $res = $this->_instance->load('serialized'); + $this->assertEquals(array('foo'), $res); + } + + public function testRemoveBadCall() + { + try { + $res = $this->_instance->remove('foo bar'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testRemoveCorrectCallNoCaching() + { + $i1 = $this->_backend->getLogIndex(); + $this->_instance->setOption('caching', false); + $res = $this->_instance->remove('foo'); + $i2 = $this->_backend->getLogIndex(); + $this->assertTrue($res); + $this->assertEquals($i1, $i2); + } + + public function testRemoveCorrectCall() + { + $res = $this->_instance->remove('foo'); + $log = $this->_backend->getLastLog(); + $expected = array( + 'methodName' => 'remove', + 'args' => array( + 0 => 'foo' + ) + ); + $this->assertTrue($res); + $this->assertEquals($expected, $log); + } + + public function testCleanBadCall1() + { + try { + $res = $this->_instance->clean('matchingTag', array('foo bar', 'foo')); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testCleanBadCall2() + { + try { + $res = $this->_instance->clean('foo'); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testCleanCorrectCallNoCaching() + { + $i1 = $this->_backend->getLogIndex(); + $this->_instance->setOption('caching', false); + $res = $this->_instance->clean('all'); + $i2 = $this->_backend->getLogIndex(); + $this->assertTrue($res); + $this->assertEquals($i1, $i2); + } + + public function testCleanCorrectCall() + { + $res = $this->_instance->clean('matchingTag', array('tag1', 'tag2')); + $log = $this->_backend->getLastLog(); + $expected = array( + 'methodName' => 'clean', + 'args' => array( + 0 => 'matchingTag', + 1 => array( + 0 => 'tag1', + 1 => 'tag2' + ) + ) + ); + $this->assertTrue($res); + $this->assertEquals($expected, $log); + } + +} + + diff --git a/test/FactoryException.php b/test/FactoryException.php new file mode 100644 index 000000000..27cbcbaa2 --- /dev/null +++ b/test/FactoryException.php @@ -0,0 +1,35 @@ +setExpectedException('Zend_Cache_Exception'); + } + + public function testBadFrontend() + { + Zend_Cache::factory('badFrontend', 'File'); + } + + public function testBadBackend() + { + Zend_Cache::factory('Output', 'badBackend'); + } + + public function testFrontendBadParam() + { + Zend_Cache::factory('badFrontend', 'File', array('badParam'=>true)); + } + + public function testBackendBadParam() + { + Zend_Cache::factory('Output', 'badBackend', array(), array('badParam'=>true)); + } + + public function testThrowMethod() + { + Zend_Cache::throwException('test'); + } +} diff --git a/test/FactoryTest.php b/test/FactoryTest.php new file mode 100644 index 000000000..3fee5d6f5 --- /dev/null +++ b/test/FactoryTest.php @@ -0,0 +1,102 @@ +assertEquals('Zend_Cache_Core', get_class($generated_frontend)); + } + + public function testFactoryCorrectCallWithCustomBackend() + { + $generated_frontend = Zend_Cache::factory('Core', 'FooBarTest', array(), array(), false, false, true); + $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); + } + + public function testFactoryCorrectCallWithCustomBackend2() + { + $generated_frontend = Zend_Cache::factory('Core', 'FooBarTestBackend', array(), array(), false, true, true); + $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); + } + + public function testFactoryCorrectCallWithCustomFrontend() + { + $generated_frontend = Zend_Cache::factory('FooBarTest', 'File', array(), array(), false, false, true); + $this->assertEquals('Zend_Cache_Frontend_FooBarTest', get_class($generated_frontend)); + } + + public function testFactoryCorrectCallWithCustomFrontend2() + { + $generated_frontend = Zend_Cache::factory('FooBarTestFrontend', 'File', array(), array(), true, false, true); + $this->assertEquals('FooBarTestFrontend', get_class($generated_frontend)); + } + public function testFactoryLoadsPlatformBackend() + { + try { + $cache = Zend_Cache::factory('Core', 'Zend-Platform'); + } catch (Zend_Cache_Exception $e) { + $message = $e->getMessage(); + if (strstr($message, 'Incorrect backend')) { + $this->fail('Zend Platform is a valid backend'); + } + } + } + + public function testBadFrontend() + { + try { + Zend_Cache::factory('badFrontend', 'File'); + } catch (Zend_Exception $e) { + return; + } + $this->fail('Zend_Exception was expected but not thrown'); + } + + public function testBadBackend() + { + try { + Zend_Cache::factory('Output', 'badBackend'); + } catch (Zend_Exception $e) { + return; + } + $this->fail('Zend_Exception was expected but not thrown'); + } + +} diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php new file mode 100644 index 000000000..81843f1a4 --- /dev/null +++ b/test/FileBackendTest.php @@ -0,0 +1,111 @@ +mkdir(); + $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; + $this->_instance = new Zend_Cache_Backend_File(array( + 'cache_dir' => $this->_cache_dir, + )); + + $logger = new Zend_Log(new Zend_Log_Writer_Null()); + $this->_instance->setDirectives(array('logger' => $logger)); + + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_File(array()); + } + + public function testConstructorWithABadFileNamePrefix() + { + try { + $class = new Zend_Cache_Backend_File(array( + 'file_name_prefix' => 'foo bar' + )); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testGetWithANonExistingCacheIdAndANullLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => null)); + $this->assertFalse($this->_instance->load('barbar')); + } + + public function testSaveCorrectCallWithHashedDirectoryStructure() + { + $this->_instance->setOption('hashed_directory_level', 2); + $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2')); + $this->assertTrue($res); + } + + public function testCleanModeAllWithHashedDirectoryStructure() + { + $this->_instance->setOption('hashed_directory_level', 2); + $this->assertTrue($this->_instance->clean('all')); + $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->test('bar2')); + } + + public function testSaveWithABadCacheDir() + { + $this->_instance->setOption('cache_dir', '/foo/bar/lfjlqsdjfklsqd/'); + $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2')); + $this->assertFalse($res); + } + +} + + diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php new file mode 100644 index 000000000..bf275936a --- /dev/null +++ b/test/FileFrontendTest.php @@ -0,0 +1,205 @@ +_masterFile = $this->_getTmpDirWindows() . DIRECTORY_SEPARATOR . 'zend_cache_master'; + $this->_masterFile1 = $this->_getTmpDirWindows() . DIRECTORY_SEPARATOR . 'zend_cache_master1'; + $this->_masterFile2 = $this->_getTmpDirWindows() . DIRECTORY_SEPARATOR . 'zend_cache_master2'; + } else { + $this->_masterFile = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master'; + $this->_masterFile1 = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master1'; + $this->_masterFile2 = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master2'; + } + if (!$this->_instance1) { + touch($this->_masterFile, 123455); + $this->_instance1 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance1->setBackend($this->_backend); + } + if (!$this->_instance2) { + touch($this->_masterFile); + $this->_instance2 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance2->setBackend($this->_backend); + } + if (!$this->_instance3) { + touch($this->_masterFile1, 123455); + touch($this->_masterFile2, 123455); + $this->_instance3 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance3->setBackend($this->_backend); + } + if (!$this->_instance4) { + touch($this->_masterFile1); + touch($this->_masterFile2); + $this->_instance4 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance4->setBackend($this->_backend); + } + } + + public function tearDown() + { + unset($this->_instance1); + unlink($this->_masterFile); + unlink($this->_masterFile1); + unlink($this->_masterFile2); + } + + private function _getTmpDirWindows() + { + if (isset($_ENV['TEMP'])) { + return $_ENV['TEMP']; + } + if (isset($_ENV['TMP'])) { + return $_ENV['TMP']; + } + if (isset($_ENV['windir'])) { + return $_ENV['windir'] . '\\temp'; + } + if (isset($_ENV['SystemRoot'])) { + return $_ENV['SystemRoot'] . '\\temp'; + } + if (isset($_SERVER['TEMP'])) { + return $_SERVER['TEMP']; + } + if (isset($_SERVER['TMP'])) { + return $_SERVER['TMP']; + } + if (isset($_SERVER['windir'])) { + return $_SERVER['windir'] . '\\temp'; + } + if (isset($_SERVER['SystemRoot'])) { + return $_SERVER['SystemRoot'] . '\\temp'; + } + return '\temp'; + } + + private function _getTmpDirUnix() + { + if (isset($_ENV['TMPDIR'])) { + return $_ENV['TMPDIR']; + } + if (isset($_SERVER['TMPDIR'])) { + return $_SERVER['TMPDIR']; + } + return '/tmp'; + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 'lifetime' => 3600, 'caching' => true)); + } + + public function testConstructorBadCall1() + { + # no masterfile + try { + $test = new Zend_Cache_Frontend_File(array('lifetime' => 3600, 'caching' => true)); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testConstructorBadCall2() + { + # incorrect option + try { + $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 0 => 3600)); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testTestCorrectCall1() + { + $this->assertFalse($this->_instance1->test('false')); + } + + public function testTestCorrectCall2() + { + $this->assertTrue($this->_instance1->test('cache_id') > 1); + } + + public function testTestCorrectCall3() + { + $this->assertFalse($this->_instance2->test('cache_id')); + } + + public function testGetCorrectCall1() + { + $this->assertFalse($this->_instance1->load('false')); + } + + public function testGetCorrectCall2() + { + $this->assertEquals('foo', $this->_instance1->load('cache_id')); + } + + public function testTestCorrectCall4() + { + $this->assertFalse($this->_instance4->test('cache_id')); + } + + public function testTestCorrectCall5() + { + $this->assertFalse($this->_instance3->load('false')); + } + + public function testGetCorrectCall3() + { + $this->assertFalse($this->_instance2->load('cache_id')); + } + + public function testConstructorWithABadMasterFile() + { + try { + $instance = new Zend_Cache_Frontend_File(array('master_file' => '/foo/bar/ljhfdjh/qhskldhqjk')); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testGetWithDoNotTestCacheValidity() + { + $this->assertEquals('foo', $this->_instance1->load('cache_id', true)); + } + +} + + diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php new file mode 100644 index 000000000..f02222206 --- /dev/null +++ b/test/FunctionFrontendTest.php @@ -0,0 +1,159 @@ +_instance) { + $this->_instance = new Zend_Cache_Frontend_Function(array()); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance->setBackend($this->_backend); + } + } + + public function tearDown() + { + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $options = array( + 'cache_by_default' => false, + 'cached_functions' => array('foo', 'bar') + ); + $test = new Zend_Cache_Frontend_Function($options); + } + + public function testConstructorBadCall() + { + $options = array( + 'cache_by_default' => false, + 0 => array('foo', 'bar') + ); + try { + $test = new Zend_Cache_Frontend_Function($options); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testCallCorrectCall1() + { + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance->call('foobar', array('param1', 'param2')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('bar', $return); + $this->assertEquals('foo', $data); + } + + public function testCallCorrectCall2() + { + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance->call('foobar', array('param3', 'param4')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param3, param4)', $return); + $this->assertEquals('foobar_output(param3, param4)', $data); + } + + public function testCallCorrectCall3() + { + // cacheByDefault = false + $this->_instance->setOption('cache_by_default', false); + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance->call('foobar', array('param1', 'param2')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param1, param2)', $return); + $this->assertEquals('foobar_output(param1, param2)', $data); + } + + public function testCallCorrectCall4() + { + // cacheByDefault = false + // cachedFunctions = array('foobar') + $this->_instance->setOption('cache_by_default', false); + $this->_instance->setOption('cached_functions', array('foobar')); + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance->call('foobar', array('param1', 'param2')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('bar', $return); + $this->assertEquals('foo', $data); + } + + public function testCallCorrectCall5() + { + // cacheByDefault = true + // nonCachedFunctions = array('foobar') + $this->_instance->setOption('cache_by_default', true); + $this->_instance->setOption('non_cached_functions', array('foobar')); + ob_start(); + ob_implicit_flush(false); + $return = $this->_instance->call('foobar', array('param1', 'param2')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param1, param2)', $return); + $this->assertEquals('foobar_output(param1, param2)', $data); + } + + public function testCallWithABadSyntax1() + { + try { + $this->_instance->call(1, array()); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testCallWithABadSyntax2() + { + try { + $this->_instance->call('foo', 1); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } +} + diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php new file mode 100644 index 000000000..93dca0791 --- /dev/null +++ b/test/MemcachedBackendTest.php @@ -0,0 +1,141 @@ + TESTS_ZEND_CACHE_MEMCACHED_HOST, + 'port' => TESTS_ZEND_CACHE_MEMCACHED_PORT, + 'persistent' => TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT + ); + $options = array( + 'servers' => array(0 => $server) + ); + $this->_instance = new Zend_Cache_Backend_Memcached($options); + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + // We have to wait after a memcache flush + sleep(1); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_Memcached(); + } + + public function testCleanModeOld() + { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() + { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() + { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testGetWithCompression() + { + $this->_instance->setOption('compression', true); + $this->testGetWithAnExistingCacheIdAndUTFCharacters(); + } + + public function testConstructorWithAnAlternativeSyntax() + { + $server = array( + 'host' => TESTS_ZEND_CACHE_MEMCACHED_HOST, + 'port' => TESTS_ZEND_CACHE_MEMCACHED_PORT, + 'persistent' => TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT + ); + $options = array( + 'servers' => $server + ); + $this->_instance = new Zend_Cache_Backend_Memcached($options); + $this->testGetWithAnExistingCacheIdAndUTFCharacters(); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testGetMetadatas($notag = false) + { + parent::testGetMetadatas(true); + } + +} + + diff --git a/test/OutputFrontendTest.php b/test/OutputFrontendTest.php new file mode 100644 index 000000000..3a75cf2d6 --- /dev/null +++ b/test/OutputFrontendTest.php @@ -0,0 +1,74 @@ +_instance) { + $this->_instance = new Zend_Cache_Frontend_Output(array()); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance->setBackend($this->_backend); + } + } + + public function tearDown() + { + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Frontend_Output(array('lifetime' => 3600, 'caching' => true)); + } + + public function testStartEndCorrectCall1() + { + ob_start(); + ob_implicit_flush(false); + if (!($this->_instance->start('123'))) { + echo('foobar'); + $this->_instance->end(); + } + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foo', $data); + } + + public function testStartEndCorrectCall2() + { + ob_start(); + ob_implicit_flush(false); + if (!($this->_instance->start('false'))) { + echo('foobar'); + $this->_instance->end(); + } + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar', $data); + } +} + diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php new file mode 100644 index 000000000..5c34499c7 --- /dev/null +++ b/test/PageFrontendTest.php @@ -0,0 +1,187 @@ +_instance) { + $this->_instance = new Zend_Cache_Frontend_Page(array()); + $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance->setBackend($this->_backend); + } + } + + public function tearDown() + { + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Frontend_Page(array('lifetime' => 3600, 'caching' => true)); + } + + public function testConstructorUnimplementedOption() + { + try { + $test = new Zend_Cache_Frontend_Page(array('http_conditional' => true)); + } catch (Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testConstructorWithBadDefaultOptions() + { + try { + $test = new Zend_Cache_Frontend_Page(array('default_options' => 'foo')); + } catch (Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + /** + * The only bad default options are non-string keys + * @group ZF-5034 + */ + public function testConstructorWithBadDefaultOptions2() + { + try { + $test = new Zend_Cache_Frontend_Page(array('default_options' => array('cache' => true, 1 => 'bar'))); + } catch (Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testConstructorWithBadRegexps() + { + try { + $test = new Zend_Cache_Frontend_Page(array('regexps' => 'foo')); + } catch (Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testConstructorWithBadRegexps2() + { + try { + $test = new Zend_Cache_Frontend_Page(array('regexps' => array('foo', 'bar'))); + } catch (Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + /** + * Only non-string keys should raise exceptions + * @group ZF-5034 + */ + public function testConstructorWithBadRegexps3() + { + $array = array( + '^/$' => array('cache' => true), + '^/index/' => array('cache' => true), + '^/article/' => array('cache' => false), + '^/article/view/' => array( + 1 => true, + 'cache_with_post_variables' => true, + 'make_id_with_post_variables' => true, + ) + ); + try { + $test = new Zend_Cache_Frontend_Page(array('regexps' => $array)); + } catch (Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testConstructorWithGoodRegexps() + { + $array = array( + '^/$' => array('cache' => true), + '^/index/' => array('cache' => true), + '^/article/' => array('cache' => false), + '^/article/view/' => array( + 'cache' => true, + 'cache_with_post_variables' => true, + 'make_id_with_post_variables' => true, + ) + ); + $test = new Zend_Cache_Frontend_Page(array('regexps' => $array)); + } + + public function testConstructorWithGoodDefaultOptions() + { + $test = new Zend_Cache_Frontend_Page(array('default_options' => array('cache' => true))); + } + + public function testStartEndCorrectCall1() + { + ob_start(); + ob_implicit_flush(false); + if (!($this->_instance->start('serialized2', true))) { + echo('foobar'); + ob_end_flush(); + } + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foo', $data); + } + + public function testStartEndCorrectCall2() + { + ob_start(); + ob_implicit_flush(false); + if (!($this->_instance->start('false', true))) { + echo('foobar'); + ob_end_flush(); + } + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar', $data); + } + + public function testStartEndCorrectCallWithDebug() + { + $this->_instance->setOption('debug_header', true); + ob_start(); + ob_implicit_flush(false); + if (!($this->_instance->start('serialized2', true))) { + echo('foobar'); + ob_end_flush(); + } + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('DEBUG HEADER : This is a cached page !foo', $data); + } +} + diff --git a/test/SkipTests.php b/test/SkipTests.php new file mode 100644 index 000000000..9034279d1 --- /dev/null +++ b/test/SkipTests.php @@ -0,0 +1,85 @@ +markTestSkipped($this->message); + } + + public function testCacheBackend() + { + // this is here only so we have at least one test + } + +} + +class Zend_Cache_ApcBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} + +class Zend_Cache_XcacheBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} + +class Zend_Cache_MemcachedBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} + +class Zend_Cache_SqliteBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} + +class Zend_Cache_ZendPlatformBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} + +class Zend_Cache_TwoLevelsBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} + +class Zend_Cache_ZendServerTest_SkipTests extends Zend_Cache_BackendTest_SkipTests +{ +} diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php new file mode 100644 index 000000000..c54ea11ef --- /dev/null +++ b/test/SqliteBackendTest.php @@ -0,0 +1,97 @@ +getTmpDir()); + $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; + $this->_instance = new Zend_Cache_Backend_Sqlite(array( + 'cache_db_complete_path' => $this->_cache_dir . 'cache.db' + )); + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + @unlink($this->_cache_dir . 'cache.db'); + $this->rmdir(); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_Sqlite(array('cache_db_complete_path' => $this->_cache_dir . 'cache.db')); + } + + public function testConstructorWithABadDBPath() + { + try { + $test = new Zend_Cache_Backend_Sqlite(array('cache_db_complete_path' => '/foo/bar/lfjlqsdjfklsqd/cache.db')); + } catch (Zend_Cache_Exception $e) { + return; + } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + + public function testCleanModeAllWithVacuum() + { + $this->_instance = new Zend_Cache_Backend_Sqlite(array( + 'cache_db_complete_path' => $this->_cache_dir . 'cache.db', + 'automatic_vacuum_factor' => 1 + )); + parent::setUp(); + $this->assertTrue($this->_instance->clean('all')); + $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->test('bar2')); + } + + public function testRemoveCorrectCallWithVacuum() + { + $this->_instance = new Zend_Cache_Backend_Sqlite(array( + 'cache_db_complete_path' => $this->_cache_dir . 'cache.db', + 'automatic_vacuum_factor' => 1 + )); + parent::setUp(); + $this->assertTrue($this->_instance->remove('bar')); + $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->remove('barbar')); + $this->assertFalse($this->_instance->test('barbar')); + } + +} + + diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php new file mode 100644 index 000000000..e3f9cf7c6 --- /dev/null +++ b/test/TwoLevelsBackendTest.php @@ -0,0 +1,82 @@ +getTmpDir()); + $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; + $slowBackend = 'File'; + $fastBackend = 'Apc'; + $slowBackendOptions = array( + 'cache_dir' => $this->_cache_dir + ); + $fastBackendOptions = array( + ); + $this->_instance = new Zend_Cache_Backend_TwoLevels(array( + 'fast_backend' => $fastBackend, + 'slow_backend' => $slowBackend, + 'fast_backend_options' => $fastBackendOptions, + 'slow_backend_options' => $slowBackendOptions + )); + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $slowBackend = 'File'; + $fastBackend = 'Apc'; + $slowBackendOptions = array( + 'cache_dir' => $this->_cache_dir + ); + $fastBackendOptions = array( + ); + $test = new Zend_Cache_Backend_TwoLevels(array( + 'fast_backend' => $fastBackend, + 'slow_backend' => $slowBackend, + 'fast_backend_options' => $fastBackendOptions, + 'slow_backend_options' => $slowBackendOptions + )); + } + +} + + diff --git a/test/XcacheBackendTest.php b/test/XcacheBackendTest.php new file mode 100644 index 000000000..4be125d4b --- /dev/null +++ b/test/XcacheBackendTest.php @@ -0,0 +1,106 @@ +_instance = new Zend_Cache_Backend_Xcache(array( + 'user' => TESTS_ZEND_CACHE_XCACHE_USER, + 'password' => TESTS_ZEND_CACHE_XCACHE_PASSWORD + )); + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_Xcache(); + } + + public function testCleanModeOld() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + +} + + diff --git a/test/ZendPlatformBackendTest.php b/test/ZendPlatformBackendTest.php new file mode 100644 index 000000000..bfde91ad1 --- /dev/null +++ b/test/ZendPlatformBackendTest.php @@ -0,0 +1,81 @@ +markTestSkipped('Zend Platform is not installed, skipping test'); + return; + } + $this->_instance = new Zend_Cache_Backend_ZendPlatform(array()); + parent::setUp($notag); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_ZendPlatform(); + } + + public function testRemoveCorrectCall() + { + $this->assertTrue($this->_instance->remove('bar')); + $this->assertFalse($this->_instance->test('bar')); + $this->assertTrue($this->_instance->remove('barbar')); + $this->assertFalse($this->_instance->test('barbar')); + } + + public function testGetWithAnExpiredCacheId() + { + sleep(2); + $this->_instance->setDirectives(array('lifetime' => 1)); + $this->assertEquals('bar : data to cache', $this->_instance->load('bar', true)); + $this->assertFalse($this->_instance->load('bar')); + $this->_instance->setDirectives(array('lifetime' => 3600)); + } + + // Because of limitations of this backend... + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testCleanModeOld() {} + public function testCleanModeNotMatchingTags() {} +} + + diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php new file mode 100755 index 000000000..011e1753b --- /dev/null +++ b/test/ZendServerDiskTest.php @@ -0,0 +1,102 @@ +_instance = new Zend_Cache_Backend_ZendServer_Disk(); + parent::setUp(true); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_ZendServer_Disk(); + } + + public function testCleanModeOld() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + +} + diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php new file mode 100755 index 000000000..d950cb16e --- /dev/null +++ b/test/ZendServerShMemTest.php @@ -0,0 +1,101 @@ +_instance = new Zend_Cache_Backend_ZendServer_ShMem(); + parent::setUp(true); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_ZendServer_ShMem(); + } + + public function testCleanModeOld() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } +} + diff --git a/test/bootstrap.php b/test/bootstrap.php new file mode 100644 index 000000000..f6a38110b --- /dev/null +++ b/test/bootstrap.php @@ -0,0 +1,34 @@ + Date: Sat, 16 May 2009 08:55:55 +0000 Subject: [PATCH 002/311] better tmpdir autodetection ? git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@15601 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 85 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 63 insertions(+), 22 deletions(-) diff --git a/src/Backend.php b/src/Backend.php index c0500327a..504b82817 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -139,34 +139,75 @@ public function isAutomaticCleaningAvailable() { return true; } - + /** - * Return a system-wide tmp directory + * Determine system TMP directory and detect if we have read access + * + * inspired from Zend_File_Transfer_Adapter_Abstract * - * @return string System-wide tmp directory + * @return string + * @throws Zend_Cache_Exception if unable to determine directory */ - static function getTmpDir() + public function getTmpDir() { - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - // windows... - foreach (array($_ENV, $_SERVER) as $tab) { - foreach (array('TEMP', 'TMP', 'windir', 'SystemRoot') as $key) { - if (isset($tab[$key])) { - $result = $tab[$key]; - if (($key == 'windir') or ($key == 'SystemRoot')) { - $result = $result . '\\temp'; - } - return $result; + $tmpdir = array(); + foreach (array($_ENV, $_SERVER) as $tab) { + foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) { + if (isset($tab[$key])) { + if (($key == 'windir') or ($key == 'SystemRoot')) { + $dir = realpath($tab[$key] . '\\temp'); + } else { + $dir = realpath($tab[$key]); } - } - } - return '\\temp'; - } else { - // unix... - if (isset($_ENV['TMPDIR'])) return $_ENV['TMPDIR']; - if (isset($_SERVER['TMPDIR'])) return $_SERVER['TMPDIR']; - return '/tmp'; + 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); + 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 $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; } /** From a9ca599b90e41d6e1dbcb25133867e090458169c Mon Sep 17 00:00:00 2001 From: "yoshida@zend.co.jp" Date: Mon, 8 Jun 2009 01:40:37 +0000 Subject: [PATCH 003/311] [ZF-6943]Wrong error message in Zend_Cache_Backend_TwoLevels Exception git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@15931 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/TwoLevels.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index bcdaff97a..5bf3848d6 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -132,7 +132,7 @@ public function __construct(array $options = array()) Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); } if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) { - Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); + Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); } $this->_slowBackend->setDirectives($this->_directives); $this->_fastBackend->setDirectives($this->_directives); From 6dbf222074910db07208cb8a5cb488ae1247f31b Mon Sep 17 00:00:00 2001 From: fab Date: Tue, 9 Jun 2009 17:16:32 +0000 Subject: [PATCH 004/311] additional test for some particular configurations git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@15955 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Backend.php b/src/Backend.php index 504b82817..f65ae335c 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -183,7 +183,9 @@ public function getTmpDir() if ($tempFile) { $dir = realpath(dirname($tempFile)); unlink($tempFile); - return $dir; + if ($this->_isGoodTmpDir($dir)) { + return $dir; + } } if ($this->_isGoodTmpDir('/tmp')) { return '/tmp'; From 1d3ce5b640f8a1ffeab6c51f1ca27bb8dfd9e666 Mon Sep 17 00:00:00 2001 From: thomas Date: Sun, 21 Jun 2009 18:50:06 +0000 Subject: [PATCH 005/311] [ZF-6295] Generic: - fixed license date (partitial) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16200 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 4 ++-- src/Backend/Apc.php | 4 ++-- src/Backend/ExtendedInterface.php | 4 ++-- src/Backend/File.php | 4 ++-- src/Backend/Interface.php | 4 ++-- src/Backend/Memcached.php | 4 ++-- src/Backend/Sqlite.php | 4 ++-- src/Backend/Test.php | 4 ++-- src/Backend/TwoLevels.php | 4 ++-- src/Backend/Xcache.php | 4 ++-- src/Backend/ZendPlatform.php | 4 ++-- src/Backend/ZendServer.php | 2 +- src/Backend/ZendServer/Disk.php | 2 +- src/Backend/ZendServer/ShMem.php | 2 +- src/Core.php | 4 ++-- src/Exception.php | 4 ++-- src/Frontend/Class.php | 4 ++-- src/Frontend/File.php | 4 ++-- src/Frontend/Function.php | 4 ++-- src/Frontend/Output.php | 4 ++-- src/Frontend/Page.php | 4 ++-- 21 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/Backend.php b/src/Backend.php index f65ae335c..8f6ed4dbc 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Backend diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php index 39481639c..67ec63f14 100644 --- a/src/Backend/Apc.php +++ b/src/Backend/Apc.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php index 43d40eeb8..87fbe07e1 100644 --- a/src/Backend/ExtendedInterface.php +++ b/src/Backend/ExtendedInterface.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/File.php b/src/Backend/File.php index 3e114b20f..8e272f23f 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -33,7 +33,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/Interface.php b/src/Backend/Interface.php index 09798b1cc..f6ab2c260 100644 --- a/src/Backend/Interface.php +++ b/src/Backend/Interface.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Zend_Cache_Backend_Interface diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 33c2accb4..0b8eba51d 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index 595d5de1d..3483bfeaf 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -33,7 +33,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface diff --git a/src/Backend/Test.php b/src/Backend/Test.php index b2146121a..c28d93969 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -33,7 +33,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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_Interface diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 5bf3848d6..4a6b71729 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php index e6064ba85..c28bc4f2d 100644 --- a/src/Backend/Xcache.php +++ b/src/Backend/Xcache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/ZendPlatform.php b/src/Backend/ZendPlatform.php index 1f0585eeb..69a81eeb3 100644 --- a/src/Backend/ZendPlatform.php +++ b/src/Backend/ZendPlatform.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -35,7 +35,7 @@ * * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index 5b9853ce1..190ebf063 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index ed64335ef..339694f4a 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index 9cd18e524..213c266ee 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Core.php b/src/Core.php index 143b89ef9..1e2b21433 100644 --- a/src/Core.php +++ b/src/Core.php @@ -14,14 +14,14 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * @package Zend_Cache - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Core diff --git a/src/Exception.php b/src/Exception.php index a46d8ca25..806c34e96 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @package Zend_Cache - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 {} diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index 659431d50..112413a94 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -28,7 +28,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Frontend/File.php b/src/Frontend/File.php index 8b905d093..777e36aab 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index b059b30ff..a27b28648 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Frontend/Output.php b/src/Frontend/Output.php index 6896dfb6c..88c23f7a9 100644 --- a/src/Frontend/Output.php +++ b/src/Frontend/Output.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index c31a5c2c8..93897c24a 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 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 From ce3bdf3ee510cdce4ac121a95d477681a9f69cb0 Mon Sep 17 00:00:00 2001 From: thomas Date: Sun, 21 Jun 2009 20:34:55 +0000 Subject: [PATCH 006/311] [ZF-6295] Generic: - fixed license date (partitial) THE LAST COMMIT... HONESTLY :-) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16225 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/AllTests.php | 4 ++-- test/SkipTests.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/AllTests.php b/test/AllTests.php index 269522a9c..e1894395b 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -50,7 +50,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_AllTests diff --git a/test/SkipTests.php b/test/SkipTests.php index 9034279d1..bda451b63 100644 --- a/test/SkipTests.php +++ b/test/SkipTests.php @@ -16,7 +16,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -36,7 +36,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Cache_BackendTest_SkipTests extends PHPUnit_Framework_TestCase From 723351c7e3a0a140675041c01d1c350fcf17482c Mon Sep 17 00:00:00 2001 From: bkarwin Date: Tue, 7 Jul 2009 06:59:03 +0000 Subject: [PATCH 007/311] ZF-507 update @copyright and other tags git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16541 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 1 + src/Backend/Apc.php | 1 + src/Backend/ExtendedInterface.php | 1 + src/Backend/File.php | 1 + src/Backend/Interface.php | 1 + src/Backend/Memcached.php | 1 + src/Backend/Sqlite.php | 1 + src/Backend/Test.php | 1 + src/Backend/TwoLevels.php | 1 + src/Backend/Xcache.php | 1 + src/Backend/ZendPlatform.php | 1 + src/Backend/ZendServer.php | 1 + src/Backend/ZendServer/Disk.php | 1 + src/Backend/ZendServer/ShMem.php | 1 + src/Core.php | 1 + src/Exception.php | 1 + src/Frontend/Class.php | 1 + src/Frontend/File.php | 1 + src/Frontend/Function.php | 1 + src/Frontend/Output.php | 1 + src/Frontend/Page.php | 1 + 21 files changed, 21 insertions(+) diff --git a/src/Backend.php b/src/Backend.php index 8f6ed4dbc..cf74e2585 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php index 67ec63f14..01a86bd90 100644 --- a/src/Backend/Apc.php +++ b/src/Backend/Apc.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php index 87fbe07e1..cae8f504f 100644 --- a/src/Backend/ExtendedInterface.php +++ b/src/Backend/ExtendedInterface.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ /** diff --git a/src/Backend/File.php b/src/Backend/File.php index 8e272f23f..27e830989 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ /** diff --git a/src/Backend/Interface.php b/src/Backend/Interface.php index f6ab2c260..99d15fa22 100644 --- a/src/Backend/Interface.php +++ b/src/Backend/Interface.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 0b8eba51d..bc899292a 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index 3483bfeaf..d17204094 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/Test.php b/src/Backend/Test.php index c28d93969..49cfd4423 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 4a6b71729..9fea2b97a 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php index c28bc4f2d..4cdabff17 100644 --- a/src/Backend/Xcache.php +++ b/src/Backend/Xcache.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/ZendPlatform.php b/src/Backend/ZendPlatform.php index 69a81eeb3..4e55bda6a 100644 --- a/src/Backend/ZendPlatform.php +++ b/src/Backend/ZendPlatform.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ /** diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index 190ebf063..ec8cb29a3 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index 339694f4a..11fb9f639 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index 213c266ee..fca91fd2f 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Core.php b/src/Core.php index 1e2b21433..599bd7bd0 100644 --- a/src/Core.php +++ b/src/Core.php @@ -16,6 +16,7 @@ * @package Zend_Cache * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Exception.php b/src/Exception.php index 806c34e96..7c2d56f61 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -16,6 +16,7 @@ * @package Zend_Cache * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ /** diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index 112413a94..16dea0350 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ /** diff --git a/src/Frontend/File.php b/src/Frontend/File.php index 777e36aab..84fa84dd6 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index a27b28648..36a8d93e8 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Frontend/Output.php b/src/Frontend/Output.php index 88c23f7a9..8b5d925c4 100644 --- a/src/Frontend/Output.php +++ b/src/Frontend/Output.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index 93897c24a..47dc548ea 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ From 293be628d9a9f7e2769b924924f1428504d01c16 Mon Sep 17 00:00:00 2001 From: mikaelkael Date: Mon, 20 Jul 2009 09:08:49 +0000 Subject: [PATCH 008/311] Zend_Cache_Backend_ZendServer: remove bad phpDoc git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16865 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/ZendServer.php | 2 -- src/Backend/ZendServer/Disk.php | 2 -- src/Backend/ZendServer/ShMem.php | 2 -- 3 files changed, 6 deletions(-) diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index ec8cb29a3..627c1c8f6 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -61,9 +61,7 @@ abstract protected function _store($data, $id, $timeToLive); /** * Fetch data * - * @var mixed $data Object to store * @var string $id Cache id - * @var int $timeToLive Time to live in seconds * @throws Zend_Cache_Exception */ abstract protected function _fetch($id); diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index 11fb9f639..8e1147617 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -72,9 +72,7 @@ protected function _store($data, $id, $timeToLive) /** * Fetch data * - * @var mixed $data Object to store * @var string $id Cache id - * @var int $timeToLive Time to live in seconds */ protected function _fetch($id) { diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index fca91fd2f..115aa7ee9 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -72,9 +72,7 @@ protected function _store($data, $id, $timeToLive) /** * Fetch data * - * @var mixed $data Object to store * @var string $id Cache id - * @var int $timeToLive Time to live in seconds */ protected function _fetch($id) { From 55b22d0c26acf58de78fffc07e8d05f1a33a3f98 Mon Sep 17 00:00:00 2001 From: mikaelkael Date: Mon, 20 Jul 2009 09:57:50 +0000 Subject: [PATCH 009/311] ZF-7315: review phpDoc for API documentation generation (Zend_Cache) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16867 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/ZendServer.php | 10 +++++----- src/Backend/ZendServer/Disk.php | 10 +++++----- src/Backend/ZendServer/ShMem.php | 10 +++++----- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index 627c1c8f6..87af6eae1 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -51,9 +51,9 @@ abstract class Zend_Cache_Backend_ZendServer extends Zend_Cache_Backend implemen /** * Store data * - * @var mixed $data Object to store - * @var string $id Cache id - * @var int $timeToLive Time to live in seconds + * @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); @@ -61,7 +61,7 @@ abstract protected function _store($data, $id, $timeToLive); /** * Fetch data * - * @var string $id Cache id + * @param string $id Cache id * @throws Zend_Cache_Exception */ abstract protected function _fetch($id); @@ -69,7 +69,7 @@ abstract protected function _fetch($id); /** * Unset data * - * @var string $id Cache id + * @param string $id Cache id */ abstract protected function _unset($id); diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index 8e1147617..30f5e06e7 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -53,9 +53,9 @@ public function __construct(array $options = array()) /** * Store data * - * @var mixed $data Object to store - * @var string $id Cache id - * @var int $timeToLive Time to live in seconds + * @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) @@ -72,7 +72,7 @@ protected function _store($data, $id, $timeToLive) /** * Fetch data * - * @var string $id Cache id + * @param string $id Cache id */ protected function _fetch($id) { @@ -82,7 +82,7 @@ protected function _fetch($id) /** * Unset data * - * @var string $id Cache id + * @param string $id Cache id * @return boolean true if no problem */ protected function _unset($id) diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index 115aa7ee9..8cfc0344b 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -53,9 +53,9 @@ public function __construct(array $options = array()) /** * Store data * - * @var mixed $data Object to store - * @var string $id Cache id - * @var int $timeToLive Time to live in seconds + * @param mixed $data Object to store + * @param string $id Cache id + * @param int $timeToLive Time to live in seconds * */ protected function _store($data, $id, $timeToLive) @@ -72,7 +72,7 @@ protected function _store($data, $id, $timeToLive) /** * Fetch data * - * @var string $id Cache id + * @param string $id Cache id */ protected function _fetch($id) { @@ -82,7 +82,7 @@ protected function _fetch($id) /** * Unset data * - * @var string $id Cache id + * @param string $id Cache id * @return boolean true if no problem */ protected function _unset($id) From a5eebc1f18753f507df342748ec3365320f3e559 Mon Sep 17 00:00:00 2001 From: matthew Date: Wed, 22 Jul 2009 19:22:34 +0000 Subject: [PATCH 010/311] [PHP 5.3 COMPAT] Removed code referencing set_magic_quotes_runtime; deprecated in 5.3 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16973 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index 27e830989..29a89ca1d 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -947,10 +947,6 @@ protected function _fileGetContents($file) if (!is_file($file)) { return false; } - if (function_exists('get_magic_quotes_runtime')) { - $mqr = @get_magic_quotes_runtime(); - @set_magic_quotes_runtime(0); - } $f = @fopen($file, 'rb'); if ($f) { if ($this->_options['file_locking']) @flock($f, LOCK_SH); From 7d386d2c2accaa0131be50b7b96095b026e3b8c8 Mon Sep 17 00:00:00 2001 From: matthew Date: Wed, 22 Jul 2009 19:23:08 +0000 Subject: [PATCH 011/311] [PHP 5.3 COMPAT] s/split/explode/ git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@16974 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/Page.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index 47dc548ea..da68855ed 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -314,7 +314,7 @@ public function _flush($data) $headersList = headers_list(); foreach($this->_specificOptions['memorize_headers'] as $key=>$headerName) { foreach ($headersList as $headerSent) { - $tmp = split(':', $headerSent); + $tmp = explode(':', $headerSent); $headerSentName = trim(array_shift($tmp)); if (strtolower($headerName) == strtolower($headerSentName)) { $headerSentValue = trim(implode(':', $tmp)); From ffe4bc60116e3dcf6fba20d3121dd9b52a65f1f6 Mon Sep 17 00:00:00 2001 From: matthew Date: Fri, 24 Jul 2009 11:55:45 +0000 Subject: [PATCH 012/311] ZF-7375: Remove call to set_magic_quotes git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17028 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index 29a89ca1d..f0f3bed11 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -954,9 +954,6 @@ protected function _fileGetContents($file) if ($this->_options['file_locking']) @flock($f, LOCK_UN); @fclose($f); } - if (function_exists('set_magic_quotes_runtime')) { - @set_magic_quotes_runtime($mqr); - } return $result; } From e184097e2d73c7cb7861bd68efd2c9f0d70c3fa2 Mon Sep 17 00:00:00 2001 From: "yoshida@zend.co.jp" Date: Sat, 8 Aug 2009 04:12:44 +0000 Subject: [PATCH 013/311] [ZF-7498]Line endings in Zend/Cache git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17442 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/ZendServer.php | 414 +++++++++++++++---------------- src/Backend/ZendServer/Disk.php | 200 +++++++-------- src/Backend/ZendServer/ShMem.php | 200 +++++++-------- 3 files changed, 407 insertions(+), 407 deletions(-) diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index 87af6eae1..4b82939b3 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -1,207 +1,207 @@ - (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 !== null) { - 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; - } - } -} + (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 !== null) { + 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; + } + } +} diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index 30f5e06e7..43cca0d6c 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -1,100 +1,100 @@ -_options['namespace'] . '::' . $id, - $data, - $timeToLive) === false) { - $this->_log('Store operation failed.'); - return false; - } - return true; - } - - /** - * Fetch data - * - * @param string $id Cache id - */ - 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']); - } -} +_options['namespace'] . '::' . $id, + $data, + $timeToLive) === false) { + $this->_log('Store operation failed.'); + return false; + } + return true; + } + + /** + * Fetch data + * + * @param string $id Cache id + */ + 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']); + } +} diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index 8cfc0344b..8f2ef6a5e 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -1,100 +1,100 @@ -_options['namespace'] . '::' . $id, - $data, - $timeToLive) === false) { - $this->_log('Store operation failed.'); - return false; - } - return true; - } - - /** - * Fetch data - * - * @param string $id Cache id - */ - 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']); - } -} +_options['namespace'] . '::' . $id, + $data, + $timeToLive) === false) { + $this->_log('Store operation failed.'); + return false; + } + return true; + } + + /** + * Fetch data + * + * @param string $id Cache id + */ + 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']); + } +} From 4e1057e1445967941ef5bee2e71ebacac6389ca6 Mon Sep 17 00:00:00 2001 From: "yoshida@zend.co.jp" Date: Sat, 8 Aug 2009 04:15:13 +0000 Subject: [PATCH 014/311] [ZF-7498]Line endings in Zend/Cache git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17443 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/ZendServerDiskTest.php | 204 +++++++++++++++++------------------ test/ZendServerShMemTest.php | 202 +++++++++++++++++----------------- 2 files changed, 203 insertions(+), 203 deletions(-) diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index 011e1753b..0906a447f 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -1,102 +1,102 @@ -_instance = new Zend_Cache_Backend_ZendServer_Disk(); - parent::setUp(true); - } - - public function tearDown() - { - parent::tearDown(); - unset($this->_instance); - } - - public function testConstructorCorrectCall() - { - $test = new Zend_Cache_Backend_ZendServer_Disk(); - } - - public function testCleanModeOld() { - $this->_instance->setDirectives(array('logging' => false)); - $this->_instance->clean('old'); - // do nothing, just to see if an error occured - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testCleanModeMatchingTags() { - $this->_instance->setDirectives(array('logging' => false)); - $this->_instance->clean('matchingTag', array('tag1')); - // do nothing, just to see if an error occured - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testCleanModeNotMatchingTags() { - $this->_instance->setDirectives(array('logging' => false)); - $this->_instance->clean('notMatchingTag', array('tag1')); - // do nothing, just to see if an error occured - $this->_instance->setDirectives(array('logging' => true)); - } - - // Because of limitations of this backend... - public function testGetWithAnExpiredCacheId() {} - public function testCleanModeMatchingTags2() {} - public function testCleanModeNotMatchingTags2() {} - public function testCleanModeNotMatchingTags3() {} - public function testSaveCorrectCall() - { - $this->_instance->setDirectives(array('logging' => false)); - parent::testSaveCorrectCall(); - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testSaveWithNullLifeTime() - { - $this->_instance->setDirectives(array('logging' => false)); - parent::testSaveWithNullLifeTime(); - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testSaveWithSpecificLifeTime() - { - - $this->_instance->setDirectives(array('logging' => false)); - parent::testSaveWithSpecificLifeTime(); - $this->_instance->setDirectives(array('logging' => true)); - } - -} - +_instance = new Zend_Cache_Backend_ZendServer_Disk(); + parent::setUp(true); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_ZendServer_Disk(); + } + + public function testCleanModeOld() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + +} + diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php index d950cb16e..e06ffe55f 100755 --- a/test/ZendServerShMemTest.php +++ b/test/ZendServerShMemTest.php @@ -1,101 +1,101 @@ -_instance = new Zend_Cache_Backend_ZendServer_ShMem(); - parent::setUp(true); - } - - public function tearDown() - { - parent::tearDown(); - unset($this->_instance); - } - - public function testConstructorCorrectCall() - { - $test = new Zend_Cache_Backend_ZendServer_ShMem(); - } - - public function testCleanModeOld() { - $this->_instance->setDirectives(array('logging' => false)); - $this->_instance->clean('old'); - // do nothing, just to see if an error occured - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testCleanModeMatchingTags() { - $this->_instance->setDirectives(array('logging' => false)); - $this->_instance->clean('matchingTag', array('tag1')); - // do nothing, just to see if an error occured - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testCleanModeNotMatchingTags() { - $this->_instance->setDirectives(array('logging' => false)); - $this->_instance->clean('notMatchingTag', array('tag1')); - // do nothing, just to see if an error occured - $this->_instance->setDirectives(array('logging' => true)); - } - - // Because of limitations of this backend... - public function testGetWithAnExpiredCacheId() {} - public function testCleanModeMatchingTags2() {} - public function testCleanModeNotMatchingTags2() {} - public function testCleanModeNotMatchingTags3() {} - public function testSaveCorrectCall() - { - $this->_instance->setDirectives(array('logging' => false)); - parent::testSaveCorrectCall(); - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testSaveWithNullLifeTime() - { - $this->_instance->setDirectives(array('logging' => false)); - parent::testSaveWithNullLifeTime(); - $this->_instance->setDirectives(array('logging' => true)); - } - - public function testSaveWithSpecificLifeTime() - { - - $this->_instance->setDirectives(array('logging' => false)); - parent::testSaveWithSpecificLifeTime(); - $this->_instance->setDirectives(array('logging' => true)); - } -} - +_instance = new Zend_Cache_Backend_ZendServer_ShMem(); + parent::setUp(true); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_ZendServer_ShMem(); + } + + public function testCleanModeOld() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('old'); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('matchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testCleanModeNotMatchingTags() { + $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->clean('notMatchingTag', array('tag1')); + // do nothing, just to see if an error occured + $this->_instance->setDirectives(array('logging' => true)); + } + + // Because of limitations of this backend... + public function testGetWithAnExpiredCacheId() {} + public function testCleanModeMatchingTags2() {} + public function testCleanModeNotMatchingTags2() {} + public function testCleanModeNotMatchingTags3() {} + public function testSaveCorrectCall() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveCorrectCall(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithNullLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } + + public function testSaveWithSpecificLifeTime() + { + + $this->_instance->setDirectives(array('logging' => false)); + parent::testSaveWithSpecificLifeTime(); + $this->_instance->setDirectives(array('logging' => true)); + } +} + From f7749fbb52c1ca16bacd083f8e4896d1c3b202f2 Mon Sep 17 00:00:00 2001 From: alexander Date: Thu, 13 Aug 2009 18:01:41 +0000 Subject: [PATCH 015/311] Merge cs-17363 back to trunk. [ZF-7581] related. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17573 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/AllTests.php | 2 + test/ApcBackendTest.php | 24 +++++++++++- test/ClassFrontendTest.php | 34 ++++++++++++++++- test/CommonBackendTest.php | 28 ++++++++++++-- test/CommonExtendedBackendTest.php | 28 ++++++++++++-- test/CoreTest.php | 22 ++++++++++- test/FactoryException.php | 28 ++++++++++++++ test/FactoryTest.php | 20 ++++++++++ test/FileBackendTest.php | 20 ++++++++++ test/FileFrontendTest.php | 22 ++++++++++- test/FunctionFrontendTest.php | 22 ++++++++++- test/MemcachedBackendTest.php | 22 ++++++++++- test/OutputFrontendTest.php | 24 +++++++++++- test/PageFrontendTest.php | 22 ++++++++++- test/SkipTests.php | 60 ++++++++++++++++++++++++++++-- test/SqliteBackendTest.php | 20 ++++++++++ test/TwoLevelsBackendTest.php | 20 ++++++++++ test/XcacheBackendTest.php | 22 ++++++++++- test/ZendPlatformBackendTest.php | 22 ++++++++++- 19 files changed, 438 insertions(+), 24 deletions(-) diff --git a/test/AllTests.php b/test/AllTests.php index e1894395b..9b56669c0 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -17,6 +17,7 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id $ */ /** @@ -52,6 +53,7 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @group Zend_Cache */ class Zend_Cache_AllTests { diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php index 902ef80dd..f0d6912dd 100644 --- a/test/ApcBackendTest.php +++ b/test/ApcBackendTest.php @@ -1,10 +1,26 @@ Date: Tue, 18 Aug 2009 22:09:45 +0000 Subject: [PATCH 016/311] ZF-7335: TEST - add missing tag $Id$ git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17668 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/ZendServerDiskTest.php | 16 ++++++++++++++++ test/ZendServerShMemTest.php | 16 ++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index 0906a447f..dcc6f96e1 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -1,7 +1,23 @@ Date: Wed, 19 Aug 2009 13:02:52 +0000 Subject: [PATCH 017/311] [ZF-7358]Zend_Cache_Backend_ZendServer_ShMem and Zend_Cache_Backend_ZendServer_Disk throws an exception in test() git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17671 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/ZendServer.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index 4b82939b3..808fd4238 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -104,7 +104,7 @@ public function load($id, $doNotTestCacheValidity = false) public function test($id) { $tmp = $this->_fetch('internal-metadatas---' . $id); - if ($tmp !== null) { + if ($tmp !== false) { if (!is_array($tmp) || !isset($tmp['mtime'])) { Zend_Cache::throwException('Cache metadata for \'' . $id . '\' id is corrupted' ); } From 61f577a939081d7b04be13697d083beb1a012435 Mon Sep 17 00:00:00 2001 From: alexander Date: Wed, 19 Aug 2009 21:21:34 +0000 Subject: [PATCH 018/311] Merging cs-17363 back to trunk. Manual merge of conflicted files. [ZF-7581] git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17682 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/ZendServerDiskTest.php | 4 ++++ test/ZendServerShMemTest.php | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index dcc6f96e1..dfa434d26 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -37,8 +37,12 @@ require_once 'PHPUnit/Framework/TestCase.php'; /** + * @category Zend * @package Zend_Cache * @subpackage UnitTests + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @license http://framework.zend.com/license/new-bsd New BSD License + * @group Zend_Cache */ class Zend_Cache_ZendServerDiskTest extends Zend_Cache_CommonBackendTest { diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php index 363d81a8d..e74b16dcd 100755 --- a/test/ZendServerShMemTest.php +++ b/test/ZendServerShMemTest.php @@ -37,8 +37,12 @@ require_once 'PHPUnit/Framework/TestCase.php'; /** + * @category Zend * @package Zend_Cache * @subpackage UnitTests + * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @license http://framework.zend.com/license/new-bsd New BSD License + * @group Zend_Cache */ class Zend_Cache_ZendServerShMemTest extends Zend_Cache_CommonBackendTest { From 25557e2b4ba114f49ab3ef1b863480f6c133ded3 Mon Sep 17 00:00:00 2001 From: thomas Date: Thu, 20 Aug 2009 12:55:34 +0000 Subject: [PATCH 019/311] [ZF-7316] Code cleaning: - reverted CRLF (Win*) to LF (*nix) - reverted TABS to 4 spaces - erased ending spaces used revision 17680 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17687 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 60 +++++++++--------- src/Backend/Apc.php | 50 +++++++-------- src/Backend/ExtendedInterface.php | 28 ++++----- src/Backend/Memcached.php | 36 +++++------ src/Backend/Xcache.php | 2 +- src/Core.php | 14 ++--- src/Frontend/File.php | 100 +++++++++++++++--------------- src/Frontend/Function.php | 2 +- src/Frontend/Page.php | 8 +-- 9 files changed, 150 insertions(+), 150 deletions(-) diff --git a/src/Backend.php b/src/Backend.php index cf74e2585..975b1bf11 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -140,77 +140,77 @@ public function isAutomaticCleaningAvailable() { return true; } - + /** * Determine system TMP directory and detect if we have read access * - * inspired from Zend_File_Transfer_Adapter_Abstract + * inspired from Zend_File_Transfer_Adapter_Abstract * * @return string * @throws Zend_Cache_Exception if unable to determine directory */ public function getTmpDir() { - $tmpdir = array(); + $tmpdir = array(); foreach (array($_ENV, $_SERVER) as $tab) { - foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) { - if (isset($tab[$key])) { - if (($key == 'windir') or ($key == 'SystemRoot')) { + foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) { + if (isset($tab[$key])) { + if (($key == 'windir') or ($key == 'SystemRoot')) { $dir = realpath($tab[$key] . '\\temp'); } else { - $dir = realpath($tab[$key]); + $dir = realpath($tab[$key]); + } + if ($this->_isGoodTmpDir($dir)) { + return $dir; } - if ($this->_isGoodTmpDir($dir)) { - return $dir; - } - } - } + } + } } $upload = ini_get('upload_tmp_dir'); if ($upload) { $dir = realpath($upload); - if ($this->_isGoodTmpDir($dir)) { - return $dir; - } + if ($this->_isGoodTmpDir($dir)) { + return $dir; + } } if (function_exists('sys_get_temp_dir')) { $dir = sys_get_temp_dir(); - if ($this->_isGoodTmpDir($dir)) { - return $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)); + $dir = realpath(dirname($tempFile)); unlink($tempFile); if ($this->_isGoodTmpDir($dir)) { return $dir; } } if ($this->_isGoodTmpDir('/tmp')) { - return '/tmp'; + return '/tmp'; } if ($this->_isGoodTmpDir('\\temp')) { - return '\\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 $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; + if (is_readable($dir)) { + if (is_writable($dir)) { + return true; + } + } + return false; } /** @@ -261,7 +261,7 @@ protected function _log($message, $priority = 4) } if (!isset($this->_directives['logger'])) { - Zend_Cache::throwException('Logging is enabled but logger is not set.'); + Zend_Cache::throwException('Logging is enabled but logger is not set.'); } $logger = $this->_directives['logger']; if (!$logger instanceof Zend_Log) { diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php index 01a86bd90..d6c532ca2 100644 --- a/src/Backend/Apc.php +++ b/src/Backend/Apc.php @@ -166,18 +166,18 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) * Return true if the automatic cleaning is available for the backend * * DEPRECATED : use getCapabilities() instead - * - * @deprecated + * + * @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 */ @@ -195,21 +195,21 @@ public function getFillingPercentage() } 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 @@ -218,26 +218,26 @@ public function getTags() public function getIdsMatchingTags($tags = array()) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND); - return 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()) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND); - return 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 @@ -246,12 +246,12 @@ public function getIdsNotMatchingTags($tags = array()) public function getIdsMatchingAnyTags($tags = array()) { $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_APC_BACKEND); - return array(); + return array(); } - + /** * Return an array of stored cache ids - * + * * @return array array of stored cache ids (string) */ public function getIds() @@ -264,7 +264,7 @@ public function getIds() } return $res; } - + /** * Return an array of metadatas for the given cache id * @@ -272,7 +272,7 @@ public function getIds() * - 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) */ @@ -294,9 +294,9 @@ public function getMetadatas($id) 'mtime' => $mtime ); } - return false; + return false; } - + /** * Give (if possible) an extra lifetime to the given cache id * @@ -318,17 +318,17 @@ public function touch($id, $extraLifetime) $lifetime = $tmp[2]; $newLifetime = $lifetime - (time() - $mtime) + $extraLifetime; if ($newLifetime <=0) { - return false; + 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) @@ -337,7 +337,7 @@ public function touch($id, $extraLifetime) * - 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() diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php index cae8f504f..53b2ffff1 100644 --- a/src/Backend/ExtendedInterface.php +++ b/src/Backend/ExtendedInterface.php @@ -36,21 +36,21 @@ interface Zend_Cache_Backend_ExtendedInterface extends Zend_Cache_Backend_Interf /** * 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 @@ -60,24 +60,24 @@ 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 * @@ -92,12 +92,12 @@ public function getFillingPercentage(); * - 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 * @@ -106,10 +106,10 @@ public function getMetadatas($id); * @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) @@ -118,9 +118,9 @@ public function touch($id, $extraLifetime); * - 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(); - + } diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index bc899292a..741f1cd1c 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -155,16 +155,16 @@ public function __construct(array $options = array()) $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'], + // 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'], + } else { + $this->_memcache->addServer($server['host'], $server['port'], $server['persistent'], $server['weight'], $server['timeout'], $server['retry_interval'], $server['status'], $server['failure_callback']); - } + } } } @@ -383,22 +383,22 @@ public function getFillingPercentage() $memSize = 0; $memUsed = 0; foreach ($mems as $key => $mem) { - if ($mem === false) { + if ($mem === false) { Zend_Cache::throwException('can\'t get stat from ' . $key); - } else { - $eachSize = $mem['limit_maxbytes']; - if ($eachSize == 0) { + } else { + $eachSize = $mem['limit_maxbytes']; + if ($eachSize == 0) { Zend_Cache::throwException('can\'t get memory size from ' . $key); - } + } - $eachUsed = $mem['bytes']; - if ($eachUsed > $eachSize) { - $eachUsed = $eachSize; - } + $eachUsed = $mem['bytes']; + if ($eachUsed > $eachSize) { + $eachUsed = $eachSize; + } - $memSize += $eachSize; - $memUsed += $eachUsed; - } + $memSize += $eachSize; + $memUsed += $eachUsed; + } } return ((int) (100. * ($memUsed / $memSize))); @@ -466,7 +466,7 @@ public function touch($id, $extraLifetime) } // #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); + $result = $this->_memcache->set($id, array($data, time(), $newLifetime), $flag, $newLifetime); } return $result; } diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php index 4cdabff17..4d9e1a80b 100644 --- a/src/Backend/Xcache.php +++ b/src/Backend/Xcache.php @@ -46,7 +46,7 @@ class Zend_Cache_Backend_Xcache extends Zend_Cache_Backend implements Zend_Cache */ 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 * diff --git a/src/Core.php b/src/Core.php index 599bd7bd0..40c982195 100644 --- a/src/Core.php +++ b/src/Core.php @@ -483,11 +483,11 @@ public function getIds() // we need to remove cache_id_prefix from ids (see #ZF-6178) $res = array(); while (list(,$id) = each($array)) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { - $res[] = preg_replace("~^{$this->_options['cache_id_prefix']}~", '', $id); - } else { - $res[] = $id; - } + if (strpos($id, $this->_options['cache_id_prefix']) === 0) { + $res[] = preg_replace("~^{$this->_options['cache_id_prefix']}~", '', $id); + } else { + $res[] = $id; + } } return $res; } @@ -520,7 +520,7 @@ public function getFillingPercentage() } return $this->_backend->getFillingPercentage(); } - + /** * Return an array of metadatas for the given cache id * @@ -534,7 +534,7 @@ public function getFillingPercentage() */ public function getMetadatas($id) { - if (!$this->_extendedBackend) { + if (!$this->_extendedBackend) { Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); } $id = $this->_id($id); // cache id may need prefix diff --git a/src/Frontend/File.php b/src/Frontend/File.php index 84fa84dd6..38cb7e8b3 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -35,46 +35,46 @@ */ class Zend_Cache_Frontend_File extends Zend_Cache_Core { - - /** - * Consts for master_files_mode - */ - const MODE_AND = 'AND'; - const MODE_OR = 'OR'; - + + /** + * 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 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_file' => null, 'master_files' => null, - 'master_files_mode' => 'OR', - 'ignore_missing_master_files' => false + 'master_files_mode' => 'OR', + 'ignore_missing_master_files' => false ); /** * Master file mtimes * * Array of int - * + * * @var array */ private $_masterFile_mtimes = null; @@ -95,10 +95,10 @@ public function __construct(array $options = array()) Zend_Cache::throwException('master_files option must be set'); } } - + /** * Change the master_file option - * + * * @param string $masterFile the complete path and name of the master file */ public function setMasterFiles($masterFiles) @@ -109,27 +109,27 @@ public function setMasterFiles($masterFiles) $this->_masterFile_mtimes = array(); $i = 0; foreach ($masterFiles as $masterFile) { - $this->_masterFile_mtimes[$i] = @filemtime($masterFile); - if ((!($this->_specificOptions['ignore_missing_master_files'])) && (!($this->_masterFile_mtimes[$i]))) { - Zend_Cache::throwException('Unable to read master_file : '.$masterFile); - } - $i++; + $this->_masterFile_mtimes[$i] = @filemtime($masterFile); + if ((!($this->_specificOptions['ignore_missing_master_files'])) && (!($this->_masterFile_mtimes[$i]))) { + Zend_Cache::throwException('Unable to read master_file : '.$masterFile); + } + $i++; } } - + /** * Change the master_file option - * - * To keep the compatibility - * + * + * To keep the compatibility + * * @deprecated * @param string $masterFile the complete path and name of the master file - */ + */ public function setMasterFile($masterFile) { - $this->setMasterFiles(array(0 => $masterFile)); + $this->setMasterFiles(array(0 => $masterFile)); } - + /** * Public frontend to set an option * @@ -145,7 +145,7 @@ public function setOption($name, $value) if ($name == 'master_file') { $this->setMasterFile($value); } else if ($name == 'master_files') { - $this->setMasterFiles($value); + $this->setMasterFiles($value); } else { parent::setOption($name, $value); } @@ -180,27 +180,27 @@ 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; - } + 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; } diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index 36a8d93e8..043be1df2 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -76,7 +76,7 @@ public function __construct(array $options = array()) * @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 + * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends * @return mixed Result */ public function call($name, $parameters = array(), $tags = array(), $specificLifetime = false, $priority = 8) diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index da68855ed..5f361af52 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -275,7 +275,7 @@ public function start($id = false, $doNotDie = false) header("$name: $value"); } } - if ($this->_specificOptions['debug_header']) { + if ($this->_specificOptions['debug_header']) { echo 'DEBUG HEADER : This is a cached page !'; } echo $data; @@ -339,9 +339,9 @@ protected function _makeId() { $tmp = $_SERVER['REQUEST_URI']; $array = explode('?', $tmp, 2); - $tmp = $array[0]; + $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']); + $tmp2 = $this->_makePartialId($arrayName, $this->_activeOptions['cache_with_' . strtolower($arrayName) . '_variables'], $this->_activeOptions['make_id_with_' . strtolower($arrayName) . '_variables']); if ($tmp2===false) { return false; } @@ -360,7 +360,7 @@ protected function _makeId() */ protected function _makePartialId($arrayName, $bool1, $bool2) { - switch ($arrayName) { + switch ($arrayName) { case 'Get': $var = $_GET; break; From 8212f2b92ae68806d7df9a14c494a6780a5dd9d6 Mon Sep 17 00:00:00 2001 From: "yoshida@zend.co.jp" Date: Sat, 22 Aug 2009 02:53:32 +0000 Subject: [PATCH 020/311] [ZF-5740]Partial cleaning in Zend_Cache_Backend_TwoLevels::clean() git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17740 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/TwoLevels.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 9fea2b97a..f21ef05e8 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -228,8 +228,9 @@ public function load($id, $doNotTestCacheValidity = false) */ public function remove($id) { - $this->_fastBackend->remove($id); - return $this->_slowBackend->remove($id); + $boolFast = $this->_fastBackend->remove($id); + $boolSlow = $this->_slowBackend->remove($id); + return $boolFast && $boolSlow; } /** @@ -264,7 +265,8 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $ids = $this->_slowBackend->getIdsMatchingTags($tags); $res = true; foreach ($ids as $id) { - $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id); + $bool = $this->remove($id); + $res = $res && $bool; } return $res; break; @@ -272,7 +274,8 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $ids = $this->_slowBackend->getIdsNotMatchingTags($tags); $res = true; foreach ($ids as $id) { - $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id); + $bool = $this->remove($id); + $res = $res && $bool; } return $res; break; @@ -280,7 +283,8 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags); $res = true; foreach ($ids as $id) { - $res = $res && $this->_slowBackend->remove($id) && $this->_fastBackend->remove($id); + $bool = $this->remove($id); + $res = $res && $bool; } return $res; break; From db09873c19e05371a75479b6e60df76665fd7734 Mon Sep 17 00:00:00 2001 From: "yoshida@zend.co.jp" Date: Fri, 28 Aug 2009 09:42:11 +0000 Subject: [PATCH 021/311] [ZF-7691]Zend_Cache clean() does not work git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@17867 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 14 ++++++++------ src/Backend/Sqlite.php | 8 ++++---- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index f0f3bed11..cfd5007cf 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -259,7 +259,9 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) public function remove($id) { $file = $this->_file($id); - return ($this->_delMetadatas($id) && $this->_remove($file)); + $boolRemove = $this->_remove($file); + $boolMetadata = $this->_delMetadatas($id); + return $boolMetadata && $boolRemove; } /** @@ -672,7 +674,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a break; case Zend_Cache::CLEANING_MODE_OLD: if (time() > $metadatas['expire']) { - $result = ($result) && ($this->remove($id)); + $result = $this->remove($id) && $result; } break; case Zend_Cache::CLEANING_MODE_MATCHING_TAG: @@ -684,7 +686,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a } } if ($matching) { - $result = ($result) && ($this->remove($id)); + $result = $this->remove($id) && $result; } break; case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: @@ -696,7 +698,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a } } if (!$matching) { - $result = ($result) && $this->remove($id); + $result = $this->remove($id) && $result; } break; case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: @@ -708,7 +710,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a } } if ($matching) { - $result = ($result) && ($this->remove($id)); + $result = $this->remove($id) && $result; } break; default: @@ -718,7 +720,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a } if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) { // Recursive call - $result = ($result) && ($this->_clean($file . DIRECTORY_SEPARATOR, $mode, $tags)); + $result = $this->_clean($file . DIRECTORY_SEPARATOR, $mode, $tags) && $result; if ($mode=='all') { // if mode=='all', we try to drop the structure too @rmdir($file); diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index d17204094..286fbfc95 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -176,7 +176,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } $res = true; foreach ($tags as $tag) { - $res = $res && $this->_registerTag($id, $tag); + $res = $this->_registerTag($id, $tag) && $res; } return $res; } @@ -630,7 +630,7 @@ private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $ids = $this->getIdsMatchingTags($tags); $result = true; foreach ($ids as $id) { - $result = $result && ($this->remove($id)); + $result = $this->remove($id) && $result; } return $result; break; @@ -638,7 +638,7 @@ private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $ids = $this->getIdsNotMatchingTags($tags); $result = true; foreach ($ids as $id) { - $result = $result && ($this->remove($id)); + $result = $this->remove($id) && $result; } return $result; break; @@ -646,7 +646,7 @@ private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $ids = $this->getIdsMatchingAnyTags($tags); $result = true; foreach ($ids as $id) { - $result = $result && ($this->remove($id)); + $result = $this->remove($id) && $result; } return $result; break; From 2478e4a0d347b714219e912cb43cb77ffb112135 Mon Sep 17 00:00:00 2001 From: padraic Date: Fri, 18 Sep 2009 17:23:14 +0000 Subject: [PATCH 022/311] Added Zend_Config support to Zend_Cache_Core - fixes ZF-7568 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@18254 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 26 ++++++++++++++++++++++++-- test/CoreTest.php | 29 +++++++++++++++++++++++++---- 2 files changed, 49 insertions(+), 6 deletions(-) diff --git a/src/Core.php b/src/Core.php index 40c982195..a3583ba5c 100644 --- a/src/Core.php +++ b/src/Core.php @@ -124,18 +124,40 @@ class Zend_Cache_Core /** * Constructor * - * @param array $options Associative array of options + * @param array|Zend_Config $options Associative array of options or Zend_Config instance * @throws Zend_Cache_Exception * @return void */ - public function __construct(array $options = array()) + 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."); + } while (list($name, $value) = each($options)) { $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(); + while (list($name, $value) = each($options)) { + $this->setOption($name, $value); + } + return $this; + } + /** * Set the backend * diff --git a/test/CoreTest.php b/test/CoreTest.php index 7f42b2496..f333affd2 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -33,6 +33,8 @@ */ require_once 'PHPUnit/Framework/TestCase.php'; +require_once 'Zend/Config.php'; + /** * @category Zend * @package Zend_Cache @@ -41,7 +43,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_CoreTest extends PHPUnit_Framework_TestCase +class Zend_Cache_CoreTest extends PHPUnit_Framework_TestCase { private $_instance; @@ -64,6 +66,27 @@ public function testConstructorCorrectCall() $test = new Zend_Cache_Core(array('lifetime' => 3600, 'caching' => true)); } + /** + * @issue ZF-7568 + */ + public function testConstructorCorrectCallWithZendConfig() + { + $test = new Zend_Cache_Core( + new Zend_Config(array('lifetime' => 3600, 'caching' => true)) + ); + } + + /** + * @issue ZF-7568 + */ + public function testSettingOptionsWithZendConfig() + { + $config = new Zend_Config(array('lifetime' => 3600, 'caching' => true)); + $test = new Zend_Cache_Core(); + $test->setConfig($config); + $this->assertEquals(3600, $test->getOption('lifetime')); + } + public function testConstructorBadOption() { try { @@ -110,7 +133,7 @@ public function testSetOptionBadCall() } /** - * Unknown options are okay and should be silently ignored. Non-string + * Unknown options are okay and should be silently ignored. Non-string * options, however, should throw exceptions. * * @group ZF-5034 @@ -457,5 +480,3 @@ public function testCleanCorrectCall() } } - - From 011b510e3b39555efc1763885f188e434ef36310 Mon Sep 17 00:00:00 2001 From: alexander Date: Thu, 12 Nov 2009 15:37:56 +0000 Subject: [PATCH 023/311] Remove trailing whitespaces, change tab for spaces, convert CRLF to LF. ZF-7316 related. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@18950 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/ApcBackendTest.php | 36 ++++++------ test/ClassFrontendTest.php | 64 +++++++++++----------- test/CommonBackendTest.php | 2 +- test/CommonExtendedBackendTest.php | 36 ++++++------ test/FactoryException.php | 12 ++-- test/FactoryTest.php | 18 +++--- test/FileBackendTest.php | 40 +++++++------- test/FileFrontendTest.php | 88 +++++++++++++++--------------- test/FunctionFrontendTest.php | 38 ++++++------- test/MemcachedBackendTest.php | 50 ++++++++--------- test/OutputFrontendTest.php | 14 ++--- test/PageFrontendTest.php | 78 +++++++++++++------------- test/SqliteBackendTest.php | 36 ++++++------ test/TwoLevelsBackendTest.php | 18 +++--- test/ZendPlatformBackendTest.php | 20 +++---- 15 files changed, 275 insertions(+), 275 deletions(-) diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php index f0d6912dd..2aa8ea284 100644 --- a/test/ApcBackendTest.php +++ b/test/ApcBackendTest.php @@ -45,52 +45,52 @@ * @group Zend_Cache */ class Zend_Cache_ApcBackendTest extends Zend_Cache_CommonExtendedBackendTest { - + protected $_instance; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct('Zend_Cache_Backend_Apc', $data, $dataName); } - + public function setUp($notag = true) - { + { $this->_instance = new Zend_Cache_Backend_Apc(array()); - parent::setUp($notag); + parent::setUp($notag); } - + public function tearDown() { parent::tearDown(); unset($this->_instance); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Apc(); + $test = new Zend_Cache_Backend_Apc(); } - + public function testCleanModeOld() { $this->_instance->setDirectives(array('logging' => false)); $this->_instance->clean('old'); // do nothing, just to see if an error occured $this->_instance->setDirectives(array('logging' => true)); } - + public function testCleanModeMatchingTags() { $this->_instance->setDirectives(array('logging' => false)); $this->_instance->clean('matchingTag', array('tag1')); // do nothing, just to see if an error occured $this->_instance->setDirectives(array('logging' => true)); } - + public function testCleanModeNotMatchingTags() { $this->_instance->setDirectives(array('logging' => false)); $this->_instance->clean('notMatchingTag', array('tag1')); // do nothing, just to see if an error occured $this->_instance->setDirectives(array('logging' => true)); } - + // Because of limitations of this backend... public function testGetWithAnExpiredCacheId() {} public function testCleanModeMatchingTags2() {} @@ -111,27 +111,27 @@ public function testSaveCorrectCall() parent::testSaveCorrectCall(); $this->_instance->setDirectives(array('logging' => true)); } - + public function testSaveWithNullLifeTime() { $this->_instance->setDirectives(array('logging' => false)); parent::testSaveWithNullLifeTime(); $this->_instance->setDirectives(array('logging' => true)); } - - public function testSaveWithSpecificLifeTime() + + public function testSaveWithSpecificLifeTime() { - + $this->_instance->setDirectives(array('logging' => false)); parent::testSaveWithSpecificLifeTime(); $this->_instance->setDirectives(array('logging' => true)); } - + public function testGetMetadatas($notag = true) { parent::testGetMetadatas($notag); } - + } diff --git a/test/ClassFrontendTest.php b/test/ClassFrontendTest.php index 75e1a59c6..b7e9b3576 100644 --- a/test/ClassFrontendTest.php +++ b/test/ClassFrontendTest.php @@ -45,16 +45,16 @@ class test { private $_string = 'hello !'; - + public static function foobar($param1, $param2) { echo "foobar_output($param1, $param2)"; - return "foobar_return($param1, $param2)"; + return "foobar_return($param1, $param2)"; } - + public function foobar2($param1, $param2) { echo($this->_string); echo "foobar2_output($param1, $param2)"; - return "foobar2_return($param1, $param2)"; + return "foobar2_return($param1, $param2)"; } } @@ -68,10 +68,10 @@ public function foobar2($param1, $param2) { * @group Zend_Cache */ class Zend_Cache_ClassFrontendTest extends PHPUnit_Framework_TestCase { - + private $_instance1; private $_instance2; - + public function setUp() { if (!$this->_instance1) { @@ -89,33 +89,33 @@ public function setUp() $this->_instance2 = new Zend_Cache_Frontend_Class($options2); $this->_backend2 = new Zend_Cache_Backend_Test(); $this->_instance2->setBackend($this->_backend2); - } + } } - + public function tearDown() { unset($this->_instance1); unset($this->_instance2); } - + public function testConstructorCorrectCall1() { $options = array( 'cache_by_default' => false, 'cached_entity' => 'test' ); - $test = new Zend_Cache_Frontend_Class($options); + $test = new Zend_Cache_Frontend_Class($options); } - + public function testConstructorCorrectCall2() { $options = array( 'cache_by_default' => false, 'cached_entity' => new test() ); - $test = new Zend_Cache_Frontend_Class($options); + $test = new Zend_Cache_Frontend_Class($options); } - + public function testConstructorBadCall() { $options = array( @@ -123,17 +123,17 @@ public function testConstructorBadCall() 0 => true, ); try { - $test = new Zend_Cache_Frontend_Class($options); + $test = new Zend_Cache_Frontend_Class($options); } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testCallCorrectCall1() { ob_start(); - ob_implicit_flush(false); + ob_implicit_flush(false); $return = $this->_instance1->foobar('param1', 'param2'); $data = ob_get_contents(); ob_end_clean(); @@ -141,11 +141,11 @@ public function testCallCorrectCall1() $this->assertEquals('bar', $return); $this->assertEquals('foo', $data); } - + public function testCallCorrectCall2() { ob_start(); - ob_implicit_flush(false); + ob_implicit_flush(false); $return = $this->_instance1->foobar('param3', 'param4'); $data = ob_get_contents(); ob_end_clean(); @@ -153,11 +153,11 @@ public function testCallCorrectCall2() $this->assertEquals('foobar_return(param3, param4)', $return); $this->assertEquals('foobar_output(param3, param4)', $data); } - + public function testCallCorrectCall3() { ob_start(); - ob_implicit_flush(false); + ob_implicit_flush(false); $return = $this->_instance2->foobar2('param1', 'param2'); $data = ob_get_contents(); ob_end_clean(); @@ -165,11 +165,11 @@ public function testCallCorrectCall3() $this->assertEquals('bar', $return); $this->assertEquals('foo', $data); } - + public function testCallCorrectCall4() { ob_start(); - ob_implicit_flush(false); + ob_implicit_flush(false); $return = $this->_instance2->foobar2('param3', 'param4'); $data = ob_get_contents(); ob_end_clean(); @@ -177,7 +177,7 @@ public function testCallCorrectCall4() $this->assertEquals('foobar2_return(param3, param4)', $return); $this->assertEquals('hello !foobar2_output(param3, param4)', $data); } - + public function testCallCorrectCall5() { // cacheByDefault = false @@ -191,7 +191,7 @@ public function testCallCorrectCall5() $this->assertEquals('foobar_return(param1, param2)', $return); $this->assertEquals('foobar_output(param1, param2)', $data); } - + public function testCallCorrectCall6() { // cacheByDefault = false @@ -206,8 +206,8 @@ public function testCallCorrectCall6() ob_implicit_flush(true); $this->assertEquals('bar', $return); $this->assertEquals('foo', $data); - } - + } + public function testCallCorrectCall7() { // cacheByDefault = true @@ -223,19 +223,19 @@ public function testCallCorrectCall7() $this->assertEquals('foobar_return(param1, param2)', $return); $this->assertEquals('foobar_output(param1, param2)', $data); } - + public function testConstructorWithABadCachedEntity() { try { $options = array( 'cached_entity' => array() ); - $instance = new Zend_Cache_Frontend_Class($options); + $instance = new Zend_Cache_Frontend_Class($options); } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); - } + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } /** * @group ZF-5034 @@ -246,7 +246,7 @@ public function testCallingConstructorWithInvalidOptionShouldNotRaiseException() 'cached_entity' => new test(), 'this_key_does_not_exist' => true ); - $test = new Zend_Cache_Frontend_Class($options); + $test = new Zend_Cache_Frontend_Class($options); } } diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php index 50bd7dba8..b144ac16a 100644 --- a/test/CommonBackendTest.php +++ b/test/CommonBackendTest.php @@ -181,7 +181,7 @@ public function testRemoveCorrectCall() public function testTestWithAnExistingCacheId() { - $res = $this->_instance->test('bar'); + $res = $this->_instance->test('bar'); if (!$res) { $this->fail('test() return false'); } diff --git a/test/CommonExtendedBackendTest.php b/test/CommonExtendedBackendTest.php index e200d5c06..542ec04fa 100644 --- a/test/CommonExtendedBackendTest.php +++ b/test/CommonExtendedBackendTest.php @@ -45,12 +45,12 @@ class Zend_Cache_CommonExtendedBackendTest extends Zend_Cache_CommonBackendTest { private $_capabilities; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct($name); } - + public function setUp($notag = false) { parent::setUp($notag); @@ -64,7 +64,7 @@ public function testGetFillingPercentage() $this->assertTrue($res >= 0); $this->assertTrue($res <= 100); } - + public function testGetIds() { if (!($this->_capabilities['get_list'])) { @@ -77,7 +77,7 @@ public function testGetIds() $this->assertTrue(in_array('bar2', $res)); $this->assertTrue(in_array('bar3', $res)); } - + public function testGetTags() { if (!($this->_capabilities['tags'])) { @@ -91,7 +91,7 @@ public function testGetTags() $this->assertTrue(in_array('tag3', $res)); $this->assertTrue(in_array('tag4', $res)); } - + public function testGetIdsMatchingTags() { if (!($this->_capabilities['tags'])) { @@ -104,7 +104,7 @@ public function testGetIdsMatchingTags() $this->assertTrue(in_array('bar2', $res)); $this->assertTrue(in_array('bar3', $res)); } - + public function testGetIdsMatchingTags2() { if (!($this->_capabilities['tags'])) { @@ -115,7 +115,7 @@ public function testGetIdsMatchingTags2() $this->assertTrue(count($res) == 1); $this->assertTrue(in_array('bar3', $res)); } - + public function testGetIdsMatchingTags3() { if (!($this->_capabilities['tags'])) { @@ -124,9 +124,9 @@ public function testGetIdsMatchingTags3() } $res = $this->_instance->getIdsMatchingTags(array('tag9999')); $this->assertTrue(count($res) == 0); - } - - + } + + public function testGetIdsMatchingTags4() { if (!($this->_capabilities['tags'])) { @@ -136,8 +136,8 @@ public function testGetIdsMatchingTags4() $res = $this->_instance->getIdsMatchingTags(array('tag3', 'tag4')); $this->assertTrue(count($res) == 1); $this->assertTrue(in_array('bar', $res)); - } - + } + public function testGetIdsNotMatchingTags() { if (!($this->_capabilities['tags'])) { @@ -147,7 +147,7 @@ public function testGetIdsNotMatchingTags() $res = $this->_instance->getIdsNotMatchingTags(array('tag3')); $this->assertTrue(count($res) == 0); } - + public function testGetIdsNotMatchingTags2() { if (!($this->_capabilities['tags'])) { @@ -159,7 +159,7 @@ public function testGetIdsNotMatchingTags2() $this->assertTrue(in_array('bar', $res)); $this->assertTrue(in_array('bar3', $res)); } - + public function testGetIdsNotMatchingTags3() { if (!($this->_capabilities['tags'])) { @@ -170,7 +170,7 @@ public function testGetIdsNotMatchingTags3() $this->assertTrue(count($res) == 1); $this->assertTrue(in_array('bar3', $res)); } - + public function testGetMetadatas($notag = false) { $res = $this->_instance->getMetadatas('bar'); @@ -187,7 +187,7 @@ public function testGetMetadatas($notag = false) $this->assertTrue($res['expire'] > time()); $this->assertTrue($res['mtime'] <= time()); } - + public function testTouch() { $res = $this->_instance->getMetadatas('bar'); @@ -197,7 +197,7 @@ public function testTouch() $this->assertTrue(($res2['expire'] - $res['expire']) == 30); $this->assertTrue(($res2['mtime'] >= $res['mtime'])); } - + public function testGetCapabilities() { $res = $this->_instance->getCapabilities(); @@ -208,7 +208,7 @@ public function testGetCapabilities() $this->assertTrue(isset($res['infinite_lifetime'])); $this->assertTrue(isset($res['get_list'])); } - + } diff --git a/test/FactoryException.php b/test/FactoryException.php index 407e8fd41..b208d11d2 100644 --- a/test/FactoryException.php +++ b/test/FactoryException.php @@ -22,7 +22,7 @@ require_once 'PHPUnit/Extensions/ExceptionTestCase.php'; require_once 'Zend/Cache.php'; - + /** * @category Zend * @package Zend_Cache @@ -35,27 +35,27 @@ class Zend_Cache_FactoryException extends PHPUnit_Extensions_ExceptionTestCase function setUp(){ $this->setExpectedException('Zend_Cache_Exception'); } - + public function testBadFrontend() { Zend_Cache::factory('badFrontend', 'File'); } - + public function testBadBackend() { Zend_Cache::factory('Output', 'badBackend'); } - + public function testFrontendBadParam() { Zend_Cache::factory('badFrontend', 'File', array('badParam'=>true)); } - + public function testBackendBadParam() { Zend_Cache::factory('Output', 'badBackend', array(), array('badParam'=>true)); } - + public function testThrowMethod() { Zend_Cache::throwException('test'); diff --git a/test/FactoryTest.php b/test/FactoryTest.php index 6d0f1750f..1855c1692 100644 --- a/test/FactoryTest.php +++ b/test/FactoryTest.php @@ -53,35 +53,35 @@ class Zend_Cache_FactoryTest extends PHPUnit_Framework_TestCase public function setUp() { } - + public function tearDown() { } - + public function testFactoryCorrectCall() { $generated_frontend = Zend_Cache::factory('Core', 'File'); $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); } - + public function testFactoryCorrectCallWithCustomBackend() { $generated_frontend = Zend_Cache::factory('Core', 'FooBarTest', array(), array(), false, false, true); $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); } - + public function testFactoryCorrectCallWithCustomBackend2() { $generated_frontend = Zend_Cache::factory('Core', 'FooBarTestBackend', array(), array(), false, true, true); $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); } - + public function testFactoryCorrectCallWithCustomFrontend() { $generated_frontend = Zend_Cache::factory('FooBarTest', 'File', array(), array(), false, false, true); $this->assertEquals('Zend_Cache_Frontend_FooBarTest', get_class($generated_frontend)); } - + public function testFactoryCorrectCallWithCustomFrontend2() { $generated_frontend = Zend_Cache::factory('FooBarTestFrontend', 'File', array(), array(), true, false, true); @@ -98,7 +98,7 @@ public function testFactoryLoadsPlatformBackend() } } } - + public function testBadFrontend() { try { @@ -108,7 +108,7 @@ public function testBadFrontend() } $this->fail('Zend_Exception was expected but not thrown'); } - + public function testBadBackend() { try { @@ -116,7 +116,7 @@ public function testBadBackend() } catch (Zend_Exception $e) { return; } - $this->fail('Zend_Exception was expected but not thrown'); + $this->fail('Zend_Exception was expected but not thrown'); } } diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php index 03e8fbf1e..6c2668203 100644 --- a/test/FileBackendTest.php +++ b/test/FileBackendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -51,41 +51,41 @@ * @group Zend_Cache */ class Zend_Cache_FileBackendTest extends Zend_Cache_CommonExtendedBackendTest { - + protected $_instance; protected $_instance2; protected $_cache_dir; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct('Zend_Cache_Backend_File', $data, $dataName); } - + public function setUp($notag = false) - { + { $this->mkdir(); $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; $this->_instance = new Zend_Cache_Backend_File(array( 'cache_dir' => $this->_cache_dir, - )); + )); $logger = new Zend_Log(new Zend_Log_Writer_Null()); $this->_instance->setDirectives(array('logger' => $logger)); - parent::setUp($notag); + parent::setUp($notag); } - + public function tearDown() { parent::tearDown(); unset($this->_instance); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_File(array()); - } - + $test = new Zend_Cache_Backend_File(array()); + } + public function testConstructorWithABadFileNamePrefix() { try { @@ -95,22 +95,22 @@ public function testConstructorWithABadFileNamePrefix() } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - - public function testGetWithANonExistingCacheIdAndANullLifeTime() + + public function testGetWithANonExistingCacheIdAndANullLifeTime() { $this->_instance->setDirectives(array('lifetime' => null)); - $this->assertFalse($this->_instance->load('barbar')); + $this->assertFalse($this->_instance->load('barbar')); } - + public function testSaveCorrectCallWithHashedDirectoryStructure() { $this->_instance->setOption('hashed_directory_level', 2); $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2')); $this->assertTrue($res); } - + public function testCleanModeAllWithHashedDirectoryStructure() { $this->_instance->setOption('hashed_directory_level', 2); @@ -118,14 +118,14 @@ public function testCleanModeAllWithHashedDirectoryStructure() $this->assertFalse($this->_instance->test('bar')); $this->assertFalse($this->_instance->test('bar2')); } - + public function testSaveWithABadCacheDir() { $this->_instance->setOption('cache_dir', '/foo/bar/lfjlqsdjfklsqd/'); $res = $this->_instance->save('data to cache', 'foo', array('tag1', 'tag2')); $this->assertFalse($res); } - + } diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php index 2d6f6a5fa..0f040e2b6 100644 --- a/test/FileFrontendTest.php +++ b/test/FileFrontendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -41,7 +41,7 @@ * @group Zend_Cache */ class Zend_Cache_FileFrontendTest extends PHPUnit_Framework_TestCase { - + private $_instance1; private $_instance2; private $_instance3; @@ -49,8 +49,8 @@ class Zend_Cache_FileFrontendTest extends PHPUnit_Framework_TestCase { private $_masterFile; private $_masterFile1; private $_masterFile2; - - + + public function setUp() { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { @@ -59,37 +59,37 @@ public function setUp() $this->_masterFile2 = $this->_getTmpDirWindows() . DIRECTORY_SEPARATOR . 'zend_cache_master2'; } else { $this->_masterFile = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master'; - $this->_masterFile1 = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master1'; - $this->_masterFile2 = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master2'; + $this->_masterFile1 = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master1'; + $this->_masterFile2 = $this->_getTmpDirUnix() . DIRECTORY_SEPARATOR . 'zend_cache_master2'; } if (!$this->_instance1) { touch($this->_masterFile, 123455); - $this->_instance1 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); + $this->_instance1 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); $this->_backend = new Zend_Cache_Backend_Test(); $this->_instance1->setBackend($this->_backend); } if (!$this->_instance2) { touch($this->_masterFile); - $this->_instance2 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); + $this->_instance2 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); $this->_backend = new Zend_Cache_Backend_Test(); $this->_instance2->setBackend($this->_backend); } if (!$this->_instance3) { - touch($this->_masterFile1, 123455); - touch($this->_masterFile2, 123455); - $this->_instance3 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); + touch($this->_masterFile1, 123455); + touch($this->_masterFile2, 123455); + $this->_instance3 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); $this->_backend = new Zend_Cache_Backend_Test(); $this->_instance3->setBackend($this->_backend); } if (!$this->_instance4) { touch($this->_masterFile1); touch($this->_masterFile2); - $this->_instance4 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); + $this->_instance4 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); $this->_backend = new Zend_Cache_Backend_Test(); $this->_instance4->setBackend($this->_backend); - } + } } - + public function tearDown() { unset($this->_instance1); @@ -97,7 +97,7 @@ public function tearDown() unlink($this->_masterFile1); unlink($this->_masterFile2); } - + private function _getTmpDirWindows() { if (isset($_ENV['TEMP'])) { @@ -126,7 +126,7 @@ private function _getTmpDirWindows() } return '\temp'; } - + private function _getTmpDirUnix() { if (isset($_ENV['TMPDIR'])) { @@ -137,74 +137,74 @@ private function _getTmpDirUnix() } return '/tmp'; } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 'lifetime' => 3600, 'caching' => true)); + $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 'lifetime' => 3600, 'caching' => true)); } - + public function testConstructorBadCall1() { # no masterfile try { - $test = new Zend_Cache_Frontend_File(array('lifetime' => 3600, 'caching' => true)); + $test = new Zend_Cache_Frontend_File(array('lifetime' => 3600, 'caching' => true)); } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testConstructorBadCall2() { # incorrect option try { - $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 0 => 3600)); + $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 0 => 3600)); } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testTestCorrectCall1() { $this->assertFalse($this->_instance1->test('false')); } - + public function testTestCorrectCall2() { $this->assertTrue($this->_instance1->test('cache_id') > 1); } - + public function testTestCorrectCall3() { $this->assertFalse($this->_instance2->test('cache_id')); } - + public function testGetCorrectCall1() { - $this->assertFalse($this->_instance1->load('false')); + $this->assertFalse($this->_instance1->load('false')); } - + public function testGetCorrectCall2() { - $this->assertEquals('foo', $this->_instance1->load('cache_id')); + $this->assertEquals('foo', $this->_instance1->load('cache_id')); } - - public function testTestCorrectCall4() + + public function testTestCorrectCall4() { $this->assertFalse($this->_instance4->test('cache_id')); } - + public function testTestCorrectCall5() { - $this->assertFalse($this->_instance3->load('false')); + $this->assertFalse($this->_instance3->load('false')); } - + public function testGetCorrectCall3() { - $this->assertFalse($this->_instance2->load('cache_id')); - } - + $this->assertFalse($this->_instance2->load('cache_id')); + } + public function testConstructorWithABadMasterFile() { try { @@ -212,14 +212,14 @@ public function testConstructorWithABadMasterFile() } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); - } - + $this->fail('Zend_Cache_Exception was expected but not thrown'); + } + public function testGetWithDoNotTestCacheValidity() { - $this->assertEquals('foo', $this->_instance1->load('cache_id', true)); + $this->assertEquals('foo', $this->_instance1->load('cache_id', true)); } - + } diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index c7c1f3755..c6368d83d 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -46,9 +46,9 @@ function foobar($param1, $param2) { * @group Zend_Cache */ class Zend_Cache_FunctionFrontendTest extends PHPUnit_Framework_TestCase { - + private $_instance; - + public function setUp() { if (!$this->_instance) { @@ -57,21 +57,21 @@ public function setUp() $this->_instance->setBackend($this->_backend); } } - + public function tearDown() { unset($this->_instance); } - + public function testConstructorCorrectCall() { $options = array( 'cache_by_default' => false, 'cached_functions' => array('foo', 'bar') ); - $test = new Zend_Cache_Frontend_Function($options); + $test = new Zend_Cache_Frontend_Function($options); } - + public function testConstructorBadCall() { $options = array( @@ -79,13 +79,13 @@ public function testConstructorBadCall() 0 => array('foo', 'bar') ); try { - $test = new Zend_Cache_Frontend_Function($options); + $test = new Zend_Cache_Frontend_Function($options); } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testCallCorrectCall1() { ob_start(); @@ -97,7 +97,7 @@ public function testCallCorrectCall1() $this->assertEquals('bar', $return); $this->assertEquals('foo', $data); } - + public function testCallCorrectCall2() { ob_start(); @@ -109,7 +109,7 @@ public function testCallCorrectCall2() $this->assertEquals('foobar_return(param3, param4)', $return); $this->assertEquals('foobar_output(param3, param4)', $data); } - + public function testCallCorrectCall3() { // cacheByDefault = false @@ -123,7 +123,7 @@ public function testCallCorrectCall3() $this->assertEquals('foobar_return(param1, param2)', $return); $this->assertEquals('foobar_output(param1, param2)', $data); } - + public function testCallCorrectCall4() { // cacheByDefault = false @@ -138,8 +138,8 @@ public function testCallCorrectCall4() ob_implicit_flush(true); $this->assertEquals('bar', $return); $this->assertEquals('foo', $data); - } - + } + public function testCallCorrectCall5() { // cacheByDefault = true @@ -155,7 +155,7 @@ public function testCallCorrectCall5() $this->assertEquals('foobar_return(param1, param2)', $return); $this->assertEquals('foobar_output(param1, param2)', $data); } - + public function testCallWithABadSyntax1() { try { @@ -163,9 +163,9 @@ public function testCallWithABadSyntax1() } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testCallWithABadSyntax2() { try { @@ -173,7 +173,7 @@ public function testCallWithABadSyntax2() } catch (Zend_Cache_Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } } diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 3fd653b77..2a4444a7d 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -45,16 +45,16 @@ * @group Zend_Cache */ class Zend_Cache_MemcachedBackendTest extends Zend_Cache_CommonExtendedBackendTest { - + protected $_instance; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct('Zend_Cache_Backend_Memcached', $data, $dataName); } - + public function setUp($notag = true) - { + { $server = array( 'host' => TESTS_ZEND_CACHE_MEMCACHED_HOST, 'port' => TESTS_ZEND_CACHE_MEMCACHED_PORT, @@ -64,9 +64,9 @@ public function setUp($notag = true) 'servers' => array(0 => $server) ); $this->_instance = new Zend_Cache_Backend_Memcached($options); - parent::setUp($notag); + parent::setUp($notag); } - + public function tearDown() { parent::tearDown(); @@ -74,42 +74,42 @@ public function tearDown() // We have to wait after a memcache flush sleep(1); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Memcached(); + $test = new Zend_Cache_Backend_Memcached(); } - - public function testCleanModeOld() + + public function testCleanModeOld() { $this->_instance->setDirectives(array('logging' => false)); $this->_instance->clean('old'); // do nothing, just to see if an error occured $this->_instance->setDirectives(array('logging' => true)); } - - public function testCleanModeMatchingTags() + + public function testCleanModeMatchingTags() { $this->_instance->setDirectives(array('logging' => false)); $this->_instance->clean('matchingTag', array('tag1')); // do nothing, just to see if an error occured $this->_instance->setDirectives(array('logging' => true)); } - - public function testCleanModeNotMatchingTags() + + public function testCleanModeNotMatchingTags() { - $this->_instance->setDirectives(array('logging' => false)); + $this->_instance->setDirectives(array('logging' => false)); $this->_instance->clean('notMatchingTag', array('tag1')); // do nothing, just to see if an error occured $this->_instance->setDirectives(array('logging' => true)); } - - public function testGetWithCompression() + + public function testGetWithCompression() { $this->_instance->setOption('compression', true); $this->testGetWithAnExistingCacheIdAndUTFCharacters(); } - + public function testConstructorWithAnAlternativeSyntax() { $server = array( @@ -123,7 +123,7 @@ public function testConstructorWithAnAlternativeSyntax() $this->_instance = new Zend_Cache_Backend_Memcached($options); $this->testGetWithAnExistingCacheIdAndUTFCharacters(); } - + // Because of limitations of this backend... public function testGetWithAnExpiredCacheId() {} public function testCleanModeMatchingTags2() {} @@ -135,22 +135,22 @@ public function testSaveCorrectCall() parent::testSaveCorrectCall(); $this->_instance->setDirectives(array('logging' => true)); } - + public function testSaveWithNullLifeTime() { $this->_instance->setDirectives(array('logging' => false)); parent::testSaveWithNullLifeTime(); $this->_instance->setDirectives(array('logging' => true)); } - - public function testSaveWithSpecificLifeTime() + + public function testSaveWithSpecificLifeTime() { - + $this->_instance->setDirectives(array('logging' => false)); parent::testSaveWithSpecificLifeTime(); $this->_instance->setDirectives(array('logging' => true)); } - + public function testGetMetadatas($notag = false) { parent::testGetMetadatas(true); diff --git a/test/OutputFrontendTest.php b/test/OutputFrontendTest.php index c0eaafa3e..1d9228809 100644 --- a/test/OutputFrontendTest.php +++ b/test/OutputFrontendTest.php @@ -41,9 +41,9 @@ * @group Zend_Cache */ class Zend_Cache_OutputFrontendTest extends PHPUnit_Framework_TestCase { - + private $_instance; - + public function setUp() { if (!$this->_instance) { @@ -52,17 +52,17 @@ public function setUp() $this->_instance->setBackend($this->_backend); } } - + public function tearDown() { unset($this->_instance); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Frontend_Output(array('lifetime' => 3600, 'caching' => true)); + $test = new Zend_Cache_Frontend_Output(array('lifetime' => 3600, 'caching' => true)); } - + public function testStartEndCorrectCall1() { ob_start(); @@ -76,7 +76,7 @@ public function testStartEndCorrectCall1() ob_implicit_flush(true); $this->assertEquals('foo', $data); } - + public function testStartEndCorrectCall2() { ob_start(); diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php index 50929127e..ad69b13ef 100644 --- a/test/PageFrontendTest.php +++ b/test/PageFrontendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -41,9 +41,9 @@ * @group Zend_Cache */ class Zend_Cache_PageFrontendTest extends PHPUnit_Framework_TestCase { - + private $_instance; - + public function setUp() { if (!$this->_instance) { @@ -52,17 +52,17 @@ public function setUp() $this->_instance->setBackend($this->_backend); } } - + public function tearDown() { unset($this->_instance); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Frontend_Page(array('lifetime' => 3600, 'caching' => true)); + $test = new Zend_Cache_Frontend_Page(array('lifetime' => 3600, 'caching' => true)); } - + public function testConstructorUnimplementedOption() { try { @@ -70,9 +70,9 @@ public function testConstructorUnimplementedOption() } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testConstructorWithBadDefaultOptions() { try { @@ -80,9 +80,9 @@ public function testConstructorWithBadDefaultOptions() } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + /** * The only bad default options are non-string keys * @group ZF-5034 @@ -94,9 +94,9 @@ public function testConstructorWithBadDefaultOptions2() } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testConstructorWithBadRegexps() { try { @@ -104,9 +104,9 @@ public function testConstructorWithBadRegexps() } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testConstructorWithBadRegexps2() { try { @@ -114,9 +114,9 @@ public function testConstructorWithBadRegexps2() } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + /** * Only non-string keys should raise exceptions * @group ZF-5034 @@ -124,13 +124,13 @@ public function testConstructorWithBadRegexps2() public function testConstructorWithBadRegexps3() { $array = array( - '^/$' => array('cache' => true), - '^/index/' => array('cache' => true), - '^/article/' => array('cache' => false), - '^/article/view/' => array( - 1 => true, - 'cache_with_post_variables' => true, - 'make_id_with_post_variables' => true, + '^/$' => array('cache' => true), + '^/index/' => array('cache' => true), + '^/article/' => array('cache' => false), + '^/article/view/' => array( + 1 => true, + 'cache_with_post_variables' => true, + 'make_id_with_post_variables' => true, ) ); try { @@ -138,29 +138,29 @@ public function testConstructorWithBadRegexps3() } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testConstructorWithGoodRegexps() { $array = array( - '^/$' => array('cache' => true), - '^/index/' => array('cache' => true), - '^/article/' => array('cache' => false), - '^/article/view/' => array( - 'cache' => true, - 'cache_with_post_variables' => true, - 'make_id_with_post_variables' => true, + '^/$' => array('cache' => true), + '^/index/' => array('cache' => true), + '^/article/' => array('cache' => false), + '^/article/view/' => array( + 'cache' => true, + 'cache_with_post_variables' => true, + 'make_id_with_post_variables' => true, ) ); - $test = new Zend_Cache_Frontend_Page(array('regexps' => $array)); + $test = new Zend_Cache_Frontend_Page(array('regexps' => $array)); } - + public function testConstructorWithGoodDefaultOptions() { $test = new Zend_Cache_Frontend_Page(array('default_options' => array('cache' => true))); } - + public function testStartEndCorrectCall1() { ob_start(); @@ -174,7 +174,7 @@ public function testStartEndCorrectCall1() ob_implicit_flush(true); $this->assertEquals('foo', $data); } - + public function testStartEndCorrectCall2() { ob_start(); @@ -188,7 +188,7 @@ public function testStartEndCorrectCall2() ob_implicit_flush(true); $this->assertEquals('foobar', $data); } - + public function testStartEndCorrectCallWithDebug() { $this->_instance->setOption('debug_header', true); @@ -202,6 +202,6 @@ public function testStartEndCorrectCallWithDebug() ob_end_clean(); ob_implicit_flush(true); $this->assertEquals('DEBUG HEADER : This is a cached page !foo', $data); - } + } } diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php index 4e8d327f8..1d03fc3ff 100644 --- a/test/SqliteBackendTest.php +++ b/test/SqliteBackendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -45,25 +45,25 @@ * @group Zend_Cache */ class Zend_Cache_sqliteBackendTest extends Zend_Cache_CommonExtendedBackendTest { - + protected $_instance; private $_cache_dir; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct('Zend_Cache_Backend_Sqlite', $data, $dataName); } - + public function setUp($notag = false) - { + { @mkdir($this->getTmpDir()); $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; $this->_instance = new Zend_Cache_Backend_Sqlite(array( 'cache_db_complete_path' => $this->_cache_dir . 'cache.db' )); - parent::setUp($notag); + parent::setUp($notag); } - + public function tearDown() { parent::tearDown(); @@ -71,12 +71,12 @@ public function tearDown() @unlink($this->_cache_dir . 'cache.db'); $this->rmdir(); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Sqlite(array('cache_db_complete_path' => $this->_cache_dir . 'cache.db')); + $test = new Zend_Cache_Backend_Sqlite(array('cache_db_complete_path' => $this->_cache_dir . 'cache.db')); } - + public function testConstructorWithABadDBPath() { try { @@ -86,32 +86,32 @@ public function testConstructorWithABadDBPath() } $this->fail('Zend_Cache_Exception was expected but not thrown'); } - + public function testCleanModeAllWithVacuum() { $this->_instance = new Zend_Cache_Backend_Sqlite(array( 'cache_db_complete_path' => $this->_cache_dir . 'cache.db', 'automatic_vacuum_factor' => 1 )); - parent::setUp(); + parent::setUp(); $this->assertTrue($this->_instance->clean('all')); $this->assertFalse($this->_instance->test('bar')); $this->assertFalse($this->_instance->test('bar2')); } - + public function testRemoveCorrectCallWithVacuum() - { + { $this->_instance = new Zend_Cache_Backend_Sqlite(array( 'cache_db_complete_path' => $this->_cache_dir . 'cache.db', 'automatic_vacuum_factor' => 1 )); - parent::setUp(); + parent::setUp(); $this->assertTrue($this->_instance->remove('bar')); - $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->test('bar')); $this->assertFalse($this->_instance->remove('barbar')); - $this->assertFalse($this->_instance->test('barbar')); + $this->assertFalse($this->_instance->test('barbar')); } - + } diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php index b104c9d6a..467bb6e63 100644 --- a/test/TwoLevelsBackendTest.php +++ b/test/TwoLevelsBackendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -45,17 +45,17 @@ * @group Zend_Cache */ class Zend_Cache_TwoLevelsBackendTest extends Zend_Cache_CommonExtendedBackendTest { - + protected $_instance; private $_cache_dir; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct('Zend_Cache_Backend_TwoLevels', $data, $dataName); } - + public function setUp($notag = false) - { + { @mkdir($this->getTmpDir()); $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; $slowBackend = 'File'; @@ -71,15 +71,15 @@ public function setUp($notag = false) 'fast_backend_options' => $fastBackendOptions, 'slow_backend_options' => $slowBackendOptions )); - parent::setUp($notag); + parent::setUp($notag); } - + public function tearDown() { parent::tearDown(); unset($this->_instance); } - + public function testConstructorCorrectCall() { $slowBackend = 'File'; @@ -96,7 +96,7 @@ public function testConstructorCorrectCall() 'slow_backend_options' => $slowBackendOptions )); } - + } diff --git a/test/ZendPlatformBackendTest.php b/test/ZendPlatformBackendTest.php index ff17ce90a..f488985b1 100644 --- a/test/ZendPlatformBackendTest.php +++ b/test/ZendPlatformBackendTest.php @@ -19,7 +19,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + /** * Zend_Cache */ @@ -45,35 +45,35 @@ * @group Zend_Cache */ class Zend_Cache_ZendPlatformBackendTest extends Zend_Cache_CommonBackendTest { - + protected $_instance; - + public function __construct($name = null, array $data = array(), $dataName = '') { parent::__construct('Zend_Cache_Backend_ZendPlatform', $data, $dataName); } - + public function setUp($notag = false) - { + { if(!function_exists('output_cache_get')) { $this->markTestSkipped('Zend Platform is not installed, skipping test'); return; } $this->_instance = new Zend_Cache_Backend_ZendPlatform(array()); - parent::setUp($notag); + parent::setUp($notag); } - + public function tearDown() { parent::tearDown(); unset($this->_instance); } - + public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_ZendPlatform(); + $test = new Zend_Cache_Backend_ZendPlatform(); } - + public function testRemoveCorrectCall() { $this->assertTrue($this->_instance->remove('bar')); From e8a21564af91a708b40ce46f7b3995ec86171c9e Mon Sep 17 00:00:00 2001 From: bate Date: Thu, 26 Nov 2009 06:15:12 +0000 Subject: [PATCH 024/311] ZF-8395: fixed missing array index check git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19249 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Memcached.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 741f1cd1c..28433b6ba 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -178,7 +178,7 @@ public function __construct(array $options = array()) public function load($id, $doNotTestCacheValidity = false) { $tmp = $this->_memcache->get($id); - if (is_array($tmp)) { + if (is_array($tmp) && isset($tmp[0])) { return $tmp[0]; } return false; From 0163b5da79d5460016ef12aaf742a3823fb024f7 Mon Sep 17 00:00:00 2001 From: bkarwin Date: Fri, 11 Dec 2009 21:16:39 +0000 Subject: [PATCH 025/311] improve consistent use of TestHelper, code covering filtering, and @group tags git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19582 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/AllTests.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/AllTests.php b/test/AllTests.php index 9b56669c0..7e53863e6 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -20,9 +20,6 @@ * @version $Id $ */ -/** - * Test helper - */ require_once dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . 'TestHelper.php'; if (!defined('PHPUnit_MAIN_METHOD')) { From 4ed6d473eed0413ae524d4fb76b2766da1656dba Mon Sep 17 00:00:00 2001 From: matthew Date: Tue, 15 Dec 2009 18:03:07 +0000 Subject: [PATCH 026/311] ZF-8547: Merge Zend_Exception previous exception support to trunk git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19661 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend.php b/src/Backend.php index 975b1bf11..6b68ef0c4 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -232,7 +232,7 @@ protected function _loggerSanity() */ require_once 'Zend/Log.php'; } catch (Zend_Exception $e) { - Zend_Cache::throwException('Logging feature is enabled but the Zend_Log class is not available'); + Zend_Cache::throwException('Logging feature is enabled but the Zend_Log class is not available', $e); } if (isset($this->_directives['logger'])) { if ($this->_directives['logger'] instanceof Zend_Log) { From 7c88e588055aeef2855cebdeb9ab9cacfebbdcdf Mon Sep 17 00:00:00 2001 From: mluiten Date: Sat, 19 Dec 2009 10:32:13 +0000 Subject: [PATCH 027/311] API Documentation improvement. Solves [ZF-4577] Zend_Cache_Core::test() may return integer when using File backend. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19780 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 2 +- src/Frontend/File.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Core.php b/src/Core.php index a3583ba5c..9cd034b61 100644 --- a/src/Core.php +++ b/src/Core.php @@ -307,7 +307,7 @@ public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = f * Test if a cache is available for the given id * * @param string $id Cache id - * @return boolean True is a cache is available, false else + * @return int|false Last modified time of cache entry if it is available, false otherwise */ public function test($id) { diff --git a/src/Frontend/File.php b/src/Frontend/File.php index 38cb7e8b3..c1ef6d0c8 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -174,7 +174,7 @@ public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = f * Test if a cache is available for the given id * * @param string $id Cache id - * @return boolean True is a cache is available, false else + * @return int|false Last modified time of cache entry if it is available, false otherwise */ public function test($id) { From 820190b1a628cc2cc55d528b43b71bd00e6c2aa1 Mon Sep 17 00:00:00 2001 From: alexander Date: Sat, 19 Dec 2009 16:35:29 +0000 Subject: [PATCH 028/311] Zend_Cache: TwoLevels backend properties visibility is changed to 'protected'. ZF-8430. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19787 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/TwoLevels.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index f21ef05e8..4a75b7ec7 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -95,21 +95,21 @@ class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Ca * * @var Zend_Cache_Backend */ - private $_slowBackend; + protected $_slowBackend; /** * Fast Backend * * @var Zend_Cache_Backend */ - private $_fastBackend; + protected $_fastBackend; /** * Cache for the fast backend filling percentage * * @var int */ - private $_fastBackendFillingPercentage = null; + protected $_fastBackendFillingPercentage = null; /** * Constructor From f07a1a58e10f08a689a05a6f398ddd9cce143a09 Mon Sep 17 00:00:00 2001 From: matthew Date: Mon, 21 Dec 2009 14:40:21 +0000 Subject: [PATCH 029/311] [REVIEW] Promoted Zend_Cache_Manager and Zend_Cache_Backend_Static to trunk git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19830 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/BlackHole.php | 250 ++++++++++++++++++++ src/Backend/Static.php | 459 +++++++++++++++++++++++++++++++++++++ src/Frontend/Capture.php | 79 +++++++ src/Manager.php | 272 ++++++++++++++++++++++ test/AllTests.php | 18 +- test/CommonBackendTest.php | 3 +- test/ManagerTest.php | 239 +++++++++++++++++++ test/StaticBackendTest.php | 248 ++++++++++++++++++++ 8 files changed, 1558 insertions(+), 10 deletions(-) create mode 100644 src/Backend/BlackHole.php create mode 100644 src/Backend/Static.php create mode 100644 src/Frontend/Capture.php create mode 100644 src/Manager.php create mode 100644 test/ManagerTest.php create mode 100644 test/StaticBackendTest.php diff --git a/src/Backend/BlackHole.php b/src/Backend/BlackHole.php new file mode 100644 index 000000000..da9c5baae --- /dev/null +++ b/src/Backend/BlackHole.php @@ -0,0 +1,250 @@ + 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) + { + } +} diff --git a/src/Backend/Static.php b/src/Backend/Static.php new file mode 100644 index 000000000..ad1c99eef --- /dev/null +++ b/src/Backend/Static.php @@ -0,0 +1,459 @@ + null, + 'sub_dir' => 'html', + 'file_extension' => '.html', + 'index_filename' => 'index', + 'file_locking' => true, + 'cache_file_umask' => 0600, + 'debug_header' => false, + 'tag_cache' => null, + ); + + /** + * 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 { + 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) + { + if ($name == 'tag_cache') { + return $this->getInnerCache(); + } else { + 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 (empty($id)) { + $id = $this->_detectId(); + } + 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 (empty($fileName)) { + $fileName = $this->_options['index_filename']; + } + $pathName = $this->_options['public_dir'] . dirname($id); + $file = $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) + { + if (!$this->_verifyPath($id)) { + Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); + } + + $fileName = basename($id); + if (empty($fileName)) { + $fileName = $this->_options['index_filename']; + } + $pathName = $this->_options['public_dir'] . dirname($id); + $file = $pathName . '/' . $fileName . $this->_options['file_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) + { + clearstatcache(); + if (is_null($id) || strlen($id) == 0) { + $id = $this->_detectId(); + } + + $fileName = basename($id); + if (empty($fileName)) { + $fileName = $this->_options['index_filename']; + } + + $pathName = $this->_options['public_dir'] . dirname($id); + if (!file_exists($pathName)) { + mkdir($pathName, $this->_options['cache_file_umask'], true); + } + + if (is_null($id) || strlen($id) == 0) { + $dataUnserialized = unserialize($data); + $data = $dataUnserialized['data']; + } + + $file = $pathName . '/' . $fileName . $this->_options['file_extension']; + if ($this->_options['file_locking']) { + $result = file_put_contents($file, $data, LOCK_EX); + } else { + $result = file_put_contents($file, $data); + } + @chmod($file, $this->_options['cache_file_umask']); + + if (count($tags) > 0) { + if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + $this->_tagged = $tagged; + } elseif (is_null($this->_tagged)) { + $this->_tagged = array(); + } + if (!isset($this->_tagged[$id])) { + $this->_tagged[$id] = array(); + } + $this->_tagged[$id] = array_unique(array_merge($this->_tagged[$id], $tags)); + $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME); + } + return (bool) $result; + } + + /** + * 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 (empty($fileName)) { + $fileName = $this->_options['index_filename']; + } + $pathName = $this->_options['public_dir'] . dirname($id); + $file = $pathName . '/' . $fileName . $this->_options['file_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 (empty($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; + } + foreach (new DirectoryIterator($directory) as $file) { + if (true === $file->isFile()) { + if (false === unlink($file->getPathName())) { + return false; + } + } + } + rmdir(dirname($path)); + } + 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 + */ + 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 (is_null($this->_tagged) && $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 (in_array($tag, $this->_tagged[$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_ALL: + if (is_null($this->_tagged)) { + $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); + $this->_tagged = $tagged; + } + if (is_null($this->_tagged) || 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 (is_null($this->_tagged)) { + $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); + $this->_tagged = $tagged; + } + if (is_null($this->_tagged) || empty($this->_tagged)) { + return true; + } + $urls = array_keys($this->_tagged); + foreach ($urls as $url) { + $difference = array_diff($tags, $this->_tagged[$url]); + 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 (is_null($this->_tagCache)) { + 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 + */ + 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"); + } + } +} diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php new file mode 100644 index 000000000..bd80a4e69 --- /dev/null +++ b/src/Frontend/Capture.php @@ -0,0 +1,79 @@ +_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 (is_null($id)) { + Zend_Cache::throwException('use of end() without a start()'); + } + $this->save($data, $id, $this->_tags); + return $data; + } +} diff --git a/src/Manager.php b/src/Manager.php new file mode 100644 index 000000000..fb693b974 --- /dev/null +++ b/src/Manager.php @@ -0,0 +1,272 @@ + array( + 'frontend' => array( + 'name' => null, + 'options' => array(), + ), + 'backend' => array( + 'name' => null, + 'options' => array(), + ), + ), + // Simple Common Default + 'default' => array( + 'frontend' => array( + 'name' => 'Core', + 'options' => array( + 'automatic_serialization' => true, + ), + ), + 'backend' => array( + 'name' => 'File', + 'options' => array( + 'cache_dir' => '../cache', + ), + ), + ), + // Static Page HTML Cache + 'page' => array( + 'frontend' => array( + 'name' => 'Output', + 'options' => array( + 'ignore_user_abort' => true, + ), + ), + 'backend' => array( + 'name' => 'Static', + 'options' => array( + 'public_dir' => '../public', + ), + ), + ), + // Tag Cache + 'tagCache' => array( + 'frontend' => array( + 'name' => 'Core', + 'options' => array( + 'automatic_serialization' => true, + ), + ), + 'backend' => array( + 'name' => 'File', + 'options' => array( + 'cache_dir' => '../cache', + ), + ), + ), + ); + + /** + * 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('tagCache'); + } + $this->_caches[$name] = Zend_Cache::factory( + $this->_optionTemplates[$name]['frontend']['name'], + $this->_optionTemplates[$name]['backend']['name'], + $this->_optionTemplates[$name]['frontend']['options'], + $this->_optionTemplates[$name]['backend']['options'] + ); + return $this->_caches[$name]; + } + } + + /** + * 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 + */ + 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; + } + + /** + * 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; + } + } + return $current; + } +} diff --git a/test/AllTests.php b/test/AllTests.php index 7e53863e6..4d0dc997b 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -26,21 +26,23 @@ define('PHPUnit_MAIN_METHOD', 'Zend_Cache_AllTests::main'); } -require_once 'Zend/Cache/FactoryTest.php'; +require_once 'Zend/Cache/ApcBackendTest.php'; +require_once 'Zend/Cache/ClassFrontendTest.php'; require_once 'Zend/Cache/CoreTest.php'; +require_once 'Zend/Cache/FactoryTest.php'; require_once 'Zend/Cache/FileBackendTest.php'; -require_once 'Zend/Cache/SqliteBackendTest.php'; -require_once 'Zend/Cache/OutputFrontendTest.php'; -require_once 'Zend/Cache/FunctionFrontendTest.php'; -require_once 'Zend/Cache/ClassFrontendTest.php'; require_once 'Zend/Cache/FileFrontendTest.php'; -require_once 'Zend/Cache/ApcBackendTest.php'; -require_once 'Zend/Cache/XcacheBackendTest.php'; +require_once 'Zend/Cache/FunctionFrontendTest.php'; +require_once 'Zend/Cache/ManagerTest.php'; require_once 'Zend/Cache/MemcachedBackendTest.php'; +require_once 'Zend/Cache/OutputFrontendTest.php'; require_once 'Zend/Cache/PageFrontendTest.php'; -require_once 'Zend/Cache/ZendPlatformBackendTest.php'; require_once 'Zend/Cache/SkipTests.php'; +require_once 'Zend/Cache/SqliteBackendTest.php'; +require_once 'Zend/Cache/StaticBackendTest.php'; require_once 'Zend/Cache/TwoLevelsBackendTest.php'; +require_once 'Zend/Cache/XcacheBackendTest.php'; +require_once 'Zend/Cache/ZendPlatformBackendTest.php'; require_once 'Zend/Cache/ZendServerDiskTest.php'; require_once 'Zend/Cache/ZendServerShMemTest.php'; diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php index b144ac16a..1a4bbcfa0 100644 --- a/test/CommonBackendTest.php +++ b/test/CommonBackendTest.php @@ -174,8 +174,7 @@ public function testRemoveCorrectCall() { $this->assertTrue($this->_instance->remove('bar')); $this->assertFalse($this->_instance->test('bar')); - - $this->_instance->remove('barbar'); + $this->assertFalse($this->_instance->remove('barbar')); $this->assertFalse($this->_instance->test('barbar')); } diff --git a/test/ManagerTest.php b/test/ManagerTest.php new file mode 100644 index 000000000..ea90b44f3 --- /dev/null +++ b/test/ManagerTest.php @@ -0,0 +1,239 @@ +_cache_dir = $this->mkdir(); + $this->_cache = Zend_Cache::factory( + 'Core', 'File', + array('automatic_serialization'=>true), + array('cache_dir'=>$this->_cache_dir) + ); + } + + public function tearDown() + { + $this->rmdir(); + $this->_cache = null; + } + + public function testSetsCacheObject() + { + $manager = new Zend_Cache_Manager; + $manager->setCache('cache1', $this->_cache); + $this->assertTrue($manager->getCache('cache1') instanceof Zend_Cache_Core); + } + + public function testLazyLoadsDefaultPageCache() + { + $manager = new Zend_Cache_Manager; + $manager->setTemplateOptions('tagCache',array( + 'backend' => array( + 'options' => array( + 'cache_dir' => $this->_cache_dir + ) + ) + )); + $this->assertTrue($manager->getCache('page') instanceof Zend_Cache_Frontend_Output); + } + + public function testCanOverrideCacheFrontendNameConfiguration() + { + $manager = new Zend_Cache_Manager; + $manager->setTemplateOptions('tagCache',array( + 'backend' => array( + 'options' => array( + 'cache_dir' => $this->_cache_dir + ) + ) + )); + $manager->setTemplateOptions('page', array( + 'frontend' => array( + 'name'=> 'Page' + ) + )); + $this->assertTrue($manager->getCache('page') instanceof Zend_Cache_Frontend_Page); + } + + public function testCanMergeTemplateCacheOptionsFromZendConfig() + { + $manager = new Zend_Cache_Manager; + $config = new Zend_Config(array( + 'backend' => array( + 'options' => array( + 'cache_dir' => $this->_cache_dir + ) + ) + )); + $manager->setTemplateOptions('tagCache', $config); + $options = $manager->getCacheTemplate('tagCache'); + $this->assertEquals($this->_cache_dir, $options['backend']['options']['cache_dir']); + } + + public function testCanOverrideCacheBackendendNameConfiguration() + { + $manager = new Zend_Cache_Manager; + $manager->setTemplateOptions('tagCache',array( + 'backend' => array( + 'options' => array( + 'cache_dir' => $this->_cache_dir + ) + ) + )); + $manager->setTemplateOptions('page', array( + 'backend' => array( + 'name'=> 'File' + ) + )); + $this->assertTrue($manager->getCache('page')->getBackend() instanceof Zend_Cache_Backend_File); + } + + public function testCanOverrideCacheFrontendOptionsConfiguration() + { + $manager = new Zend_Cache_Manager; + $manager->setTemplateOptions('page', array( + 'frontend' => array( + 'options'=> array( + 'lifetime' => 9999 + ) + ) + )); + $config = $manager->getCacheTemplate('page'); + $this->assertEquals(9999, $config['frontend']['options']['lifetime']); + } + + public function testCanOverrideCacheBackendOptionsConfiguration() + { + $manager = new Zend_Cache_Manager; + $manager->setTemplateOptions('page', array( + 'backend' => array( + 'options'=> array( + 'public_dir' => './cacheDir' + ) + ) + )); + $config = $manager->getCacheTemplate('page'); + $this->assertEquals('./cacheDir', $config['backend']['options']['public_dir']); + } + + public function testSetsConfigTemplate() + { + $manager = new Zend_Cache_Manager; + $config = array( + 'frontend' => array( + 'name' => 'Core', + 'options' => array( + 'automatic_serialization' => true + ) + ), + 'backend' => array( + 'name' => 'File', + 'options' => array( + 'cache_dir' => '../cache', + ) + ) + ); + $manager->setCacheTemplate('myCache', $config); + $this->assertSame($config, $manager->getCacheTemplate('myCache')); + } + + public function testSetsOptionsTemplateUsingZendConfig() + { + $manager = new Zend_Cache_Manager; + $config = array( + 'frontend' => array( + 'name' => 'Core', + 'options' => array( + 'automatic_serialization' => true + ) + ), + 'backend' => array( + 'name' => 'File', + 'options' => array( + 'cache_dir' => '../cache', + ) + ) + ); + $manager->setCacheTemplate('myCache', new Zend_Config($config)); + $this->assertSame($config, $manager->getCacheTemplate('myCache')); + } + + public function testConfigTemplatesDetectedAsAvailableCaches() + { + $manager = new Zend_Cache_Manager; + $this->assertTrue($manager->hasCache('page')); + } + + public function testGettingPageCacheAlsoCreatesTagCache() + { + $manager = new Zend_Cache_Manager; + $tagCacheConfig = $manager->getCacheTemplate('tagCache'); + $tagCacheConfig['backend']['options']['cache_dir'] = $this->getTmpDir(); + $manager->setCacheTemplate('tagCache', $tagCacheConfig); + $tagCache = $manager->getCache('page')->getBackend()->getOption('tag_cache'); + $this->assertTrue($tagCache instanceof Zend_Cache_Core); + } + + // Helper Methods + + public function mkdir() + { + $tmp = $this->getTmpDir(); + @mkdir($tmp); + return $tmp; + } + + public function rmdir() + { + $tmpDir = $this->getTmpDir(false); + foreach (glob("$tmpDir*") as $dirname) { + @rmdir($dirname); + } + } + + public function getTmpDir($date = true) + { + $suffix = ''; + $tmp = sys_get_temp_dir(); + if ($date) { + $suffix = date('mdyHis'); + } + if (is_writeable($tmp)) { + return $tmp . DIRECTORY_SEPARATOR . 'zend_cache_tmp_dir_' . $suffix; + } else { + throw new Exception("no writable tmpdir found"); + } + } + +} diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php new file mode 100644 index 000000000..39e44d37f --- /dev/null +++ b/test/StaticBackendTest.php @@ -0,0 +1,248 @@ +mkdir(); + $this->_cache_dir = $this->mkdir(); + @mkdir($this->_cache_dir.'/tags'); + + $this->_innerCache = Zend_Cache::factory('Core','File', + array('automatic_serialization'=>true), array('cache_dir'=>$this->_cache_dir.'/tags') + ); + $this->_instance = new Zend_Cache_Backend_Static(array( + 'public_dir' => $this->_cache_dir, + 'tag_cache' => $this->_innerCache + )); + + $logger = new Zend_Log(new Zend_Log_Writer_Null()); + $this->_instance->setDirectives(array('logger' => $logger)); + + $this->_requestUriOld = + isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null; + $_SERVER['REQUEST_URI'] = '/foo'; + + $this->_instance->setDirectives(array('logging' => true)); + + $this->_instance->save('bar : data to cache', '/bar', array('tag3', 'tag4')); + $this->_instance->save('bar2 : data to cache', '/bar2', array('tag3', 'tag1')); + $this->_instance->save('bar3 : data to cache', '/bar3', array('tag2', 'tag3')); + } + + public function tearDown() + { + parent::tearDown(); + unset($this->_instance); + $_SERVER['REQUEST_URI'] = $this->_requestUriOld; + $this->rmdir(); + } + + public function testConstructorCorrectCall() + { + $test = new Zend_Cache_Backend_Static(array()); + } + + public function testRemoveCorrectCall() + { + $this->assertTrue($this->_instance->remove('/bar')); + $this->assertFalse($this->_instance->test('/bar')); + $this->assertFalse($this->_instance->remove('/barbar')); + $this->assertFalse($this->_instance->test('/barbar')); + } + + public function testOptionsSetTagCache() + { + $test = new Zend_Cache_Backend_Static(array('tag_cache'=>$this->_innerCache)); + $this->assertTrue($test->getInnerCache() instanceof Zend_Cache_Core); + } + + public function testSaveCorrectCall() + { + $res = $this->_instance->save('data to cache', '/foo', array('tag1', 'tag2')); + $this->assertTrue($res); + } + + public function testSaveWithNullLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => null)); + $res = $this->_instance->save('data to cache', '/foo', array('tag1', 'tag2')); + $this->assertTrue($res); + } + + public function testSaveWithSpecificLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => 3600)); + $res = $this->_instance->save('data to cache', '/foo', array('tag1', 'tag2'), 10); + $this->assertTrue($res); + } + + public function testTestWithAnExistingCacheId() + { + $res = $this->_instance->test('/bar'); + if (!$res) { + $this->fail('test() return false'); + } + return; + } + + public function testTestWithANonExistingCacheId() + { + $this->assertFalse($this->_instance->test('/barbar')); + } + + public function testTestWithAnExistingCacheIdAndANullLifeTime() + { + $this->_instance->setDirectives(array('lifetime' => null)); + $res = $this->_instance->test('/bar'); + if (!$res) { + $this->fail('test() return false'); + } + return; + } + + public function testGetWithANonExistingCacheId() + { + $this->assertFalse($this->_instance->load('/barbar')); + } + + public function testGetWithAnExistingCacheId() + { + $this->assertEquals('bar : data to cache', $this->_instance->load('/bar')); + } + + public function testGetWithAnExistingCacheIdAndUTFCharacters() + { + $data = '"""""' . "'" . '\n' . 'ééééé'; + $this->_instance->save($data, '/foo'); + $this->assertEquals($data, $this->_instance->load('/foo')); + } + + public function testCleanModeMatchingTags() + { + $this->assertTrue($this->_instance->clean('matchingTag', array('tag3'))); + $this->assertFalse($this->_instance->test('/bar')); + $this->assertFalse($this->_instance->test('/bar2')); + } + + public function testCleanModeMatchingTags2() + { + $this->assertTrue($this->_instance->clean('matchingTag', array('tag3', 'tag4'))); + $this->assertFalse($this->_instance->test('/bar')); + } + + public function testCleanModeNotMatchingTags() + { + $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag3'))); + $this->assertTrue($this->_instance->test('/bar')); + $this->assertTrue($this->_instance->test('/bar2')); + } + + public function testCleanModeNotMatchingTags2() + { + $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag4'))); + $this->assertTrue($this->_instance->test('/bar')); + $this->assertFalse($this->_instance->test('/bar2')); + } + + public function testCleanModeNotMatchingTags3() + { + $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag4', 'tag1'))); + $this->assertTrue($this->_instance->test('/bar')); + $this->assertTrue($this->_instance->test('/bar2')); + $this->assertFalse($this->_instance->test('/bar3')); + } + + public function testCleanModeAll() + { + $this->assertTrue($this->_instance->clean('all')); + $this->assertFalse($this->_instance->test('bar')); + $this->assertFalse($this->_instance->test('bar2')); + } + + + // Irrelevant Tests (from common tests) + + public function testGetWithAnExpiredCacheId() + { + $this->markTestSkipped('Irrelevant Test'); + } + + public function testCleanModeOld() + { + $this->markTestSkipped('Irrelevant Test'); + } + + // Helper Methods + + public function mkdir() + { + $tmp = $this->getTmpDir(); + @mkdir($tmp); + return $tmp; + } + + public function rmdir() + { + $tmpDir = $this->getTmpDir(false); + foreach (glob("$tmpDir*") as $dirname) { + @rmdir($dirname); + } + } + + public function getTmpDir($date = true) + { + $suffix = ''; + $tmp = sys_get_temp_dir(); + if ($date) { + $suffix = date('mdyHis'); + } + if (is_writeable($tmp)) { + return $tmp . DIRECTORY_SEPARATOR . 'zend_cache_tmp_dir_' . $suffix; + } else { + throw new Exception("no writable tmpdir found"); + } + } + +} From a1a27eda82612c2c8b7863a5fac322f52fc75ce1 Mon Sep 17 00:00:00 2001 From: padraic Date: Mon, 21 Dec 2009 21:49:33 +0000 Subject: [PATCH 030/311] Added check to save() method to ensure any octal presented as a string is converted to a decimal (otherwise left untouched) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@19865 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index ad1c99eef..a67e92604 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -189,7 +189,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $pathName = $this->_options['public_dir'] . dirname($id); if (!file_exists($pathName)) { - mkdir($pathName, $this->_options['cache_file_umask'], true); + mkdir($pathName, $this->_octdec($this->_options['cache_file_umask']), true); } if (is_null($id) || strlen($id) == 0) { @@ -456,4 +456,19 @@ protected static function _validateIdOrTag($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 $val The potential octal in need of conversion + * @return int + */ + protected function _octdec($val) + { + if (decoct(octdec($val)) == $val && is_string($val)) { + return octdec($val); + } + return $val; + } } From 61d1898cd0ca486a7daee1928b2e625efd7a5ec5 Mon Sep 17 00:00:00 2001 From: bkarwin Date: Wed, 6 Jan 2010 02:05:09 +0000 Subject: [PATCH 031/311] [ZF-8718] update copyright tags for 2010 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20096 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 4 ++-- src/Backend/Apc.php | 4 ++-- src/Backend/BlackHole.php | 4 ++-- src/Backend/ExtendedInterface.php | 4 ++-- src/Backend/File.php | 4 ++-- src/Backend/Interface.php | 4 ++-- src/Backend/Memcached.php | 4 ++-- src/Backend/Sqlite.php | 4 ++-- src/Backend/Static.php | 4 ++-- src/Backend/Test.php | 4 ++-- src/Backend/TwoLevels.php | 4 ++-- src/Backend/Xcache.php | 4 ++-- src/Backend/ZendPlatform.php | 4 ++-- src/Backend/ZendServer.php | 4 ++-- src/Backend/ZendServer/Disk.php | 4 ++-- src/Backend/ZendServer/ShMem.php | 4 ++-- src/Core.php | 4 ++-- src/Exception.php | 4 ++-- src/Frontend/Capture.php | 4 ++-- src/Frontend/Class.php | 4 ++-- src/Frontend/File.php | 4 ++-- src/Frontend/Function.php | 4 ++-- src/Frontend/Output.php | 4 ++-- src/Frontend/Page.php | 4 ++-- src/Manager.php | 4 ++-- test/AllTests.php | 4 ++-- test/ApcBackendTest.php | 4 ++-- test/ClassFrontendTest.php | 6 +++--- test/CommonBackendTest.php | 4 ++-- test/CommonExtendedBackendTest.php | 4 ++-- test/CoreTest.php | 4 ++-- test/FactoryException.php | 4 ++-- test/FactoryTest.php | 4 ++-- test/FileBackendTest.php | 4 ++-- test/FileFrontendTest.php | 4 ++-- test/FunctionFrontendTest.php | 4 ++-- test/ManagerTest.php | 4 ++-- test/MemcachedBackendTest.php | 4 ++-- test/OutputFrontendTest.php | 4 ++-- test/PageFrontendTest.php | 4 ++-- test/SkipTests.php | 18 +++++++++--------- test/SqliteBackendTest.php | 4 ++-- test/TwoLevelsBackendTest.php | 4 ++-- test/XcacheBackendTest.php | 4 ++-- test/ZendPlatformBackendTest.php | 4 ++-- test/ZendServerDiskTest.php | 4 ++-- test/ZendServerShMemTest.php | 4 ++-- 47 files changed, 102 insertions(+), 102 deletions(-) diff --git a/src/Backend.php b/src/Backend.php index 6b68ef0c4..76d0e7867 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -24,7 +24,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Backend diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php index d6c532ca2..885a756ab 100644 --- a/src/Backend/Apc.php +++ b/src/Backend/Apc.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -35,7 +35,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/BlackHole.php b/src/Backend/BlackHole.php index da9c5baae..9ae72f397 100644 --- a/src/Backend/BlackHole.php +++ b/src/Backend/BlackHole.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $ */ @@ -33,7 +33,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Backend_BlackHole diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php index 53b2ffff1..b48be4d13 100644 --- a/src/Backend/ExtendedInterface.php +++ b/src/Backend/ExtendedInterface.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -28,7 +28,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/File.php b/src/Backend/File.php index cfd5007cf..e67ea6918 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/Interface.php b/src/Backend/Interface.php index 99d15fa22..cee5cc539 100644 --- a/src/Backend/Interface.php +++ b/src/Backend/Interface.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -24,7 +24,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Zend_Cache_Backend_Interface diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 28433b6ba..59947f93c 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -35,7 +35,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index 286fbfc95..46f9116f3 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface diff --git a/src/Backend/Static.php b/src/Backend/Static.php index a67e92604..4b564dc30 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $ */ @@ -33,7 +33,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Backend_Static diff --git a/src/Backend/Test.php b/src/Backend/Test.php index 49cfd4423..53dd12e1b 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -34,7 +34,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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_Interface diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 4a75b7ec7..74b3278c7 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -35,7 +35,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php index 4d9e1a80b..664d45b69 100644 --- a/src/Backend/Xcache.php +++ b/src/Backend/Xcache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -35,7 +35,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/ZendPlatform.php b/src/Backend/ZendPlatform.php index 4e55bda6a..e6146bb62 100644 --- a/src/Backend/ZendPlatform.php +++ b/src/Backend/ZendPlatform.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -36,7 +36,7 @@ * * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index 808fd4238..ead7de7db 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -31,7 +31,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index 43cca0d6c..6c6f67d7c 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -31,7 +31,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index 8f2ef6a5e..f21b3a38e 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -31,7 +31,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Backend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Core.php b/src/Core.php index 9cd034b61..66a7b9889 100644 --- a/src/Core.php +++ b/src/Core.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -22,7 +22,7 @@ /** * @package Zend_Cache - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Core diff --git a/src/Exception.php b/src/Exception.php index 7c2d56f61..e6cf9f3c0 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -26,7 +26,7 @@ /** * @package Zend_Cache - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 {} diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index bd80a4e69..98e70ab62 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index 16dea0350..ffb8cac7d 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -29,7 +29,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Frontend/File.php b/src/Frontend/File.php index c1ef6d0c8..eccb1eeb4 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index 043be1df2..46c266f8d 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Frontend/Output.php b/src/Frontend/Output.php index 8b5d925c4..2c253a9f5 100644 --- a/src/Frontend/Output.php +++ b/src/Frontend/Output.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index 5f361af52..bf6046ea1 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -30,7 +30,7 @@ /** * @package Zend_Cache * @subpackage Zend_Cache_Frontend - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 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 diff --git a/src/Manager.php b/src/Manager.php index fb693b974..18b7a9508 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_Manager diff --git a/test/AllTests.php b/test/AllTests.php index 4d0dc997b..51f597c46 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id $ */ @@ -50,7 +50,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php index 2aa8ea284..e3bb859f5 100644 --- a/test/ApcBackendTest.php +++ b/test/ApcBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/ClassFrontendTest.php b/test/ClassFrontendTest.php index b7e9b3576..b286fb881 100644 --- a/test/ClassFrontendTest.php +++ b/test/ClassFrontendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -38,7 +38,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -63,7 +63,7 @@ public function foobar2($param1, $param2) { * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php index 1a4bbcfa0..cb94d0e76 100644 --- a/test/CommonBackendTest.php +++ b/test/CommonBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -33,7 +33,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/CommonExtendedBackendTest.php b/test/CommonExtendedBackendTest.php index 542ec04fa..3c7fcfada 100644 --- a/test/CommonExtendedBackendTest.php +++ b/test/CommonExtendedBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -38,7 +38,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/CoreTest.php b/test/CoreTest.php index f333affd2..38d13d8f2 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -39,7 +39,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/FactoryException.php b/test/FactoryException.php index b208d11d2..e049f5a5e 100644 --- a/test/FactoryException.php +++ b/test/FactoryException.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -27,7 +27,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_FactoryException extends PHPUnit_Extensions_ExceptionTestCase diff --git a/test/FactoryTest.php b/test/FactoryTest.php index 1855c1692..810c7ab73 100644 --- a/test/FactoryTest.php +++ b/test/FactoryTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -43,7 +43,7 @@ class FooBarTestFrontend extends Zend_Cache_Core { } * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php index 6c2668203..4168573bb 100644 --- a/test/FileBackendTest.php +++ b/test/FileBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -46,7 +46,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php index 0f040e2b6..5cdab99e3 100644 --- a/test/FileFrontendTest.php +++ b/test/FileFrontendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -36,7 +36,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index c6368d83d..c7953a79b 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -41,7 +41,7 @@ function foobar($param1, $param2) { * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/ManagerTest.php b/test/ManagerTest.php index ea90b44f3..e1beb7a13 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -14,7 +14,7 @@ * * @category Zend_Cache * @package UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -26,7 +26,7 @@ /** * @category Zend_Cache * @package UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Cache_ManagerTest extends PHPUnit_Framework_TestCase diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 2a4444a7d..5e1f9181c 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/OutputFrontendTest.php b/test/OutputFrontendTest.php index 1d9228809..aaf67b1f2 100644 --- a/test/OutputFrontendTest.php +++ b/test/OutputFrontendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -36,7 +36,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php index ad69b13ef..d5433a8f3 100644 --- a/test/PageFrontendTest.php +++ b/test/PageFrontendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -36,7 +36,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/SkipTests.php b/test/SkipTests.php index a9fec7a20..296498321 100644 --- a/test/SkipTests.php +++ b/test/SkipTests.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -33,7 +33,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -58,7 +58,7 @@ public function testCacheBackend() * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -70,7 +70,7 @@ class Zend_Cache_ApcBackendTest_SkipTests extends Zend_Cache_BackendTest_SkipTes * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -82,7 +82,7 @@ class Zend_Cache_XcacheBackendTest_SkipTests extends Zend_Cache_BackendTest_Skip * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -94,7 +94,7 @@ class Zend_Cache_MemcachedBackendTest_SkipTests extends Zend_Cache_BackendTest_S * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -106,7 +106,7 @@ class Zend_Cache_SqliteBackendTest_SkipTests extends Zend_Cache_BackendTest_Skip * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -118,7 +118,7 @@ class Zend_Cache_ZendPlatformBackendTest_SkipTests extends Zend_Cache_BackendTes * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ @@ -130,7 +130,7 @@ class Zend_Cache_TwoLevelsBackendTest_SkipTests extends Zend_Cache_BackendTest_S * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php index 1d03fc3ff..437080576 100644 --- a/test/SqliteBackendTest.php +++ b/test/SqliteBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php index 467bb6e63..9eed99916 100644 --- a/test/TwoLevelsBackendTest.php +++ b/test/TwoLevelsBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/XcacheBackendTest.php b/test/XcacheBackendTest.php index dc67c5720..8a008972b 100644 --- a/test/XcacheBackendTest.php +++ b/test/XcacheBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/ZendPlatformBackendTest.php b/test/ZendPlatformBackendTest.php index f488985b1..b69f6312f 100644 --- a/test/ZendPlatformBackendTest.php +++ b/test/ZendPlatformBackendTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index dfa434d26..e46fb4617 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php index e74b16dcd..b888e5fcf 100755 --- a/test/ZendServerShMemTest.php +++ b/test/ZendServerShMemTest.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ @@ -40,7 +40,7 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ From def2ba6622d89b0f4c02cacb40a15349a4492ade Mon Sep 17 00:00:00 2001 From: mabe Date: Mon, 18 Jan 2010 14:38:21 +0000 Subject: [PATCH 032/311] ZF-5514: implemented patch and adapted test backend git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20378 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Test.php | 11 ++++++----- src/Frontend/Class.php | 11 ++++++----- src/Frontend/Function.php | 11 ++++++----- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/Backend/Test.php b/src/Backend/Test.php index 53dd12e1b..412a6d6af 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -103,7 +103,11 @@ public function setDirectives($directives) public function load($id, $doNotTestCacheValidity = false) { $this->_addLog('get', array($id, $doNotTestCacheValidity)); - if ($id=='false') { + if ( $id == 'false' + || $id == 'd8523b3ee441006261eeffa5c3d3a0a7' + || $id == 'e83249ea22178277d5befc2c5e2e9ace' + || $id == '40f649b94977c0a6e76902e2a0b43587') + { return false; } if ($id=='serialized') { @@ -136,10 +140,7 @@ public function test($id) if ($id=='false') { return false; } - if (($id=='d8523b3ee441006261eeffa5c3d3a0a7') or ($id=='3c439c922209e2cb0b54d6deffccd75a')) { - return false; - } - if (($id=='40f649b94977c0a6e76902e2a0b43587') or ($id=='e83249ea22178277d5befc2c5e2e9ace')) { + if (($id=='3c439c922209e2cb0b54d6deffccd75a')) { return false; } return 123456; diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index ffb8cac7d..e4aef9452 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -208,14 +208,14 @@ public function __call($name, $parameters) // We do not have not cache return call_user_func_array(array($this->_cachedEntity, $name), $parameters); } + $id = $this->_makeId($name, $parameters); - if ($this->test($id)) { + if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1]) ) { // A cache is available - $result = $this->load($id); - $output = $result[0]; - $return = $result[1]; + $output = $rs[0]; + $return = $rs[1]; } else { - // A cache is not available + // A cache is not available (or not valid for this frontend) ob_start(); ob_implicit_flush(false); $return = call_user_func_array(array($this->_cachedEntity, $name), $parameters); @@ -224,6 +224,7 @@ public function __call($name, $parameters) $data = array($output, $return); $this->save($data, $id, $this->_tags, $this->_specificLifetime, $this->_priority); } + echo $output; return $return; } diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index 46c266f8d..337623f86 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -89,14 +89,14 @@ public function call($name, $parameters = array(), $tags = array(), $specificLif // We do not have not cache return call_user_func_array($name, $parameters); } + $id = $this->_makeId($name, $parameters); - if ($this->test($id)) { + if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) { // A cache is available - $result = $this->load($id); - $output = $result[0]; - $return = $result[1]; + $output = $rs[0]; + $return = $rs[1]; } else { - // A cache is not available + // A cache is not available (or not valid for this frontend) ob_start(); ob_implicit_flush(false); $return = call_user_func_array($name, $parameters); @@ -105,6 +105,7 @@ public function call($name, $parameters = array(), $tags = array(), $specificLif $data = array($output, $return); $this->save($data, $id, $tags, $specificLifetime, $priority); } + echo $output; return $return; } From 40dabc700020572653dbc1fd982d7d6126cac772 Mon Sep 17 00:00:00 2001 From: ralph Date: Wed, 20 Jan 2010 16:01:48 +0000 Subject: [PATCH 033/311] ZF-8809 - Various win32 issues: - Added abstract to CommonBackendTest - Fixed line ending issues in Zend_CodeGenerator_Php_PropertyTest - Fixed file deletion failures on win32 in Zend_Paginator tests - Fixed failing test in Zend_Validate_BarcodeTest (win32 specific) - Disabled compression test in Zend_Validate_File when system is buggy git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20443 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/CommonBackendTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php index cb94d0e76..65b73468c 100644 --- a/test/CommonBackendTest.php +++ b/test/CommonBackendTest.php @@ -37,7 +37,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_CommonBackendTest extends PHPUnit_Framework_TestCase { +abstract class Zend_Cache_CommonBackendTest extends PHPUnit_Framework_TestCase { protected $_instance; protected $_className; From d0e5dc3ea6560ec46e44c20165cf893b8902fe9c Mon Sep 17 00:00:00 2001 From: padraic Date: Fri, 22 Jan 2010 14:22:12 +0000 Subject: [PATCH 034/311] Add missing $this return on a method git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20520 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Manager.php b/src/Manager.php index 18b7a9508..b80fd8353 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -185,6 +185,7 @@ public function setCacheTemplate($name, $options) . ' an associative array or instance of Zend_Config'); } $this->_optionTemplates[$name] = $options; + return $this; } /** From 98b7545a3a1784631aa84b6ae75e812be638afa4 Mon Sep 17 00:00:00 2001 From: padraic Date: Fri, 22 Jan 2010 15:44:23 +0000 Subject: [PATCH 035/311] Added tests checking for cache backend naming capitalisation corruption (none found but added anyway for ZFINC-125) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20524 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/ManagerTest.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/ManagerTest.php b/test/ManagerTest.php index e1beb7a13..9a9170322 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -167,6 +167,24 @@ public function testSetsConfigTemplate() $manager->setCacheTemplate('myCache', $config); $this->assertSame($config, $manager->getCacheTemplate('myCache')); } + + public function testSetsConfigTemplateWithoutMultipartNameNormalisation() + { + $manager = new Zend_Cache_Manager; + $config = array( + 'frontend' => array( + 'name' => 'Core', + 'options' => array( + 'automatic_serialization' => true + ) + ), + 'backend' => array( + 'name' => 'BlackHole' + ) + ); + $manager->setCacheTemplate('myCache', $config); + $this->assertSame($config, $manager->getCacheTemplate('myCache')); + } public function testSetsOptionsTemplateUsingZendConfig() { From 9cc9f6e74de1d7588d4bdc82c85bf729e4b039b3 Mon Sep 17 00:00:00 2001 From: padraic Date: Sun, 24 Jan 2010 18:41:24 +0000 Subject: [PATCH 036/311] Updated tagCache to tagcache name to make it possible to adjust via application.ini or other git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20580 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Manager.php b/src/Manager.php index b80fd8353..e24254973 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -91,7 +91,7 @@ class Zend_Cache_Manager ), ), // Tag Cache - 'tagCache' => array( + 'tagcache' => array( 'frontend' => array( 'name' => 'Core', 'options' => array( @@ -155,7 +155,7 @@ public function getCache($name) || !$this->_optionTemplates[$name]['backend']['options']['tag_cache'] instanceof Zend_Cache_Core) ) { $this->_optionTemplates[$name]['backend']['options']['tag_cache'] - = $this->getCache('tagCache'); + = $this->getCache('tagcache'); } $this->_caches[$name] = Zend_Cache::factory( $this->_optionTemplates[$name]['frontend']['name'], From 58e296aa5f0ad40fa26a9adfde368c2cefda984f Mon Sep 17 00:00:00 2001 From: padraic Date: Sun, 24 Jan 2010 20:30:02 +0000 Subject: [PATCH 037/311] Updates to Zend_Cache Static Caching - fixes ID encoding, and default frontend setting in Cache Manager git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20582 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 16 +++++++++++++++- src/Manager.php | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 4b564dc30..e48e60376 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -117,6 +117,8 @@ public function load($id, $doNotTestCacheValidity = false) { if (empty($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'); @@ -130,7 +132,7 @@ public function load($id, $doNotTestCacheValidity = false) $fileName = $this->_options['index_filename']; } $pathName = $this->_options['public_dir'] . dirname($id); - $file = $pathName . '/' . $fileName . $this->_options['file_extension']; + $file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension']; if (file_exists($file)) { $content = file_get_contents($file); return $content; @@ -147,6 +149,7 @@ public function load($id, $doNotTestCacheValidity = false) */ 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'); } @@ -180,6 +183,8 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) clearstatcache(); if (is_null($id) || strlen($id) == 0) { $id = $this->_detectId(); + } else { + $id = $this->_decodeId($id); } $fileName = basename($id); @@ -435,6 +440,7 @@ protected function _detectId() * @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) { @@ -471,4 +477,12 @@ protected function _octdec($val) } return $val; } + + /** + * Decode a request URI from the provided ID + */ + protected function _decodeId($id) + { + return pack('H*', $id);; + } } diff --git a/src/Manager.php b/src/Manager.php index e24254973..f18ce6835 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -78,7 +78,7 @@ class Zend_Cache_Manager // Static Page HTML Cache 'page' => array( 'frontend' => array( - 'name' => 'Output', + 'name' => 'Capture', 'options' => array( 'ignore_user_abort' => true, ), From b741a7e41a57f6250efa26f09bd81e3f0566b8e1 Mon Sep 17 00:00:00 2001 From: mabe Date: Sun, 24 Jan 2010 23:28:59 +0000 Subject: [PATCH 038/311] ZF-8897: Zend_Cache_Backend_Memcached: Now getFillingPercentage only throws exception if all server failes git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20588 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Memcached.php | 29 +++++++++++++++-------------- test/MemcachedBackendTest.php | 15 +++++++++++++-- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 59947f93c..f1001a260 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -383,22 +383,23 @@ public function getFillingPercentage() $memSize = 0; $memUsed = 0; foreach ($mems as $key => $mem) { - if ($mem === false) { - Zend_Cache::throwException('can\'t get stat from ' . $key); - } else { - $eachSize = $mem['limit_maxbytes']; - if ($eachSize == 0) { - Zend_Cache::throwException('can\'t get memory size from ' . $key); - } - - $eachUsed = $mem['bytes']; - if ($eachUsed > $eachSize) { - $eachUsed = $eachSize; - } + if ($mem === false || !$mem['limit_maxbytes']) { + $this->_log('can\'t get stat from ' . $key); + continue; + } - $memSize += $eachSize; - $memUsed += $eachUsed; + $eachSize = $mem['limit_maxbytes']; + $eachUsed = $mem['bytes']; + if ($eachUsed > $eachSize) { + $eachUsed = $eachSize; } + + $memSize += $eachSize; + $memUsed += $eachUsed; + } + + if (!$memSize || !$memUsed) { + Zend_Cache::throwException('Can\'t get filling percentage'); } return ((int) (100. * ($memUsed / $memSize))); diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 5e1f9181c..72bfb4289 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -55,13 +55,18 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = true) { - $server = array( + $serverValid = array( 'host' => TESTS_ZEND_CACHE_MEMCACHED_HOST, 'port' => TESTS_ZEND_CACHE_MEMCACHED_PORT, 'persistent' => TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT ); + $serverFail = array( + 'host' => 'not.exist', + 'port' => TESTS_ZEND_CACHE_MEMCACHED_PORT, + 'persistent' => TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT + ); $options = array( - 'servers' => array(0 => $server) + 'servers' => array($serverValid, $serverFail) ); $this->_instance = new Zend_Cache_Backend_Memcached($options); parent::setUp($notag); @@ -156,6 +161,12 @@ public function testGetMetadatas($notag = false) parent::testGetMetadatas(true); } + public function testGetFillingPercentage() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testGetFillingPercentage(); + } + } From 5d93d1ae9f91b3d9694aacc34ffb2693bc6d5ee3 Mon Sep 17 00:00:00 2001 From: mabe Date: Mon, 25 Jan 2010 00:12:10 +0000 Subject: [PATCH 039/311] ZF-8856: reverted changes of save() of ZF-5702: The add command isn't faster because it needs a second request if cache already exist and a memcached bug on replacing items couldn't be reproduced git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20590 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Memcached.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index f1001a260..21f28c928 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -219,13 +219,14 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } else { $flag = 0; } - // #ZF-5702 : we try add() first becase set() seems to be slower - if (!($result = $this->_memcache->add($id, array($data, time(), $lifetime), $flag, $lifetime))) { - $result = $this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime); - } + + // 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("Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend"); } + return $result; } From 2d205a32dcb60cbf11fe0b0451b5c08233895de8 Mon Sep 17 00:00:00 2001 From: padraic Date: Mon, 25 Jan 2010 13:03:23 +0000 Subject: [PATCH 040/311] Updated static caching classes for new ID encoding git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20598 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 25 +++++++++++++++++++------ src/Frontend/Capture.php | 3 ++- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index e48e60376..be2e13121 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -192,23 +192,21 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $fileName = $this->_options['index_filename']; } - $pathName = $this->_options['public_dir'] . dirname($id); - if (!file_exists($pathName)) { - mkdir($pathName, $this->_octdec($this->_options['cache_file_umask']), true); - } + $pathName = realpath($this->_options['public_dir']) . dirname($id); + $this->_createDirectoriesFor($pathName); if (is_null($id) || strlen($id) == 0) { $dataUnserialized = unserialize($data); $data = $dataUnserialized['data']; } - $file = $pathName . '/' . $fileName . $this->_options['file_extension']; + $file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension']; if ($this->_options['file_locking']) { $result = file_put_contents($file, $data, LOCK_EX); } else { $result = file_put_contents($file, $data); } - @chmod($file, $this->_options['cache_file_umask']); + @chmod($file, $this->_octdec($this->_options['cache_file_umask'])); if (count($tags) > 0) { if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { @@ -224,6 +222,21 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } return (bool) $result; } + + /** + * Recursively create the directories needed to write the static file + */ + protected function _createDirectoriesFor($path) + { + $parts = explode('/', $path); + $directory = ''; + foreach ($parts as $part) { + $directory = rtrim($directory, '/') . '/' . $part; + if (!is_dir($directory)) { + mkdir($directory, $this->_octdec($this->_options['cache_file_umask'])); + } + } + } /** * Remove a cache record diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index 98e70ab62..6161c93b2 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -71,8 +71,9 @@ public function _flush($data) { $id = array_pop($this->_idStack); if (is_null($id)) { - Zend_Cache::throwException('use of end() without a start()'); + Zend_Cache::throwException('use of _flush() without a start()'); } + file_put_contents('/var/www/data.dump', $data); $this->save($data, $id, $this->_tags); return $data; } From 07e8514a11c52f6a09938631cfe9c9e480ec43d7 Mon Sep 17 00:00:00 2001 From: padraic Date: Mon, 25 Jan 2010 13:56:06 +0000 Subject: [PATCH 041/311] Updated Static Backend tests for hexadecimal encoded ID requirements git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20600 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/StaticBackendTest.php | 54 +++++++++++++++++++------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index 39e44d37f..bcfb43885 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -66,9 +66,9 @@ public function setUp($notag = false) $this->_instance->setDirectives(array('logging' => true)); - $this->_instance->save('bar : data to cache', '/bar', array('tag3', 'tag4')); - $this->_instance->save('bar2 : data to cache', '/bar2', array('tag3', 'tag1')); - $this->_instance->save('bar3 : data to cache', '/bar3', array('tag2', 'tag3')); + $this->_instance->save('bar : data to cache', bin2hex('/bar'), array('tag3', 'tag4')); + $this->_instance->save('bar2 : data to cache', bin2hex('/bar2'), array('tag3', 'tag1')); + $this->_instance->save('bar3 : data to cache', bin2hex('/bar3'), array('tag2', 'tag3')); } public function tearDown() @@ -87,9 +87,9 @@ public function testConstructorCorrectCall() public function testRemoveCorrectCall() { $this->assertTrue($this->_instance->remove('/bar')); - $this->assertFalse($this->_instance->test('/bar')); + $this->assertFalse($this->_instance->test(bin2hex('/bar'))); $this->assertFalse($this->_instance->remove('/barbar')); - $this->assertFalse($this->_instance->test('/barbar')); + $this->assertFalse($this->_instance->test(bin2hex('/barbar'))); } public function testOptionsSetTagCache() @@ -100,27 +100,27 @@ public function testOptionsSetTagCache() public function testSaveCorrectCall() { - $res = $this->_instance->save('data to cache', '/foo', array('tag1', 'tag2')); + $res = $this->_instance->save('data to cache', bin2hex('/foo'), array('tag1', 'tag2')); $this->assertTrue($res); } public function testSaveWithNullLifeTime() { $this->_instance->setDirectives(array('lifetime' => null)); - $res = $this->_instance->save('data to cache', '/foo', array('tag1', 'tag2')); + $res = $this->_instance->save('data to cache', bin2hex('/foo'), array('tag1', 'tag2')); $this->assertTrue($res); } public function testSaveWithSpecificLifeTime() { $this->_instance->setDirectives(array('lifetime' => 3600)); - $res = $this->_instance->save('data to cache', '/foo', array('tag1', 'tag2'), 10); + $res = $this->_instance->save('data to cache', bin2hex('/foo'), array('tag1', 'tag2'), 10); $this->assertTrue($res); } public function testTestWithAnExistingCacheId() { - $res = $this->_instance->test('/bar'); + $res = $this->_instance->test(bin2hex('/bar')); if (!$res) { $this->fail('test() return false'); } @@ -129,13 +129,13 @@ public function testTestWithAnExistingCacheId() public function testTestWithANonExistingCacheId() { - $this->assertFalse($this->_instance->test('/barbar')); + $this->assertFalse($this->_instance->test(bin2hex('/barbar'))); } public function testTestWithAnExistingCacheIdAndANullLifeTime() { $this->_instance->setDirectives(array('lifetime' => null)); - $res = $this->_instance->test('/bar'); + $res = $this->_instance->test(bin2hex('/bar')); if (!$res) { $this->fail('test() return false'); } @@ -144,61 +144,61 @@ public function testTestWithAnExistingCacheIdAndANullLifeTime() public function testGetWithANonExistingCacheId() { - $this->assertFalse($this->_instance->load('/barbar')); + $this->assertFalse($this->_instance->load(bin2hex('/barbar'))); } public function testGetWithAnExistingCacheId() { - $this->assertEquals('bar : data to cache', $this->_instance->load('/bar')); + $this->assertEquals('bar : data to cache', $this->_instance->load(bin2hex('/bar'))); } public function testGetWithAnExistingCacheIdAndUTFCharacters() { $data = '"""""' . "'" . '\n' . 'ééééé'; - $this->_instance->save($data, '/foo'); - $this->assertEquals($data, $this->_instance->load('/foo')); + $this->_instance->save($data, bin2hex('/foo')); + $this->assertEquals($data, $this->_instance->load(bin2hex('/foo'))); } public function testCleanModeMatchingTags() { $this->assertTrue($this->_instance->clean('matchingTag', array('tag3'))); - $this->assertFalse($this->_instance->test('/bar')); - $this->assertFalse($this->_instance->test('/bar2')); + $this->assertFalse($this->_instance->test(bin2hex('/bar'))); + $this->assertFalse($this->_instance->test(bin2hex('/bar2'))); } public function testCleanModeMatchingTags2() { $this->assertTrue($this->_instance->clean('matchingTag', array('tag3', 'tag4'))); - $this->assertFalse($this->_instance->test('/bar')); + $this->assertFalse($this->_instance->test(bin2hex('/bar'))); } public function testCleanModeNotMatchingTags() { $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag3'))); - $this->assertTrue($this->_instance->test('/bar')); - $this->assertTrue($this->_instance->test('/bar2')); + $this->assertTrue($this->_instance->test(bin2hex('/bar'))); + $this->assertTrue($this->_instance->test(bin2hex('/bar2'))); } public function testCleanModeNotMatchingTags2() { $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag4'))); - $this->assertTrue($this->_instance->test('/bar')); - $this->assertFalse($this->_instance->test('/bar2')); + $this->assertTrue($this->_instance->test(bin2hex('/bar'))); + $this->assertFalse($this->_instance->test(bin2hex('/bar2'))); } public function testCleanModeNotMatchingTags3() { $this->assertTrue($this->_instance->clean('notMatchingTag', array('tag4', 'tag1'))); - $this->assertTrue($this->_instance->test('/bar')); - $this->assertTrue($this->_instance->test('/bar2')); - $this->assertFalse($this->_instance->test('/bar3')); + $this->assertTrue($this->_instance->test(bin2hex('/bar'))); + $this->assertTrue($this->_instance->test(bin2hex('/bar2'))); + $this->assertFalse($this->_instance->test(bin2hex('/bar3'))); } public function testCleanModeAll() { $this->assertTrue($this->_instance->clean('all')); - $this->assertFalse($this->_instance->test('bar')); - $this->assertFalse($this->_instance->test('bar2')); + $this->assertFalse($this->_instance->test(bin2hex('bar'))); + $this->assertFalse($this->_instance->test(bin2hex('bar2'))); } From 06b9ee1f62bb43ed693cce9c71d2b8553c3c9d75 Mon Sep 17 00:00:00 2001 From: padraic Date: Mon, 25 Jan 2010 14:25:52 +0000 Subject: [PATCH 042/311] Updated static page cache tag cache, Zend_Cache_Manager::PAGETAGCACHE, handling and fixed tag communication from Zend_Cache_Frontend_Capture git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20602 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/Capture.php | 3 ++- src/Manager.php | 10 ++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index 6161c93b2..f3903a26d 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -52,8 +52,9 @@ class Zend_Cache_Frontend_Capture extends Zend_Cache_Core * @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, $tags) + public function start($id, array $tags) { + $this->_tags = $tags; ob_start(array($this, '_flush')); ob_implicit_flush(false); $this->_idStack[] = $id; diff --git a/src/Manager.php b/src/Manager.php index f18ce6835..6e669c2e1 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -34,6 +34,11 @@ 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 @@ -91,11 +96,12 @@ class Zend_Cache_Manager ), ), // Tag Cache - 'tagcache' => array( + 'pagetag' => array( 'frontend' => array( 'name' => 'Core', 'options' => array( 'automatic_serialization' => true, + 'lifetime' => null ), ), 'backend' => array( @@ -155,7 +161,7 @@ public function getCache($name) || !$this->_optionTemplates[$name]['backend']['options']['tag_cache'] instanceof Zend_Cache_Core) ) { $this->_optionTemplates[$name]['backend']['options']['tag_cache'] - = $this->getCache('tagcache'); + = $this->getCache(self::PAGETAGCACHE ); } $this->_caches[$name] = Zend_Cache::factory( $this->_optionTemplates[$name]['frontend']['name'], From 2fb44d526160ab241c1df6eab6abc8f52da498ff Mon Sep 17 00:00:00 2001 From: matthew Date: Mon, 25 Jan 2010 19:39:48 +0000 Subject: [PATCH 043/311] ZF-8932: allow empty options passed to CacheManager git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20611 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Manager.php b/src/Manager.php index 6e669c2e1..bcfbd1ad7 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -166,8 +166,8 @@ public function getCache($name) $this->_caches[$name] = Zend_Cache::factory( $this->_optionTemplates[$name]['frontend']['name'], $this->_optionTemplates[$name]['backend']['name'], - $this->_optionTemplates[$name]['frontend']['options'], - $this->_optionTemplates[$name]['backend']['options'] + isset($this->_optionTemplates[$name]['frontend']['options']) ? $this->_optionTemplates[$name]['frontend']['options'] : array(), + isset($this->_optionTemplates[$name]['backend']['options']) ? $this->_optionTemplates[$name]['backend']['options'] : array() ); return $this->_caches[$name]; } From 0482390725fa4c93e34576122887fafcb5fbf8b9 Mon Sep 17 00:00:00 2001 From: padraic Date: Tue, 26 Jan 2010 12:37:31 +0000 Subject: [PATCH 044/311] Updated Static-Cache umask default - fixes out-of-box issues on Ubuntu (for example) where the permissions were problematic. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20645 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 4 ++-- src/Manager.php | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index be2e13121..da903808b 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -52,7 +52,7 @@ class Zend_Cache_Backend_Static 'file_extension' => '.html', 'index_filename' => 'index', 'file_locking' => true, - 'cache_file_umask' => 0600, + 'cache_file_umask' => 0644, 'debug_header' => false, 'tag_cache' => null, ); @@ -254,7 +254,7 @@ public function remove($id) $fileName = $this->_options['index_filename']; } $pathName = $this->_options['public_dir'] . dirname($id); - $file = $pathName . '/' . $fileName . $this->_options['file_extension']; + $file = realpath($pathName) . '/' . $fileName . $this->_options['file_extension']; if (!file_exists($file)) { return false; } diff --git a/src/Manager.php b/src/Manager.php index bcfbd1ad7..75debeec3 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -108,6 +108,7 @@ class Zend_Cache_Manager 'name' => 'File', 'options' => array( 'cache_dir' => '../cache', + 'cache_file_umask' => 0644 ), ), ), From b97f57a2280d61f64f9023d191674e2cdb68f000 Mon Sep 17 00:00:00 2001 From: padraic Date: Tue, 26 Jan 2010 12:42:05 +0000 Subject: [PATCH 045/311] Added disable_caching flag option to Static Backend cache to disable caching via configuration options (useful for testing/development) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20647 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index da903808b..25ca5afe9 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -55,6 +55,7 @@ class Zend_Cache_Backend_Static 'cache_file_umask' => 0644, 'debug_header' => false, 'tag_cache' => null, + 'disable_caching' => false ); /** @@ -180,6 +181,9 @@ public function test($id) */ public function save($data, $id, $tags = array(), $specificLifetime = false) { + if ($this->_options['disable_caching']) { + return true; + } clearstatcache(); if (is_null($id) || strlen($id) == 0) { $id = $this->_detectId(); From 57e49cc722f17d1632baca76ab1e30711be03262 Mon Sep 17 00:00:00 2001 From: padraic Date: Wed, 27 Jan 2010 11:29:10 +0000 Subject: [PATCH 046/311] Patched extension support for static caching to include removal/clean ops based on inner cache git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20687 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 39 +++++++++++++++++++++++++++++++------- src/Frontend/Capture.php | 12 +++++++++--- test/StaticBackendTest.php | 7 +++++++ 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 25ca5afe9..ed7ea3d81 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -101,7 +101,13 @@ public function getOption($name) if ($name == 'tag_cache') { return $this->getInnerCache(); } else { - return parent::getOption($name); + if (in_array($name, $this->_options)) { + return $this->_options[$name]; + } + if ($name == 'lifetime') { + return parent::getLifetime(); + } + return null; } } @@ -159,8 +165,20 @@ public function test($id) if (empty($fileName)) { $fileName = $this->_options['index_filename']; } + if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + $this->_tagged = $tagged; + } elseif (!$this->_tagged) { + return false; + } $pathName = $this->_options['public_dir'] . dirname($id); - $file = $pathName . '/' . $fileName . $this->_options['file_extension']; + + // 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; } @@ -184,6 +202,11 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) if ($this->_options['disable_caching']) { return true; } + $extension = null; + if (is_array($data)) { + $extension = '.' . ltrim($data[1], '.'); + $data = $data[0]; + } clearstatcache(); if (is_null($id) || strlen($id) == 0) { $id = $this->_detectId(); @@ -203,8 +226,9 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $dataUnserialized = unserialize($data); $data = $dataUnserialized['data']; } - - $file = rtrim($pathName, '/') . '/' . $fileName . $this->_options['file_extension']; + $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 { @@ -221,7 +245,8 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) if (!isset($this->_tagged[$id])) { $this->_tagged[$id] = array(); } - $this->_tagged[$id] = array_unique(array_merge($this->_tagged[$id], $tags)); + $this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id], $tags)); + $this->_tagged[$id]['extension'] = $ext; $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME); } return (bool) $result; @@ -341,7 +366,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) foreach ($tags as $tag) { $urls = array_keys($this->_tagged); foreach ($urls as $url) { - if (in_array($tag, $this->_tagged[$url])) { + if (in_array($tag, $this->_tagged[$url]['tags'])) { $this->remove($url); unset($this->_tagged[$url]); } @@ -382,7 +407,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } $urls = array_keys($this->_tagged); foreach ($urls as $url) { - $difference = array_diff($tags, $this->_tagged[$url]); + $difference = array_diff($tags, $this->_tagged[$url]['tags']); if (count($tags) == count($difference)) { $this->remove($url); unset($this->_tagged[$url]); diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index f3903a26d..a91986f35 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -45,6 +45,8 @@ class Zend_Cache_Frontend_Capture extends Zend_Cache_Core * @var array */ protected $_tags = array(); + + protected $_extension = null; /** * Start the cache @@ -52,9 +54,10 @@ class Zend_Cache_Frontend_Capture extends Zend_Cache_Core * @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) + 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; @@ -74,8 +77,11 @@ public function _flush($data) if (is_null($id)) { Zend_Cache::throwException('use of _flush() without a start()'); } - file_put_contents('/var/www/data.dump', $data); - $this->save($data, $id, $this->_tags); + if ($this->_extension) { + $this->save(array($data, $this->_extension), $id, $this->_tags); + } else { + $this->save($data, $id, $this->_tags); + } return $data; } } diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index bcfb43885..f64b9e698 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -118,6 +118,13 @@ public function testSaveWithSpecificLifeTime() $this->assertTrue($res); } + public function testSaveWithSpecificExtension() + { + $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo'), array('tag1')); + $this->assertTrue($this->_instance->test(bin2hex('/foo'))); + unlink($this->_instance->getOption('public_dir') . '/foo.xml'); + } + public function testTestWithAnExistingCacheId() { $res = $this->_instance->test(bin2hex('/bar')); From 4ba3fccc8ddabe2bfa9f37aa1842fe267a2649e4 Mon Sep 17 00:00:00 2001 From: padraic Date: Wed, 27 Jan 2010 11:42:58 +0000 Subject: [PATCH 047/311] Added support for extension tracking without requiring tags - both now share same inner cache git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20689 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 34 +++++++++++++++++++++------------- test/StaticBackendTest.php | 17 ++++++++++++++++- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index ed7ea3d81..698ad1024 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -236,19 +236,17 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } @chmod($file, $this->_octdec($this->_options['cache_file_umask'])); - if (count($tags) > 0) { - if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { - $this->_tagged = $tagged; - } elseif (is_null($this->_tagged)) { - $this->_tagged = array(); - } - if (!isset($this->_tagged[$id])) { - $this->_tagged[$id] = array(); - } - $this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id], $tags)); - $this->_tagged[$id]['extension'] = $ext; - $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME); + if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + $this->_tagged = $tagged; + } elseif (is_null($this->_tagged)) { + $this->_tagged = array(); } + if (!isset($this->_tagged[$id])) { + $this->_tagged[$id] = array(); + } + $this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id], $tags)); + $this->_tagged[$id]['extension'] = $ext; + $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME); return (bool) $result; } @@ -279,11 +277,21 @@ public function remove($id) Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); } $fileName = basename($id); + if (is_null($this->_tagged) && $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 (empty($fileName)) { $fileName = $this->_options['index_filename']; } $pathName = $this->_options['public_dir'] . dirname($id); - $file = realpath($pathName) . '/' . $fileName . $this->_options['file_extension']; + $file = realpath($pathName) . '/' . $fileName . $extension; if (!file_exists($file)) { return false; } diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index f64b9e698..096a19431 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -117,13 +117,28 @@ public function testSaveWithSpecificLifeTime() $res = $this->_instance->save('data to cache', bin2hex('/foo'), array('tag1', 'tag2'), 10); $this->assertTrue($res); } - + public function testSaveWithSpecificExtension() + { + $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo2')); + $this->assertTrue($this->_instance->test(bin2hex('/foo2'))); + unlink($this->_instance->getOption('public_dir') . '/foo2.xml'); + } + + public function testSaveWithSpecificExtensionWithTag() { $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo'), array('tag1')); $this->assertTrue($this->_instance->test(bin2hex('/foo'))); unlink($this->_instance->getOption('public_dir') . '/foo.xml'); } + + public function testRemovalWithSpecificExtension() + { + $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo'), array('tag1')); + $this->assertTrue($this->_instance->test(bin2hex('/foo'))); + $this->assertTrue($this->_instance->remove('/foo')); + $this->assertFalse($this->_instance->test(bin2hex('/foo'))); + } public function testTestWithAnExistingCacheId() { From eac212fe51e5765fea458e4887029a8bfa034f14 Mon Sep 17 00:00:00 2001 From: padraic Date: Wed, 27 Jan 2010 16:47:12 +0000 Subject: [PATCH 048/311] Switched from array parameter to serialized parameter when saving static cache data git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20694 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 18 +++++++++++++++++- src/Manager.php | 1 + test/StaticBackendTest.php | 12 ++++++------ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 698ad1024..c70e76572 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -203,10 +203,12 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) return true; } $extension = null; - if (is_array($data)) { + if ($this->_isSerialized($data)) { + $data = unserialize($data); $extension = '.' . ltrim($data[1], '.'); $data = $data[0]; } + clearstatcache(); if (is_null($id) || strlen($id) == 0) { $id = $this->_detectId(); @@ -264,6 +266,20 @@ protected function _createDirectoriesFor($path) } } } + + /** + * 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 diff --git a/src/Manager.php b/src/Manager.php index 75debeec3..295c27d1f 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -86,6 +86,7 @@ class Zend_Cache_Manager 'name' => 'Capture', 'options' => array( 'ignore_user_abort' => true, + 'automatic_serialization' => true ), ), 'backend' => array( diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index 096a19431..c46cf8660 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -120,24 +120,24 @@ public function testSaveWithSpecificLifeTime() public function testSaveWithSpecificExtension() { - $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo2')); + $res = $this->_instance->save(serialize(array('data to cache', 'xml')), bin2hex('/foo2')); $this->assertTrue($this->_instance->test(bin2hex('/foo2'))); unlink($this->_instance->getOption('public_dir') . '/foo2.xml'); } public function testSaveWithSpecificExtensionWithTag() { - $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo'), array('tag1')); + $res = $this->_instance->save(serialize(array('data to cache', 'xml')), bin2hex('/foo'), array('tag1')); $this->assertTrue($this->_instance->test(bin2hex('/foo'))); unlink($this->_instance->getOption('public_dir') . '/foo.xml'); } public function testRemovalWithSpecificExtension() { - $res = $this->_instance->save(array('data to cache', 'xml'), bin2hex('/foo'), array('tag1')); - $this->assertTrue($this->_instance->test(bin2hex('/foo'))); - $this->assertTrue($this->_instance->remove('/foo')); - $this->assertFalse($this->_instance->test(bin2hex('/foo'))); + $res = $this->_instance->save(serialize(array('data to cache', 'xml')), bin2hex('/foo3'), array('tag1')); + $this->assertTrue($this->_instance->test(bin2hex('/foo3'))); + $this->assertTrue($this->_instance->remove('/foo3')); + $this->assertFalse($this->_instance->test(bin2hex('/foo3'))); } public function testTestWithAnExistingCacheId() From e941c7e74173a7f5e51b04a92cf342c4534ef872 Mon Sep 17 00:00:00 2001 From: padraic Date: Wed, 27 Jan 2010 18:00:33 +0000 Subject: [PATCH 049/311] Fixed nesting of tags in static cache backend git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20696 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 4 ++-- src/Frontend/Capture.php | 2 +- src/Manager.php | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index c70e76572..839edb429 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -208,7 +208,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $extension = '.' . ltrim($data[1], '.'); $data = $data[0]; } - + clearstatcache(); if (is_null($id) || strlen($id) == 0) { $id = $this->_detectId(); @@ -246,7 +246,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) if (!isset($this->_tagged[$id])) { $this->_tagged[$id] = array(); } - $this->_tagged[$id]['tags'] = array_unique(array_merge($this->_tagged[$id], $tags)); + $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; diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index a91986f35..a4ed47d6a 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -78,7 +78,7 @@ public function _flush($data) Zend_Cache::throwException('use of _flush() without a start()'); } if ($this->_extension) { - $this->save(array($data, $this->_extension), $id, $this->_tags); + $this->save(serialize(array($data, $this->_extension)), $id, $this->_tags); } else { $this->save($data, $id, $this->_tags); } diff --git a/src/Manager.php b/src/Manager.php index 295c27d1f..e4739bc9e 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -86,7 +86,7 @@ class Zend_Cache_Manager 'name' => 'Capture', 'options' => array( 'ignore_user_abort' => true, - 'automatic_serialization' => true +// 'automatic_serialization' => true ), ), 'backend' => array( From 3bc53232f9cc4cf02fae51e65e989b582081621d Mon Sep 17 00:00:00 2001 From: padraic Date: Wed, 27 Jan 2010 22:21:20 +0000 Subject: [PATCH 050/311] Updated permissions git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20706 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 839edb429..1f079d5b1 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -47,15 +47,16 @@ class Zend_Cache_Backend_Static * @var array */ protected $_options = array( - 'public_dir' => null, - 'sub_dir' => 'html', - 'file_extension' => '.html', - 'index_filename' => 'index', - 'file_locking' => true, - 'cache_file_umask' => 0644, - 'debug_header' => false, - 'tag_cache' => null, - 'disable_caching' => false + 'public_dir' => null, + 'sub_dir' => 'html', + 'file_extension' => '.html', + 'index_filename' => 'index', + 'file_locking' => true, + 'cache_file_umask' => 0600, + 'cache_directory_umask' => 0700, + 'debug_header' => false, + 'tag_cache' => null, + 'disable_caching' => false ); /** @@ -232,6 +233,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) if ($extension) $ext = $extension; $file = rtrim($pathName, '/') . '/' . $fileName . $ext; if ($this->_options['file_locking']) { + file_put_contents('/var/www/data.dump', $file.$data); $result = file_put_contents($file, $data, LOCK_EX); } else { $result = file_put_contents($file, $data); @@ -262,7 +264,7 @@ protected function _createDirectoriesFor($path) foreach ($parts as $part) { $directory = rtrim($directory, '/') . '/' . $part; if (!is_dir($directory)) { - mkdir($directory, $this->_octdec($this->_options['cache_file_umask'])); + mkdir($directory, $this->_octdec($this->_options['cache_directory_umask'])); } } } From 1560ca46ae301b255c43a8fb3bc298a3ed84b188 Mon Sep 17 00:00:00 2001 From: padraic Date: Thu, 28 Jan 2010 00:29:37 +0000 Subject: [PATCH 051/311] Ensured static cache tag array is initialised to avoid merging NULL to a tag array incorrectly git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20708 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 1f079d5b1..e2fc5288a 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -248,6 +248,9 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) 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); @@ -392,7 +395,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) foreach ($tags as $tag) { $urls = array_keys($this->_tagged); foreach ($urls as $url) { - if (in_array($tag, $this->_tagged[$url]['tags'])) { + if (isset($this->_tagged[$url]['tags']) && in_array($tag, $this->_tagged[$url]['tags'])) { $this->remove($url); unset($this->_tagged[$url]); } From ed697a9f5ff542eafedadd66a2ed8ce77cda19f0 Mon Sep 17 00:00:00 2001 From: mikaelkael Date: Sun, 31 Jan 2010 09:43:03 +0000 Subject: [PATCH 052/311] [ZF-9029] Add svn keyword Id git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20785 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/BlackHole.php | 2 +- src/Backend/Static.php | 2 +- src/Frontend/Capture.php | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Backend/BlackHole.php b/src/Backend/BlackHole.php index 9ae72f397..066bba28c 100644 --- a/src/Backend/BlackHole.php +++ b/src/Backend/BlackHole.php @@ -17,7 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $ + * @version $Id$ */ /** diff --git a/src/Backend/Static.php b/src/Backend/Static.php index e2fc5288a..7bcd97ab2 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -17,7 +17,7 @@ * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: BlackHole.php 17867 2009-08-28 09:42:11Z yoshida@zend.co.jp $ + * @version $Id$ */ /** diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index a4ed47d6a..3da6a5bda 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -17,6 +17,7 @@ * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * @version $Id$ */ From 8ee91a774922f7f7d81a7c6b49118996674f0cf3 Mon Sep 17 00:00:00 2001 From: "yoshida@zend.co.jp" Date: Mon, 1 Feb 2010 20:52:24 +0000 Subject: [PATCH 053/311] [ZF-8741]Zend_Cache_Core::getIdsMatchingAnyTags() not implemented git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20815 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 45 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/src/Core.php b/src/Core.php index 66a7b9889..d839c9202 100644 --- a/src/Core.php +++ b/src/Core.php @@ -27,6 +27,12 @@ */ 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 * @@ -463,10 +469,10 @@ public function clean($mode = 'all', $tags = array()) public function getIdsMatchingTags($tags = array()) { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException('tags are not supported by the current backend'); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } return $this->_backend->getIdsMatchingTags($tags); } @@ -482,14 +488,33 @@ public function getIdsMatchingTags($tags = array()) public function getIdsNotMatchingTags($tags = array()) { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException('tags are not supported by the current backend'); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } return $this->_backend->getIdsNotMatchingTags($tags); } + /** + * 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_SUPPORT_TAG); + } + return $this->_backend->getIdsMatchingAnyTags($tags); + } + /** * Return an array of stored cache ids * @@ -498,7 +523,7 @@ public function getIdsNotMatchingTags($tags = array()) public function getIds() { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } $array = $this->_backend->getIds(); if ((!isset($this->_options['cache_id_prefix'])) || ($this->_options['cache_id_prefix'] == '')) return $array; @@ -522,10 +547,10 @@ public function getIds() public function getTags() { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException('tags are not supported by the current backend'); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } return $this->_backend->getTags(); } @@ -538,7 +563,7 @@ public function getTags() public function getFillingPercentage() { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } return $this->_backend->getFillingPercentage(); } @@ -557,7 +582,7 @@ public function getFillingPercentage() public function getMetadatas($id) { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } $id = $this->_id($id); // cache id may need prefix return $this->_backend->getMetadatas($id); @@ -573,7 +598,7 @@ public function getMetadatas($id) public function touch($id, $extraLifetime) { if (!$this->_extendedBackend) { - Zend_Cache::throwException('Current backend doesn\'t implement the Zend_Cache_Backend_ExtendedInterface, so this method is not available'); + Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } $id = $this->_id($id); // cache id may need prefix return $this->_backend->touch($id, $extraLifetime); From c9745bc16ebe4c6f496a7d58589336a54fb0240b Mon Sep 17 00:00:00 2001 From: matthew Date: Wed, 3 Feb 2010 18:18:32 +0000 Subject: [PATCH 054/311] ZF-9014: remove obsolete code in Zend_Cache_Backend::_loggerSanity() git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20880 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/Backend.php b/src/Backend.php index 76d0e7867..a0c633174 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -226,22 +226,16 @@ protected function _loggerSanity() if (!isset($this->_directives['logging']) || !$this->_directives['logging']) { return; } - try { - /** - * @see Zend_Log - */ - require_once 'Zend/Log.php'; - } catch (Zend_Exception $e) { - Zend_Cache::throwException('Logging feature is enabled but the Zend_Log class is not available', $e); - } + if (isset($this->_directives['logger'])) { if ($this->_directives['logger'] instanceof Zend_Log) { return; - } else { - Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.'); } + 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'; $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); $this->_directives['logger'] = $logger; From 171c8886668cbc32714c547b8a13dbbecb05630d Mon Sep 17 00:00:00 2001 From: padraic Date: Fri, 5 Feb 2010 14:35:13 +0000 Subject: [PATCH 055/311] Allows interpretation of a lifetime setting set to an empty string as NULL - required to support INI configuration. Fixes ZF-9092 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20929 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 3 +++ test/CoreTest.php | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/Core.php b/src/Core.php index d839c9202..f8840fa80 100644 --- a/src/Core.php +++ b/src/Core.php @@ -262,6 +262,9 @@ 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; } diff --git a/test/CoreTest.php b/test/CoreTest.php index 38d13d8f2..65ed671cd 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -86,6 +86,17 @@ public function testSettingOptionsWithZendConfig() $test->setConfig($config); $this->assertEquals(3600, $test->getOption('lifetime')); } + + /** + * @group ZF-9092 + */ + public function testSettingLifetimeAsEmptyIsInterpretedAsNull() + { + $config = new Zend_Config(array('lifetime' => '', 'caching' => true)); + $test = new Zend_Cache_Core(); + $test->setConfig($config); + $this->assertSame(NULL, $test->getOption('lifetime')); + } public function testConstructorBadOption() { From 1c675358da41d32275af34ab9e40d69ba4abce4b Mon Sep 17 00:00:00 2001 From: padraic Date: Tue, 16 Feb 2010 14:20:35 +0000 Subject: [PATCH 056/311] Removed commented out line from Zend_Cache_Manager Fixed a parameter missing bug in Zend_Feed_Pubsubhubbub (0.3 Compatibility) git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21066 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Manager.php b/src/Manager.php index e4739bc9e..75debeec3 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -86,7 +86,6 @@ class Zend_Cache_Manager 'name' => 'Capture', 'options' => array( 'ignore_user_abort' => true, -// 'automatic_serialization' => true ), ), 'backend' => array( From 4bcebf6271dbb76cb037755e7c14345a0e8e41c0 Mon Sep 17 00:00:00 2001 From: padraic Date: Tue, 23 Feb 2010 18:53:48 +0000 Subject: [PATCH 057/311] Add require_once for Zend_Cache class - fixes ZF-9239 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21162 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Manager.php b/src/Manager.php index 75debeec3..a409a2b81 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -22,6 +22,9 @@ /** @see Zend_Cache_Exception */ require_once 'Zend/Cache/Exception.php'; +/** @see Zend_Cache */ +require_once 'Zend/Cache.php'; + /** * @category Zend * @package Zend_Cache From b1b67209114045f26cd63bf24c5b81e6d55f9473 Mon Sep 17 00:00:00 2001 From: mabe Date: Sun, 28 Feb 2010 02:30:51 +0000 Subject: [PATCH 058/311] ZF-8633: check ids by pattern [a-zA-Z0-9_] in stead of [\w] and set D modifier git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21221 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 4 ++-- src/Core.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index e67ea6918..e20a3d3c1 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -123,8 +123,8 @@ public function __construct(array $options = array()) $this->setCacheDir(self::getTmpDir() . DIRECTORY_SEPARATOR, false); } if (isset($this->_options['file_name_prefix'])) { // particular case for this option - if (!preg_match('~^[\w]+$~', $this->_options['file_name_prefix'])) { - Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-A0-9_]'); + 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) { diff --git a/src/Core.php b/src/Core.php index f8840fa80..51e6f024b 100644 --- a/src/Core.php +++ b/src/Core.php @@ -624,7 +624,7 @@ protected static function _validateIdOrTag($string) if (substr($string, 0, 9) == 'internal-') { Zend_Cache::throwException('"internal-*" ids or tags are reserved'); } - if (!preg_match('~^[\w]+$~D', $string)) { + if (!preg_match('~^[a-zA-Z0-9_]+$~D', $string)) { Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]"); } } From a702c3c3fad43f8b0dc6a6cab7504f5e706c41de Mon Sep 17 00:00:00 2001 From: mabe Date: Sun, 28 Feb 2010 02:43:13 +0000 Subject: [PATCH 059/311] cache tests: don't call clean on a non existing instance on tearDown git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21222 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/CommonBackendTest.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php index 65b73468c..eff11bade 100644 --- a/test/CommonBackendTest.php +++ b/test/CommonBackendTest.php @@ -98,7 +98,9 @@ public function getTmpDir($date = true) public function tearDown() { - $this->_instance->clean(); + if ($this->_instance) { + $this->_instance->clean(); + } $this->rmdir(); } From 350feca0761a8381c782a238322d688fa2983ede Mon Sep 17 00:00:00 2001 From: mabe Date: Mon, 1 Mar 2010 13:40:11 +0000 Subject: [PATCH 060/311] ZF-7600: Zend_Cache_Core::getIds* have to strip cache_id_prefix git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21279 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Test.php | 143 ++++++++++++++++++++++++++++++++++++++++++- src/Core.php | 71 +++++++++++++++++---- test/CoreTest.php | 32 ++++++++++ 3 files changed, 231 insertions(+), 15 deletions(-) diff --git a/src/Backend/Test.php b/src/Backend/Test.php index 412a6d6af..cb2493d0d 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -24,7 +24,7 @@ /** * @see Zend_Cache_Backend_Interface */ -require_once 'Zend/Cache/Backend/Interface.php'; +require_once 'Zend/Cache/Backend/ExtendedInterface.php'; /** * @see Zend_Cache_Backend @@ -37,7 +37,7 @@ * @copyright Copyright (c) 2005-2010 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_Interface +class Zend_Cache_Backend_Test extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface { /** * Available options @@ -252,6 +252,145 @@ 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 * diff --git a/src/Core.php b/src/Core.php index 51e6f024b..97ee372a2 100644 --- a/src/Core.php +++ b/src/Core.php @@ -477,7 +477,21 @@ public function getIdsMatchingTags($tags = array()) if (!($this->_backendCapabilities['tags'])) { Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } - return $this->_backend->getIdsMatchingTags($tags); + + $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, $this->_options['cache_id_prefix']) === 0) { + $id = substr($id, $prefixLen); + } + } + } + + return $ids; } /** @@ -496,7 +510,21 @@ public function getIdsNotMatchingTags($tags = array()) if (!($this->_backendCapabilities['tags'])) { Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } - return $this->_backend->getIdsNotMatchingTags($tags); + + $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, $this->_options['cache_id_prefix']) === 0) { + $id = substr($id, $prefixLen); + } + } + } + + return $ids; } /** @@ -515,7 +543,21 @@ public function getIdsMatchingAnyTags($tags = array()) if (!($this->_backendCapabilities['tags'])) { Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } - return $this->_backend->getIdsMatchingAnyTags($tags); + + $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, $this->_options['cache_id_prefix']) === 0) { + $id = substr($id, $prefixLen); + } + } + } + + return $ids; } /** @@ -528,18 +570,21 @@ public function getIds() if (!$this->_extendedBackend) { Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } - $array = $this->_backend->getIds(); - if ((!isset($this->_options['cache_id_prefix'])) || ($this->_options['cache_id_prefix'] == '')) return $array; - // we need to remove cache_id_prefix from ids (see #ZF-6178) - $res = array(); - while (list(,$id) = each($array)) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { - $res[] = preg_replace("~^{$this->_options['cache_id_prefix']}~", '', $id); - } else { - $res[] = $id; + + $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, $this->_options['cache_id_prefix']) === 0) { + $id = substr($id, $prefixLen); + } } } - return $res; + + return $ids; } /** diff --git a/test/CoreTest.php b/test/CoreTest.php index 65ed671cd..c46656e67 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -490,4 +490,36 @@ public function testCleanCorrectCall() $this->assertEquals($expected, $log); } + public function testGetIds() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIds(); + $this->assertContains('id1', $ids); + $this->assertContains('id2', $ids); + } + + public function testGetIdsMatchingTags() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIdsMatchingTags(array('tag1', 'tag2')); + $this->assertContains('id1', $ids); + $this->assertContains('id2', $ids); + } + + public function testGetIdsNotMatchingTags() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIdsNotMatchingTags(array('tag3', 'tag4')); + $this->assertContains('id3', $ids); + $this->assertContains('id4', $ids); + } + + public function testGetIdsMatchingAnyTags() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIdsMatchingAnyTags(array('tag5', 'tag6')); + $this->assertContains('id5', $ids); + $this->assertContains('id6', $ids); + } + } From 5deee4968630be45d5bd58545f38c2410592c7c6 Mon Sep 17 00:00:00 2001 From: mabe Date: Mon, 1 Mar 2010 13:47:54 +0000 Subject: [PATCH 061/311] ZF-7600: small speed up: use $prefix instead of $this->_options['cache_id_prefix'] git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21280 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Core.php b/src/Core.php index 97ee372a2..7555c3b71 100644 --- a/src/Core.php +++ b/src/Core.php @@ -485,7 +485,7 @@ public function getIdsMatchingTags($tags = array()) $prefix = & $this->_options['cache_id_prefix']; $prefixLen = strlen($prefix); foreach ($ids as &$id) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { + if (strpos($id, $prefix) === 0) { $id = substr($id, $prefixLen); } } @@ -518,7 +518,7 @@ public function getIdsNotMatchingTags($tags = array()) $prefix = & $this->_options['cache_id_prefix']; $prefixLen = strlen($prefix); foreach ($ids as &$id) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { + if (strpos($id, $prefix) === 0) { $id = substr($id, $prefixLen); } } @@ -551,7 +551,7 @@ public function getIdsMatchingAnyTags($tags = array()) $prefix = & $this->_options['cache_id_prefix']; $prefixLen = strlen($prefix); foreach ($ids as &$id) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { + if (strpos($id, $prefix) === 0) { $id = substr($id, $prefixLen); } } @@ -578,7 +578,7 @@ public function getIds() $prefix = & $this->_options['cache_id_prefix']; $prefixLen = strlen($prefix); foreach ($ids as &$id) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { + if (strpos($id, $prefix) === 0) { $id = substr($id, $prefixLen); } } From c8006519349ebd12bba0171cef14ca2b3ded9e4d Mon Sep 17 00:00:00 2001 From: matthew Date: Wed, 3 Mar 2010 20:46:05 +0000 Subject: [PATCH 062/311] [2.0] Stripped require_once calls (skipping Zend_Gdata, Zend_Pdf, Zend_Search, and Zend_Service components) git-svn-id: http://framework.zend.com/svn/framework/standard/branches/development-2.0@21309 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend.php | 5 +++-- src/Backend/Apc.php | 15 +++------------ src/Backend/BlackHole.php | 13 +++---------- src/Backend/ExtendedInterface.php | 6 +----- src/Backend/File.php | 14 +++----------- src/Backend/Memcached.php | 15 +++------------ src/Backend/Sqlite.php | 14 +++----------- src/Backend/Static.php | 13 +++---------- src/Backend/Test.php | 14 +++----------- src/Backend/TwoLevels.php | 16 +++------------- src/Backend/Xcache.php | 15 +++------------ src/Backend/ZendPlatform.php | 14 +++----------- src/Backend/ZendServer.php | 11 +++-------- src/Backend/ZendServer/Disk.php | 11 +++-------- src/Backend/ZendServer/ShMem.php | 11 +++-------- src/Core.php | 4 +++- src/Exception.php | 6 +----- src/Frontend/Capture.php | 8 +------- src/Frontend/Class.php | 7 +------ src/Frontend/File.php | 8 +------- src/Frontend/Function.php | 8 +------- src/Frontend/Output.php | 8 +------- src/Frontend/Page.php | 8 +------- src/Manager.php | 10 ++-------- 24 files changed, 55 insertions(+), 199 deletions(-) diff --git a/src/Backend.php b/src/Backend.php index a0c633174..a3c67464a 100644 --- a/src/Backend.php +++ b/src/Backend.php @@ -22,6 +22,9 @@ /** + * @uses Zend_Cache + * @uses Zend_Log + * @uses Zend_Log_Writer_Stream * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) @@ -235,8 +238,6 @@ protected function _loggerSanity() } // Create a default logger to the standard output stream - require_once 'Zend/Log.php'; - require_once 'Zend/Log/Writer/Stream.php'; $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); $this->_directives['logger'] = $logger; } diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php index 885a756ab..157fb003f 100644 --- a/src/Backend/Apc.php +++ b/src/Backend/Apc.php @@ -20,19 +20,10 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/ExtendedInterface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/BlackHole.php b/src/Backend/BlackHole.php index 066bba28c..1e4f14fe1 100644 --- a/src/Backend/BlackHole.php +++ b/src/Backend/BlackHole.php @@ -21,16 +21,9 @@ */ /** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/ExtendedInterface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - -/** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php index b48be4d13..763adb9a1 100644 --- a/src/Backend/ExtendedInterface.php +++ b/src/Backend/ExtendedInterface.php @@ -21,11 +21,7 @@ */ /** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/Interface.php'; - -/** + * @uses Zend_Cache_Backend_Interface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/File.php b/src/Backend/File.php index e67ea6918..e8fe5eb11 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -21,17 +21,9 @@ */ /** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/ExtendedInterface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - - -/** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_ExtendedInterfaceInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 21f28c928..a9a24351b 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -20,19 +20,10 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/ExtendedInterface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index 46f9116f3..8280fc13d 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -20,18 +20,10 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/ExtendedInterface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 7bcd97ab2..d32a61bfd 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -21,16 +21,9 @@ */ /** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/Interface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - -/** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_Interface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/Test.php b/src/Backend/Test.php index 412a6d6af..79c977a21 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -20,18 +20,10 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/Interface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_Interface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 74b3278c7..9512ca4f8 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -20,25 +20,15 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Backend_ExtendedInterface - */ -require_once 'Zend/Cache/Backend/ExtendedInterface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 { /** diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php index 664d45b69..76b113c74 100644 --- a/src/Backend/Xcache.php +++ b/src/Backend/Xcache.php @@ -20,19 +20,10 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Backend_Interface - */ -require_once 'Zend/Cache/Backend/Interface.php'; - -/** - * @see Zend_Cache_Backend - */ -require_once 'Zend/Cache/Backend.php'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_Interface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/ZendPlatform.php b/src/Backend/ZendPlatform.php index e6146bb62..7228253e3 100644 --- a/src/Backend/ZendPlatform.php +++ b/src/Backend/ZendPlatform.php @@ -20,20 +20,12 @@ * @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) * + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_Interface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer.php index ead7de7db..1d1f6942f 100755 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer.php @@ -20,15 +20,10 @@ * @version $Id$ */ - -/** @see Zend_Cache_Backend_Interface */ -require_once 'Zend/Cache/Backend/Interface.php'; - -/** @see Zend_Cache_Backend */ -require_once 'Zend/Cache/Backend.php'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend + * @uses Zend_Cache_Backend_Interface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php index 6c6f67d7c..92ea0ecdf 100755 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -20,15 +20,10 @@ * @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'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend_Interface + * @uses Zend_Cache_Backend_ZendServer * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php index f21b3a38e..15ac4f71d 100755 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -20,15 +20,10 @@ * @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'; - - /** + * @uses Zend_Cache + * @uses Zend_Cache_Backend_Interface + * @uses Zend_Cache_Backend_ZendServer * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Core.php b/src/Core.php index f8840fa80..743d3d5e7 100644 --- a/src/Core.php +++ b/src/Core.php @@ -21,6 +21,9 @@ /** + * @uses Zend_Cache + * @uses Zend_Log + * @uses Zend_Log_Writer_Stream * @package Zend_Cache * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License @@ -668,7 +671,6 @@ protected function _loggerSanity() } // Create a default logger to the standard output stream - require_once 'Zend/Log/Writer/Stream.php'; $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); $this->_options['logger'] = $logger; } diff --git a/src/Exception.php b/src/Exception.php index e6cf9f3c0..a67b765da 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -20,11 +20,7 @@ */ /** - * @see Zend_Exception - */ -require_once 'Zend/Exception.php'; - -/** + * @uses Zend_Exception * @package Zend_Cache * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index 3da6a5bda..7fb88a5af 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -20,14 +20,8 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Core - */ -require_once 'Zend/Cache/Core.php'; - - /** + * @uses Zend_Cache_Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index e4aef9452..8449fa648 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -21,12 +21,7 @@ */ /** - * @see Zend_Cache_Core - */ -require_once 'Zend/Cache/Core.php'; - - -/** + * @uses Zend_Cache_Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Frontend/File.php b/src/Frontend/File.php index eccb1eeb4..0b0f6ee2e 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -20,14 +20,8 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Core - */ -require_once 'Zend/Cache/Core.php'; - - /** + * @uses Zend_Cache_Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index 337623f86..5d93902c4 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -20,14 +20,8 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Core - */ -require_once 'Zend/Cache/Core.php'; - - /** + * @uses Zend_Cache_Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Frontend/Output.php b/src/Frontend/Output.php index 2c253a9f5..7111cc6f7 100644 --- a/src/Frontend/Output.php +++ b/src/Frontend/Output.php @@ -20,14 +20,8 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Core - */ -require_once 'Zend/Cache/Core.php'; - - /** + * @uses Zend_Cache_Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index bf6046ea1..8c5bf0cd3 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -20,14 +20,8 @@ * @version $Id$ */ - -/** - * @see Zend_Cache_Core - */ -require_once 'Zend/Cache/Core.php'; - - /** + * @uses Zend_Cache_Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) diff --git a/src/Manager.php b/src/Manager.php index a409a2b81..391b023b6 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -19,13 +19,9 @@ * @version $Id$ */ -/** @see Zend_Cache_Exception */ -require_once 'Zend/Cache/Exception.php'; - -/** @see Zend_Cache */ -require_once 'Zend/Cache.php'; - /** + * @uses Zend_Cache + * @uses Zend_Cache_Exception * @category Zend * @package Zend_Cache * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) @@ -190,7 +186,6 @@ 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'); } @@ -240,7 +235,6 @@ 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'); } From e3aeb7c4e9c08b0ebae41092ca14f2a6ac5be2cd Mon Sep 17 00:00:00 2001 From: matthew Date: Mon, 8 Mar 2010 20:36:57 +0000 Subject: [PATCH 063/311] [2.0] Updated test suite - Created phpunit.xml - Renamed TestHelper.php Bootstrap.php; latter now referenced in phpunit.xml - Uses autoloading - Stripped require_once calls globally (will need to run individual groups iteratively to determine if any test caes are missing necessary calls) - Controller tests now run (but 4 new errors) git-svn-id: http://framework.zend.com/svn/framework/standard/branches/development-2.0@21390 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/AllTests.php | 205 ----------------------------- test/ApcBackendTest.php | 4 - test/ClassFrontendTest.php | 4 - test/CommonBackendTest.php | 2 - test/CommonExtendedBackendTest.php | 3 - test/CoreTest.php | 6 - test/FactoryException.php | 2 - test/FactoryTest.php | 4 - test/FileBackendTest.php | 6 - test/FileFrontendTest.php | 4 - test/FunctionFrontendTest.php | 4 - test/ManagerTest.php | 3 - test/MemcachedBackendTest.php | 4 - test/OutputFrontendTest.php | 4 - test/PageFrontendTest.php | 4 - test/SkipTests.php | 2 - test/SqliteBackendTest.php | 4 - test/StaticBackendTest.php | 6 - test/TwoLevelsBackendTest.php | 4 - test/XcacheBackendTest.php | 4 - test/ZendPlatformBackendTest.php | 4 - test/ZendServerDiskTest.php | 4 - test/ZendServerShMemTest.php | 4 - 23 files changed, 291 deletions(-) delete mode 100644 test/AllTests.php diff --git a/test/AllTests.php b/test/AllTests.php deleted file mode 100644 index 51f597c46..000000000 --- a/test/AllTests.php +++ /dev/null @@ -1,205 +0,0 @@ -addTestSuite('Zend_Cache_FactoryTest'); - $suite->addTestSuite('Zend_Cache_CoreTest'); - $suite->addTestSuite('Zend_Cache_FileBackendTest'); - $suite->addTestSuite('Zend_Cache_OutputFrontendTest'); - $suite->addTestSuite('Zend_Cache_FunctionFrontendTest'); - $suite->addTestSuite('Zend_Cache_ClassFrontendTest'); - $suite->addTestSuite('Zend_Cache_FileFrontendTest'); - $suite->addTestSuite('Zend_Cache_PageFrontendTest'); - - /* - * Check if SQLite tests are enabled, and if extension and driver are available. - */ - if (!defined('TESTS_ZEND_CACHE_SQLITE_ENABLED') || - constant('TESTS_ZEND_CACHE_SQLITE_ENABLED') === false) { - $skipTest = new Zend_Cache_SqliteBackendTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!extension_loaded('sqlite')) { - $skipTest = new Zend_Cache_SqliteBackendTest_SkipTests(); - $skipTest->message = "Extension 'sqlite' is not loaded"; - $suite->addTest($skipTest); - } else { - $suite->addTestSuite('Zend_Cache_SqliteBackendTest'); - } - - /* - * Check if APC tests are enabled, and if extension is available. - */ - if (!defined('TESTS_ZEND_CACHE_APC_ENABLED') || - constant('TESTS_ZEND_CACHE_APC_ENABLED') === false) { - $skipTest = new Zend_Cache_ApcBackendTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!extension_loaded('apc')) { - $skipTest = new Zend_Cache_ApcBackendTest_SkipTests(); - $skipTest->message = "Extension 'APC' is not loaded"; - $suite->addTest($skipTest); - } else { - $suite->addTestSuite('Zend_Cache_ApcBackendTest'); - } - - /* - * Check if Xcache tests are enabled, and if extension is available. - */ - if (!defined('TESTS_ZEND_CACHE_XCACHE_ENABLED') || - constant('TESTS_ZEND_CACHE_XCACHE_ENABLED') === false) { - $skipTest = new Zend_Cache_XCacheBackendTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!extension_loaded('xcache')) { - $skipTest = new Zend_Cache_XCacheBackendTest_SkipTests(); - $skipTest->message = "Extension 'XCache' is not loaded"; - $suite->addTest($skipTest); - } else { - $suite->addTestSuite('Zend_Cache_XCacheBackendTest'); - } - - /* - * Check if Memcached tests are enabled, and if extension is available. - */ - if (!defined('TESTS_ZEND_CACHE_MEMCACHED_ENABLED') || - constant('TESTS_ZEND_CACHE_MEMCACHED_ENABLED') === false) { - $skipTest = new Zend_Cache_MemcachedBackendTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!extension_loaded('memcache')) { - $skipTest = new Zend_Cache_MemcachedBackendTest_SkipTests(); - $skipTest->message = "Extension 'APC' is not loaded"; - $suite->addTest($skipTest); - } else { - if (!defined('TESTS_ZEND_CACHE_MEMCACHED_HOST')) { - define('TESTS_ZEND_CACHE_MEMCACHED_HOST', '127.0.0.1'); - } - if (!defined('TESTS_ZEND_CACHE_MEMCACHED_PORT')) { - define('TESTS_ZEND_CACHE_MEMCACHED_PORT', 11211); - } - if (!defined('TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT')) { - define('TESTS_ZEND_CACHE_MEMCACHED_PERSISTENT', true); - } - $suite->addTestSuite('Zend_Cache_MemcachedBackendTest'); - } - - /* - * Check if Zend Platform tests are enabled, and if extension is available. - */ - if (!defined('TESTS_ZEND_CACHE_PLATFORM_ENABLED') || - constant('TESTS_ZEND_CACHE_PLATFORM_ENABLED') === false) { - $skipTest = new Zend_Cache_ZendPlatformBackendTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!function_exists('accelerator_license_info')) { - $skipTest = new Zend_Cache_ZendPlatformBackendTest_SkipTests(); - $skipTest->message = 'Extension for Zend Platform is not loaded'; - $suite->addTest($skipTest); - } else { - $suite->addTestSuite('Zend_Cache_ZendPlatformBackendTest'); - } - - /* - * Check if APC tests are enabled, and if extension is available. - */ - if (!defined('TESTS_ZEND_CACHE_APC_ENABLED') || - constant('TESTS_ZEND_CACHE_APC_ENABLED') === false) { - $skipTest = new Zend_Cache_TwoLevelsBackendTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!extension_loaded('apc')) { - $skipTest = new Zend_Cache_TwoLevelsBackendTest_SkipTests(); - $skipTest->message = "Extension 'APC' is not loaded"; - $suite->addTest($skipTest); - } else { - $suite->addTestSuite('Zend_Cache_TwoLevelsBackendTest'); - } - - /* - * Check if Zend Server tests are enabled, and appropriate functions are available. - */ - if (!defined('TESTS_ZEND_CACHE_ZENDSERVER_ENABLED') || - constant('TESTS_ZEND_CACHE_ZENDSERVER_ENABLED') === false) { - $skipTest = new Zend_Cache_ZendServerTest_SkipTests(); - $skipTest->message = 'Tests are not enabled in TestConfiguration.php'; - $suite->addTest($skipTest); - } else if (!function_exists('zend_shm_cache_store')) { - $skipTest = new Zend_Cache_ZendServerTest_SkipTests(); - $skipTest->message = "Zend Server caching environment is not available"; - $suite->addTest($skipTest); - } else { - $suite->addTestSuite('Zend_Cache_ZendServerDiskTest'); - $suite->addTestSuite('Zend_Cache_ZendServerShMemTest'); - } - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'Zend_Cache_AllTests::main') { - Zend_Cache_AllTests::main(); -} diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php index e3bb859f5..047d1b548 100644 --- a/test/ApcBackendTest.php +++ b/test/ApcBackendTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/Apc.php'; /** * Common tests for backends */ -require_once 'CommonExtendedBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/ClassFrontendTest.php b/test/ClassFrontendTest.php index b286fb881..604ea6087 100644 --- a/test/ClassFrontendTest.php +++ b/test/ClassFrontendTest.php @@ -23,14 +23,10 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Frontend/Class.php'; -require_once 'Zend/Cache/Backend/Test.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @todo: Should this class be named Zend_Cache_Something? diff --git a/test/CommonBackendTest.php b/test/CommonBackendTest.php index 65b73468c..a4cb7ed47 100644 --- a/test/CommonBackendTest.php +++ b/test/CommonBackendTest.php @@ -20,14 +20,12 @@ * @version $Id$ */ -require_once 'PHPUnit/Util/Filter.php'; PHPUnit_Util_Filter::addFileToFilter(__FILE__); /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/CommonExtendedBackendTest.php b/test/CommonExtendedBackendTest.php index 3c7fcfada..35fbe791f 100644 --- a/test/CommonExtendedBackendTest.php +++ b/test/CommonExtendedBackendTest.php @@ -20,19 +20,16 @@ * @version $Id$ */ -require_once 'PHPUnit/Util/Filter.php'; PHPUnit_Util_Filter::addFileToFilter(__FILE__); /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @see Zend_Cache_CommonBackendTest */ -require_once 'CommonBackendTest.php'; /** * @category Zend diff --git a/test/CoreTest.php b/test/CoreTest.php index 65ed671cd..1c9ac9a37 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -23,17 +23,11 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Core.php'; -require_once 'Zend/Cache/Backend/File.php'; // TODO : use only Test backend ? -require_once 'Zend/Cache/Backend/Test.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; -require_once 'Zend/Config.php'; /** * @category Zend diff --git a/test/FactoryException.php b/test/FactoryException.php index e049f5a5e..a00255a3f 100644 --- a/test/FactoryException.php +++ b/test/FactoryException.php @@ -20,8 +20,6 @@ * @version $Id$ */ -require_once 'PHPUnit/Extensions/ExceptionTestCase.php'; -require_once 'Zend/Cache.php'; /** * @category Zend diff --git a/test/FactoryTest.php b/test/FactoryTest.php index 810c7ab73..9484e9d12 100644 --- a/test/FactoryTest.php +++ b/test/FactoryTest.php @@ -23,19 +23,15 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; -require_once 'Zend/Cache/Backend/File.php'; class Zend_Cache_Backend_FooBarTest extends Zend_Cache_Backend_File { } class FooBarTestBackend extends Zend_Cache_Backend_File { } -require_once 'Zend/Cache/Core.php'; class Zend_Cache_Frontend_FooBarTest extends Zend_Cache_Core { } class FooBarTestFrontend extends Zend_Cache_Core { } diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php index 4168573bb..b4d795e99 100644 --- a/test/FileBackendTest.php +++ b/test/FileBackendTest.php @@ -23,24 +23,18 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/File.php'; /** * Zend_Log */ -require_once 'Zend/Log.php'; -require_once 'Zend/Log/Writer/Null.php'; /** * Common tests for backends */ -require_once 'CommonExtendedBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php index 5cdab99e3..300b30f54 100644 --- a/test/FileFrontendTest.php +++ b/test/FileFrontendTest.php @@ -23,14 +23,10 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Frontend/File.php'; -require_once 'Zend/Cache/Backend/Test.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index c7953a79b..3648851de 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -23,14 +23,10 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Frontend/Function.php'; -require_once 'Zend/Cache/Backend/Test.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; function foobar($param1, $param2) { echo "foobar_output($param1, $param2)"; diff --git a/test/ManagerTest.php b/test/ManagerTest.php index 9a9170322..b277808a6 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -19,9 +19,6 @@ * @version $Id$ */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Manager.php'; -require_once 'Zend/Config.php'; /** * @category Zend_Cache diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 72bfb4289..f19aef4cf 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/Memcached.php'; /** * Common tests for backends */ -require_once 'CommonExtendedBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/OutputFrontendTest.php b/test/OutputFrontendTest.php index aaf67b1f2..71b96de83 100644 --- a/test/OutputFrontendTest.php +++ b/test/OutputFrontendTest.php @@ -23,14 +23,10 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Frontend/Output.php'; -require_once 'Zend/Cache/Backend/Test.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php index d5433a8f3..25eb37676 100644 --- a/test/PageFrontendTest.php +++ b/test/PageFrontendTest.php @@ -23,14 +23,10 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Frontend/Page.php'; -require_once 'Zend/Cache/Backend/Test.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/SkipTests.php b/test/SkipTests.php index 296498321..44d04175f 100644 --- a/test/SkipTests.php +++ b/test/SkipTests.php @@ -23,9 +23,7 @@ /** * PHPUnit_Framework_TestCase */ -require_once 'PHPUnit/Framework/TestCase.php'; -require_once 'PHPUnit/Util/Filter.php'; PHPUnit_Util_Filter::addFileToFilter(__FILE__); diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php index 437080576..e18f690ad 100644 --- a/test/SqliteBackendTest.php +++ b/test/SqliteBackendTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/Sqlite.php'; /** * Common tests for backends */ -require_once 'CommonExtendedBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index c46cf8660..5e51c4905 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -7,24 +7,18 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/Static.php'; /** * Zend_Log */ -require_once 'Zend/Log.php'; -require_once 'Zend/Log/Writer/Null.php'; /** * Common tests for backends */ -require_once 'CommonBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @package Zend_Cache diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php index 9eed99916..373ff542e 100644 --- a/test/TwoLevelsBackendTest.php +++ b/test/TwoLevelsBackendTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/TwoLevels.php'; /** * Common tests for backends */ -require_once 'CommonExtendedBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/XcacheBackendTest.php b/test/XcacheBackendTest.php index 8a008972b..af8832206 100644 --- a/test/XcacheBackendTest.php +++ b/test/XcacheBackendTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/Xcache.php'; /** * Common tests for backends */ -require_once 'CommonBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/ZendPlatformBackendTest.php b/test/ZendPlatformBackendTest.php index b69f6312f..fdfb43d4e 100644 --- a/test/ZendPlatformBackendTest.php +++ b/test/ZendPlatformBackendTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/ZendPlatform.php'; /** * Common tests for backends */ -require_once 'CommonBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index e46fb4617..9f94b08e7 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/ZendServer/Disk.php'; /** * Common tests for backends */ -require_once 'CommonBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php index b888e5fcf..7c6760dc3 100755 --- a/test/ZendServerShMemTest.php +++ b/test/ZendServerShMemTest.php @@ -23,18 +23,14 @@ /** * Zend_Cache */ -require_once 'Zend/Cache.php'; -require_once 'Zend/Cache/Backend/ZendServer/ShMem.php'; /** * Common tests for backends */ -require_once 'CommonBackendTest.php'; /** * PHPUnit test case */ -require_once 'PHPUnit/Framework/TestCase.php'; /** * @category Zend From 07d60132ffd81d1bc654a2dfb6d1ba5ebe1616eb Mon Sep 17 00:00:00 2001 From: matthew Date: Tue, 9 Mar 2010 17:57:29 +0000 Subject: [PATCH 064/311] [2.0] Zend_Cache tests now pass git-svn-id: http://framework.zend.com/svn/framework/standard/branches/development-2.0@21415 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 1 - src/Manager.php | 2 +- test/ApcBackendTest.php | 18 ++++----------- test/FileBackendTest.php | 19 ++------------- test/ManagerTest.php | 23 ++++++++++--------- test/MemcachedBackendTest.php | 18 ++++----------- test/SqliteBackendTest.php | 15 ++---------- test/StaticBackendTest.php | 19 ++------------- ...nBackendTest.php => TestCommonBackend.php} | 7 ++++-- ...Test.php => TestCommonExtendedBackend.php} | 11 ++------- test/TwoLevelsBackendTest.php | 18 ++++----------- test/XcacheBackendTest.php | 18 ++++----------- test/ZendPlatformBackendTest.php | 15 ++---------- test/ZendServerDiskTest.php | 18 ++++----------- test/ZendServerShMemTest.php | 18 ++++----------- 15 files changed, 58 insertions(+), 162 deletions(-) rename test/{CommonBackendTest.php => TestCommonBackend.php} (98%) rename test/{CommonExtendedBackendTest.php => TestCommonExtendedBackend.php} (97%) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index d32a61bfd..100b95660 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -226,7 +226,6 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) if ($extension) $ext = $extension; $file = rtrim($pathName, '/') . '/' . $fileName . $ext; if ($this->_options['file_locking']) { - file_put_contents('/var/www/data.dump', $file.$data); $result = file_put_contents($file, $data, LOCK_EX); } else { $result = file_put_contents($file, $data); diff --git a/src/Manager.php b/src/Manager.php index 391b023b6..e17e257d5 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -240,7 +240,7 @@ public function setTemplateOptions($name, $options) } if (!isset($this->_optionTemplates[$name])) { throw new Zend_Cache_Exception('A cache configuration template' - . 'does not exist with the name "' . $name . '"'); + . ' does not exist with the name "' . $name . '"'); } $this->_optionTemplates[$name] = $this->_mergeOptions($this->_optionTemplates[$name], $options); diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php index 047d1b548..b04cfad9b 100644 --- a/test/ApcBackendTest.php +++ b/test/ApcBackendTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ApcBackendTest extends Zend_Cache_CommonExtendedBackendTest { +class Zend_Cache_ApcBackendTest extends Zend_Cache_TestCommonExtendedBackend +{ protected $_instance; @@ -51,6 +40,9 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = true) { + if (!constant('TESTS_ZEND_CACHE_APC_ENABLED')) { + $this->markTestSkipped('Zend_Cache APC tests not enabled'); + } $this->_instance = new Zend_Cache_Backend_Apc(array()); parent::setUp($notag); } diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php index b4d795e99..94b6ffaa9 100644 --- a/test/FileBackendTest.php +++ b/test/FileBackendTest.php @@ -20,22 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Zend_Log - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -44,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_FileBackendTest extends Zend_Cache_CommonExtendedBackendTest { +class Zend_Cache_FileBackendTest extends Zend_Cache_TestCommonExtendedBackend +{ protected $_instance; protected $_instance2; diff --git a/test/ManagerTest.php b/test/ManagerTest.php index b277808a6..bcf9a8694 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -55,20 +55,21 @@ public function testSetsCacheObject() public function testLazyLoadsDefaultPageCache() { $manager = new Zend_Cache_Manager; - $manager->setTemplateOptions('tagCache',array( + $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir ) ) )); - $this->assertTrue($manager->getCache('page') instanceof Zend_Cache_Frontend_Output); + $cache = $manager->getCache('page'); + $this->assertTrue($cache instanceof Zend_Cache_Core); } public function testCanOverrideCacheFrontendNameConfiguration() { $manager = new Zend_Cache_Manager; - $manager->setTemplateOptions('tagCache',array( + $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir @@ -93,15 +94,15 @@ public function testCanMergeTemplateCacheOptionsFromZendConfig() ) ) )); - $manager->setTemplateOptions('tagCache', $config); - $options = $manager->getCacheTemplate('tagCache'); + $manager->setTemplateOptions('pagetag', $config); + $options = $manager->getCacheTemplate('pagetag'); $this->assertEquals($this->_cache_dir, $options['backend']['options']['cache_dir']); } public function testCanOverrideCacheBackendendNameConfiguration() { $manager = new Zend_Cache_Manager; - $manager->setTemplateOptions('tagCache',array( + $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir @@ -213,11 +214,11 @@ public function testConfigTemplatesDetectedAsAvailableCaches() public function testGettingPageCacheAlsoCreatesTagCache() { $manager = new Zend_Cache_Manager; - $tagCacheConfig = $manager->getCacheTemplate('tagCache'); - $tagCacheConfig['backend']['options']['cache_dir'] = $this->getTmpDir(); - $manager->setCacheTemplate('tagCache', $tagCacheConfig); - $tagCache = $manager->getCache('page')->getBackend()->getOption('tag_cache'); - $this->assertTrue($tagCache instanceof Zend_Cache_Core); + $pagetagConfig = $manager->getCacheTemplate('pagetag'); + $pagetagConfig['backend']['options']['cache_dir'] = $this->getTmpDir(); + $manager->setCacheTemplate('pagetag', $pagetagConfig); + $pagetag = $manager->getCache('page')->getBackend()->getOption('tag_cache'); + $this->assertTrue($pagetag instanceof Zend_Cache_Core); } // Helper Methods diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index f19aef4cf..29e24e9a5 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_MemcachedBackendTest extends Zend_Cache_CommonExtendedBackendTest { +class Zend_Cache_MemcachedBackendTest extends Zend_Cache_TestCommonExtendedBackend +{ protected $_instance; @@ -51,6 +40,9 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = true) { + if (!constant('TESTS_ZEND_CACHE_MEMCACHED_ENABLED')) { + $this->markTestSkipped('Zend_Cache memcache adapter tests are not enabled'); + } $serverValid = array( 'host' => TESTS_ZEND_CACHE_MEMCACHED_HOST, 'port' => TESTS_ZEND_CACHE_MEMCACHED_PORT, diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php index e18f690ad..ca05ce83b 100644 --- a/test/SqliteBackendTest.php +++ b/test/SqliteBackendTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_sqliteBackendTest extends Zend_Cache_CommonExtendedBackendTest { +class Zend_Cache_SqliteBackendTest extends Zend_Cache_TestCommonExtendedBackend +{ protected $_instance; private $_cache_dir; diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index 5e51c4905..bb76f2722 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -4,27 +4,12 @@ * @subpackage UnitTests */ -/** - * Zend_Cache - */ - -/** - * Zend_Log - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @package Zend_Cache * @subpackage UnitTests */ -class Zend_Cache_StaticBackendTest extends Zend_Cache_CommonBackendTest { +class Zend_Cache_StaticBackendTest extends Zend_Cache_TestCommonBackend +{ protected $_instance; protected $_instance2; diff --git a/test/CommonBackendTest.php b/test/TestCommonBackend.php similarity index 98% rename from test/CommonBackendTest.php rename to test/TestCommonBackend.php index a4cb7ed47..446f39428 100644 --- a/test/CommonBackendTest.php +++ b/test/TestCommonBackend.php @@ -35,7 +35,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -abstract class Zend_Cache_CommonBackendTest extends PHPUnit_Framework_TestCase { +abstract class Zend_Cache_TestCommonBackend extends PHPUnit_Framework_TestCase +{ protected $_instance; protected $_className; @@ -96,7 +97,9 @@ public function getTmpDir($date = true) public function tearDown() { - $this->_instance->clean(); + if ($this->_instance) { + $this->_instance->clean(); + } $this->rmdir(); } diff --git a/test/CommonExtendedBackendTest.php b/test/TestCommonExtendedBackend.php similarity index 97% rename from test/CommonExtendedBackendTest.php rename to test/TestCommonExtendedBackend.php index 35fbe791f..12d4eb653 100644 --- a/test/CommonExtendedBackendTest.php +++ b/test/TestCommonExtendedBackend.php @@ -23,14 +23,6 @@ PHPUnit_Util_Filter::addFileToFilter(__FILE__); -/** - * PHPUnit test case - */ - -/** - * @see Zend_Cache_CommonBackendTest - */ - /** * @category Zend * @package Zend_Cache @@ -39,7 +31,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_CommonExtendedBackendTest extends Zend_Cache_CommonBackendTest { +class Zend_Cache_TestCommonExtendedBackend extends Zend_Cache_TestCommonBackend +{ private $_capabilities; diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php index 373ff542e..bf1f4c7ed 100644 --- a/test/TwoLevelsBackendTest.php +++ b/test/TwoLevelsBackendTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_TwoLevelsBackendTest extends Zend_Cache_CommonExtendedBackendTest { +class Zend_Cache_TwoLevelsBackendTest extends Zend_Cache_TestCommonExtendedBackend +{ protected $_instance; private $_cache_dir; @@ -52,6 +41,9 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = false) { + if (!constant('TESTS_ZEND_CACHE_APC_ENABLED')) { + $this->markTestSkipped('Zend_Cache APC tests not enabled'); + } @mkdir($this->getTmpDir()); $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; $slowBackend = 'File'; diff --git a/test/XcacheBackendTest.php b/test/XcacheBackendTest.php index af8832206..bfb987b8d 100644 --- a/test/XcacheBackendTest.php +++ b/test/XcacheBackendTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_XcacheBackendTest extends Zend_Cache_CommonBackendTest { +class Zend_Cache_XcacheBackendTest extends Zend_Cache_TestCommonBackend +{ protected $_instance; @@ -51,6 +40,9 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = true) { + if (!constant('TESTS_ZEND_CACHE_XCACHE_ENABLED')) { + $this->markTestSkipped('Zend_Cache XCache tests not enabled'); + } $this->_instance = new Zend_Cache_Backend_Xcache(array( 'user' => TESTS_ZEND_CACHE_XCACHE_USER, 'password' => TESTS_ZEND_CACHE_XCACHE_PASSWORD diff --git a/test/ZendPlatformBackendTest.php b/test/ZendPlatformBackendTest.php index fdfb43d4e..3c8cddee8 100644 --- a/test/ZendPlatformBackendTest.php +++ b/test/ZendPlatformBackendTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ZendPlatformBackendTest extends Zend_Cache_CommonBackendTest { +class Zend_Cache_ZendPlatformBackendTest extends Zend_Cache_TestCommonBackend +{ protected $_instance; diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index 9f94b08e7..75d61069a 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ZendServerDiskTest extends Zend_Cache_CommonBackendTest { +class Zend_Cache_ZendServerDiskTest extends Zend_Cache_TestCommonBackend +{ protected $_instance; @@ -51,6 +40,9 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = true) { + if (!function_exists('zend_disk_cache_store')) { + $this->markTestSkipped('Zend_Cache Zend Server disk backend tests not enabled'); + } $this->_instance = new Zend_Cache_Backend_ZendServer_Disk(); parent::setUp(true); } diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php index 7c6760dc3..1732bb72a 100755 --- a/test/ZendServerShMemTest.php +++ b/test/ZendServerShMemTest.php @@ -20,18 +20,6 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * Common tests for backends - */ - -/** - * PHPUnit test case - */ - /** * @category Zend * @package Zend_Cache @@ -40,7 +28,8 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ZendServerShMemTest extends Zend_Cache_CommonBackendTest { +class Zend_Cache_ZendServerShMemTest extends Zend_Cache_TestCommonBackend +{ protected $_instance; @@ -51,6 +40,9 @@ public function __construct($name = null, array $data = array(), $dataName = '') public function setUp($notag = true) { + if (!function_exists('zend_shm_cache_store')) { + $this->markTestSkipped('Zend_Cache Zend Server ShMem backend tests not enabled'); + } $this->_instance = new Zend_Cache_Backend_ZendServer_ShMem(); parent::setUp(true); } From b1784747e0c5a66cf3942301f395e2f5b3323955 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 9 Mar 2010 19:23:54 +0000 Subject: [PATCH 065/311] ZF-9376: fixed php notice on delte using ext/memcache 3.x and memcached 1.4.4 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21420 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Memcached.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 21f28c928..d785410d7 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -238,7 +238,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) */ public function remove($id) { - return $this->_memcache->delete($id); + return $this->_memcache->delete($id, 0); } /** From f32d6630e6831f6f68641b8724f852d7352e65c6 Mon Sep 17 00:00:00 2001 From: matthew Date: Tue, 16 Mar 2010 12:38:39 +0000 Subject: [PATCH 066/311] [2.0] Merged in changes from trunk up to r21517 git-svn-id: http://framework.zend.com/svn/framework/standard/branches/development-2.0@21518 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 4 +- src/Backend/Memcached.php | 2 +- src/Backend/Test.php | 141 +++++++++++++++++++++++++++++++++++++- src/Core.php | 73 ++++++++++++++++---- test/CoreTest.php | 32 +++++++++ 5 files changed, 234 insertions(+), 18 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index e8fe5eb11..e23ad3dd6 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -115,8 +115,8 @@ public function __construct(array $options = array()) $this->setCacheDir(self::getTmpDir() . DIRECTORY_SEPARATOR, false); } if (isset($this->_options['file_name_prefix'])) { // particular case for this option - if (!preg_match('~^[\w]+$~', $this->_options['file_name_prefix'])) { - Zend_Cache::throwException('Invalid file_name_prefix : must use only [a-zA-A0-9_]'); + 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) { diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index a9a24351b..147b9cb4c 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -229,7 +229,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) */ public function remove($id) { - return $this->_memcache->delete($id); + return $this->_memcache->delete($id, 0); } /** diff --git a/src/Backend/Test.php b/src/Backend/Test.php index 79c977a21..dcaa46742 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -29,7 +29,7 @@ * @copyright Copyright (c) 2005-2010 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_Interface +class Zend_Cache_Backend_Test extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface { /** * Available options @@ -244,6 +244,145 @@ 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 * diff --git a/src/Core.php b/src/Core.php index 743d3d5e7..13e151934 100644 --- a/src/Core.php +++ b/src/Core.php @@ -480,7 +480,21 @@ public function getIdsMatchingTags($tags = array()) if (!($this->_backendCapabilities['tags'])) { Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } - return $this->_backend->getIdsMatchingTags($tags); + + $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; } /** @@ -499,7 +513,21 @@ public function getIdsNotMatchingTags($tags = array()) if (!($this->_backendCapabilities['tags'])) { Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } - return $this->_backend->getIdsNotMatchingTags($tags); + + $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; } /** @@ -518,7 +546,21 @@ public function getIdsMatchingAnyTags($tags = array()) if (!($this->_backendCapabilities['tags'])) { Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } - return $this->_backend->getIdsMatchingAnyTags($tags); + + $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; } /** @@ -531,18 +573,21 @@ public function getIds() if (!$this->_extendedBackend) { Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } - $array = $this->_backend->getIds(); - if ((!isset($this->_options['cache_id_prefix'])) || ($this->_options['cache_id_prefix'] == '')) return $array; - // we need to remove cache_id_prefix from ids (see #ZF-6178) - $res = array(); - while (list(,$id) = each($array)) { - if (strpos($id, $this->_options['cache_id_prefix']) === 0) { - $res[] = preg_replace("~^{$this->_options['cache_id_prefix']}~", '', $id); - } else { - $res[] = $id; + + $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 $res; + + return $ids; } /** @@ -627,7 +672,7 @@ protected static function _validateIdOrTag($string) if (substr($string, 0, 9) == 'internal-') { Zend_Cache::throwException('"internal-*" ids or tags are reserved'); } - if (!preg_match('~^[\w]+$~D', $string)) { + if (!preg_match('~^[a-zA-Z0-9_]+$~D', $string)) { Zend_Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]"); } } diff --git a/test/CoreTest.php b/test/CoreTest.php index 1c9ac9a37..03bb08618 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -484,4 +484,36 @@ public function testCleanCorrectCall() $this->assertEquals($expected, $log); } + public function testGetIds() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIds(); + $this->assertContains('id1', $ids); + $this->assertContains('id2', $ids); + } + + public function testGetIdsMatchingTags() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIdsMatchingTags(array('tag1', 'tag2')); + $this->assertContains('id1', $ids); + $this->assertContains('id2', $ids); + } + + public function testGetIdsNotMatchingTags() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIdsNotMatchingTags(array('tag3', 'tag4')); + $this->assertContains('id3', $ids); + $this->assertContains('id4', $ids); + } + + public function testGetIdsMatchingAnyTags() + { + $this->_instance->setOption('cache_id_prefix', 'prefix_'); + $ids = $this->_instance->getIdsMatchingAnyTags(array('tag5', 'tag6')); + $this->assertContains('id5', $ids); + $this->assertContains('id6', $ids); + } + } From a585ddd0fbf38b989b5c8fa6ec2ff0fd45574758 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 16 Mar 2010 17:46:38 +0000 Subject: [PATCH 067/311] ZF-9428: Empty Memcached throwed Exception on getFillingPercentage git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21519 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Memcached.php | 8 ++++---- test/CommonExtendedBackendTest.php | 11 +++++++++++ test/MemcachedBackendTest.php | 6 ++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index d785410d7..b66eb3266 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -381,10 +381,10 @@ public function getFillingPercentage() { $mems = $this->_memcache->getExtendedStats(); - $memSize = 0; - $memUsed = 0; + $memSize = null; + $memUsed = null; foreach ($mems as $key => $mem) { - if ($mem === false || !$mem['limit_maxbytes']) { + if ($mem === false) { $this->_log('can\'t get stat from ' . $key); continue; } @@ -399,7 +399,7 @@ public function getFillingPercentage() $memUsed += $eachUsed; } - if (!$memSize || !$memUsed) { + if ($memSize === null || $memUsed === null) { Zend_Cache::throwException('Can\'t get filling percentage'); } diff --git a/test/CommonExtendedBackendTest.php b/test/CommonExtendedBackendTest.php index 3c7fcfada..839026495 100644 --- a/test/CommonExtendedBackendTest.php +++ b/test/CommonExtendedBackendTest.php @@ -65,6 +65,17 @@ public function testGetFillingPercentage() $this->assertTrue($res <= 100); } + public function testGetFillingPercentageOnEmptyBackend() + { + $this->_instance->setDirectives(array('logging' => false)); // ??? + $this->_instance->clean(Zend_Cache::CLEANING_MODE_ALL); + $res = $this->_instance->getFillingPercentage(); + $this->_instance->setDirectives(array('logging' => true)); // ??? + $this->assertTrue(is_integer($res)); + $this->assertTrue($res >= 0); + $this->assertTrue($res <= 100); + } + public function testGetIds() { if (!($this->_capabilities['get_list'])) { diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 72bfb4289..7f8baacad 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -167,6 +167,12 @@ public function testGetFillingPercentage() parent::testGetFillingPercentage(); } + public function testGetFillingPercentageOnEmptyBackend() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testGetFillingPercentageOnEmptyBackend(); + } + } From d240f6926222e29b94206f8810b419e2313247b4 Mon Sep 17 00:00:00 2001 From: mabe Date: Wed, 24 Mar 2010 17:10:23 +0000 Subject: [PATCH 068/311] ZF-9506: error on list files if a directory can't list or glob returns false on empty directories git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21636 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index e20a3d3c1..3188dd500 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -647,6 +647,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $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; } foreach ($glob as $file) { @@ -739,7 +740,8 @@ protected function _get($dir, $mode, $tags = array()) $prefix = $this->_options['file_name_prefix']; $glob = @glob($dir . $prefix . '--*'); if ($glob === false) { - return true; + // On some systems it is impossible to distinguish between empty match and an error. + return array(); } foreach ($glob as $file) { if (is_file($file)) { @@ -802,7 +804,12 @@ protected function _get($dir, $mode, $tags = array()) } if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) { // Recursive call - $result = array_unique(array_merge($result, $this->_get($file . DIRECTORY_SEPARATOR, $mode, $tags))); + $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); From cbdb37e1c0ff2c1e4433c0343cd216cc1aa4abc7 Mon Sep 17 00:00:00 2001 From: matthew Date: Fri, 26 Mar 2010 14:57:23 +0000 Subject: [PATCH 069/311] [2.0] Updating to latest trunk git-svn-id: http://framework.zend.com/svn/framework/standard/branches/development-2.0@21654 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/File.php | 11 +++++++++-- src/Backend/Memcached.php | 8 ++++---- test/MemcachedBackendTest.php | 6 ++++++ test/TestCommonExtendedBackend.php | 11 +++++++++++ 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index e23ad3dd6..accd43098 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -639,6 +639,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $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; } foreach ($glob as $file) { @@ -731,7 +732,8 @@ protected function _get($dir, $mode, $tags = array()) $prefix = $this->_options['file_name_prefix']; $glob = @glob($dir . $prefix . '--*'); if ($glob === false) { - return true; + // On some systems it is impossible to distinguish between empty match and an error. + return array(); } foreach ($glob as $file) { if (is_file($file)) { @@ -794,7 +796,12 @@ protected function _get($dir, $mode, $tags = array()) } if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) { // Recursive call - $result = array_unique(array_merge($result, $this->_get($file . DIRECTORY_SEPARATOR, $mode, $tags))); + $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); diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 147b9cb4c..995b82de0 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -372,10 +372,10 @@ public function getFillingPercentage() { $mems = $this->_memcache->getExtendedStats(); - $memSize = 0; - $memUsed = 0; + $memSize = null; + $memUsed = null; foreach ($mems as $key => $mem) { - if ($mem === false || !$mem['limit_maxbytes']) { + if ($mem === false) { $this->_log('can\'t get stat from ' . $key); continue; } @@ -390,7 +390,7 @@ public function getFillingPercentage() $memUsed += $eachUsed; } - if (!$memSize || !$memUsed) { + if ($memSize === null || $memUsed === null) { Zend_Cache::throwException('Can\'t get filling percentage'); } diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 29e24e9a5..1d7bea895 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -155,6 +155,12 @@ public function testGetFillingPercentage() parent::testGetFillingPercentage(); } + public function testGetFillingPercentageOnEmptyBackend() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testGetFillingPercentageOnEmptyBackend(); + } + } diff --git a/test/TestCommonExtendedBackend.php b/test/TestCommonExtendedBackend.php index 12d4eb653..e6bf9d14e 100644 --- a/test/TestCommonExtendedBackend.php +++ b/test/TestCommonExtendedBackend.php @@ -55,6 +55,17 @@ public function testGetFillingPercentage() $this->assertTrue($res <= 100); } + public function testGetFillingPercentageOnEmptyBackend() + { + $this->_instance->setDirectives(array('logging' => false)); // ??? + $this->_instance->clean(Zend_Cache::CLEANING_MODE_ALL); + $res = $this->_instance->getFillingPercentage(); + $this->_instance->setDirectives(array('logging' => true)); // ??? + $this->assertTrue(is_integer($res)); + $this->assertTrue($res >= 0); + $this->assertTrue($res <= 100); + } + public function testGetIds() { if (!($this->_capabilities['get_list'])) { From 21bf1c459fd5cef56f9f545d852ef9926395554a Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 26 Mar 2010 11:02:25 -0400 Subject: [PATCH 070/311] Merged in latest changes to svn/development-2.0 branch --- src/Backend/File.php | 11 +++++++++-- src/Backend/Memcached.php | 8 ++++---- test/MemcachedBackendTest.php | 6 ++++++ test/TestCommonExtendedBackend.php | 11 +++++++++++ 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/Backend/File.php b/src/Backend/File.php index e23ad3dd6..accd43098 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -639,6 +639,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $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; } foreach ($glob as $file) { @@ -731,7 +732,8 @@ protected function _get($dir, $mode, $tags = array()) $prefix = $this->_options['file_name_prefix']; $glob = @glob($dir . $prefix . '--*'); if ($glob === false) { - return true; + // On some systems it is impossible to distinguish between empty match and an error. + return array(); } foreach ($glob as $file) { if (is_file($file)) { @@ -794,7 +796,12 @@ protected function _get($dir, $mode, $tags = array()) } if ((is_dir($file)) and ($this->_options['hashed_directory_level']>0)) { // Recursive call - $result = array_unique(array_merge($result, $this->_get($file . DIRECTORY_SEPARATOR, $mode, $tags))); + $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); diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 147b9cb4c..995b82de0 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -372,10 +372,10 @@ public function getFillingPercentage() { $mems = $this->_memcache->getExtendedStats(); - $memSize = 0; - $memUsed = 0; + $memSize = null; + $memUsed = null; foreach ($mems as $key => $mem) { - if ($mem === false || !$mem['limit_maxbytes']) { + if ($mem === false) { $this->_log('can\'t get stat from ' . $key); continue; } @@ -390,7 +390,7 @@ public function getFillingPercentage() $memUsed += $eachUsed; } - if (!$memSize || !$memUsed) { + if ($memSize === null || $memUsed === null) { Zend_Cache::throwException('Can\'t get filling percentage'); } diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 29e24e9a5..1d7bea895 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -155,6 +155,12 @@ public function testGetFillingPercentage() parent::testGetFillingPercentage(); } + public function testGetFillingPercentageOnEmptyBackend() + { + $this->_instance->setDirectives(array('logging' => false)); + parent::testGetFillingPercentageOnEmptyBackend(); + } + } diff --git a/test/TestCommonExtendedBackend.php b/test/TestCommonExtendedBackend.php index 12d4eb653..e6bf9d14e 100644 --- a/test/TestCommonExtendedBackend.php +++ b/test/TestCommonExtendedBackend.php @@ -55,6 +55,17 @@ public function testGetFillingPercentage() $this->assertTrue($res <= 100); } + public function testGetFillingPercentageOnEmptyBackend() + { + $this->_instance->setDirectives(array('logging' => false)); // ??? + $this->_instance->clean(Zend_Cache::CLEANING_MODE_ALL); + $res = $this->_instance->getFillingPercentage(); + $this->_instance->setDirectives(array('logging' => true)); // ??? + $this->assertTrue(is_integer($res)); + $this->assertTrue($res >= 0); + $this->assertTrue($res <= 100); + } + public function testGetIds() { if (!($this->_capabilities['get_list'])) { From e849bbce7bc8c11573ce2d9b16081025a9d8893b Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 26 Mar 2010 12:53:24 -0400 Subject: [PATCH 071/311] Added PHPTools submodule --- .gitmodules | 3 +++ tools/phptools | 1 + 2 files changed, 4 insertions(+) create mode 100644 .gitmodules create mode 160000 tools/phptools diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..21d57da59 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "tools/phptools"] + path = tools/phptools + url = git://github.com/ralphschindler/PHPTools.git diff --git a/tools/phptools b/tools/phptools new file mode 160000 index 000000000..685f0e09a --- /dev/null +++ b/tools/phptools @@ -0,0 +1 @@ +Subproject commit 685f0e09aabbc45d82d3836aefc82be1efddb513 From 0c96f2a4307a3c312a0bb44d7be2e4fe08d4b364 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 26 Mar 2010 13:49:44 -0400 Subject: [PATCH 072/311] Updated PHPTools --- tools/phptools | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/phptools b/tools/phptools index 685f0e09a..d232cb3e4 160000 --- a/tools/phptools +++ b/tools/phptools @@ -1 +1 @@ -Subproject commit 685f0e09aabbc45d82d3836aefc82be1efddb513 +Subproject commit d232cb3e4f1448daccefc74882da1862cda7656f From 182b701734feb4c480d0e3912c0390d6e7aa629a Mon Sep 17 00:00:00 2001 From: padraic Date: Mon, 29 Mar 2010 14:45:01 +0000 Subject: [PATCH 073/311] Removes debugging code remnant. Fixes ZF-9355 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21674 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 7bcd97ab2..030e832ae 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -233,7 +233,6 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) if ($extension) $ext = $extension; $file = rtrim($pathName, '/') . '/' . $fileName . $ext; if ($this->_options['file_locking']) { - file_put_contents('/var/www/data.dump', $file.$data); $result = file_put_contents($file, $data, LOCK_EX); } else { $result = file_put_contents($file, $data); From f374493619aac92e9da5bc7f5601711f15155a5d Mon Sep 17 00:00:00 2001 From: Ralph Schindler Date: Mon, 29 Mar 2010 12:11:42 -0500 Subject: [PATCH 074/311] Zend\Cache first pass of naming conversion Left to do: - Make tests work --- src/Backend/Apc.php | 38 +-- src/{ => Backend}/Backend.php | 46 ++-- .../{Interface.php => BackendInterface.php} | 9 +- src/Backend/BlackHole.php | 22 +- src/Backend/ExtendedInterface.php | 9 +- src/Backend/File.php | 54 ++-- src/Backend/Memcached.php | 42 +-- src/Backend/Sqlite.php | 46 ++-- src/Backend/{Static.php => StaticBackend.php} | 68 ++--- src/Backend/Test.php | 16 +- src/Backend/TwoLevels.php | 54 ++-- src/Backend/Xcache.php | 34 ++- src/Backend/ZendPlatform.php | 48 ++-- src/Backend/ZendServer/Disk.php | 17 +- src/Backend/ZendServer/ShMem.php | 17 +- src/Backend/{ => ZendServer}/ZendServer.php | 38 +-- src/Cache.php | 249 ++++++++++++++++++ src/Core.php | 116 ++++---- src/Exception.php | 9 +- src/Frontend/Capture.php | 11 +- src/Frontend/{Class.php => ClassFrontend.php} | 20 +- src/Frontend/File.php | 18 +- .../{Function.php => FunctionFrontend.php} | 16 +- src/Frontend/Output.php | 11 +- src/Frontend/Page.php | 28 +- src/Manager.php | 40 +-- test/ApcBackendTest.php | 11 +- test/ClassFrontendTest.php | 37 ++- test/CoreTest.php | 97 ++++--- test/FactoryException.php | 16 +- test/FactoryTest.php | 50 ++-- test/FileBackendTest.php | 19 +- test/FileFrontendTest.php | 47 ++-- test/FunctionFrontendTest.php | 32 +-- test/ManagerTest.php | 46 ++-- test/MemcachedBackendTest.php | 13 +- test/OutputFrontendTest.php | 16 +- test/PageFrontendTest.php | 45 ++-- test/SqliteBackendTest.php | 19 +- test/StaticBackendTest.php | 19 +- test/TestCommonBackend.php | 17 +- test/TestCommonExtendedBackend.php | 7 +- test/TwoLevelsBackendTest.php | 11 +- test/XcacheBackendTest.php | 11 +- test/ZendPlatformBackendTest.php | 11 +- test/ZendServerDiskTest.php | 11 +- test/ZendServerShMemTest.php | 11 +- 47 files changed, 1005 insertions(+), 617 deletions(-) rename src/{ => Backend}/Backend.php (83%) rename src/Backend/{Interface.php => BackendInterface.php} (95%) rename src/Backend/{Static.php => StaticBackend.php} (89%) mode change 100755 => 100644 src/Backend/ZendServer/Disk.php mode change 100755 => 100644 src/Backend/ZendServer/ShMem.php rename src/Backend/{ => ZendServer}/ZendServer.php (84%) mode change 100755 => 100644 create mode 100644 src/Cache.php rename src/Frontend/{Class.php => ClassFrontend.php} (93%) rename src/Frontend/{Function.php => FunctionFrontend.php} (92%) diff --git a/src/Backend/Apc.php b/src/Backend/Apc.php index 157fb003f..841c7e365 100644 --- a/src/Backend/Apc.php +++ b/src/Backend/Apc.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_ExtendedInterface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class Apc extends Backend implements ExtendedInterface { /** * Log message @@ -41,13 +47,13 @@ class Zend_Cache_Backend_Apc extends Zend_Cache_Backend implements Zend_Cache_Ba * Constructor * * @param array $options associative array of options - * @throws Zend_Cache_Exception + * @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 !'); + Cache\Cache::throwException('The apc extension must be loaded for using this backend !'); } parent::__construct($options); } @@ -130,25 +136,25 @@ public function remove($id) * * @param string $mode clean mode * @param array $tags array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: return apc_clear_cache('user'); break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\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: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_APC_BACKEND); break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } @@ -169,7 +175,7 @@ public function isAutomaticCleaningAvailable() /** * Return the filling percentage of the backend storage * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return int integer between 0 and 100 */ public function getFillingPercentage() @@ -179,7 +185,7 @@ public function getFillingPercentage() $memAvailable= $mem['avail_mem']; $memUsed = $memSize - $memAvailable; if ($memSize == 0) { - Zend_Cache::throwException('can\'t get apc memory size'); + Cache\Cache::throwException('can\'t get apc memory size'); } if ($memUsed > $memSize) { return 100; diff --git a/src/Backend.php b/src/Backend/Backend.php similarity index 83% rename from src/Backend.php rename to src/Backend/Backend.php index a3c67464a..18f76c319 100644 --- a/src/Backend.php +++ b/src/Backend/Backend.php @@ -20,17 +20,23 @@ * @version $Id$ */ +/** + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; +use Zend\Log; /** - * @uses Zend_Cache - * @uses Zend_Log - * @uses Zend_Log_Writer_Stream + * @uses \Zend\Cache\Cache + * @uses \Zend\Log\Logger + * @uses \Zend\Log\Writer\Stream * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Zend_Cache_Backend +class Backend { /** * Frontend or Core directives @@ -61,7 +67,7 @@ class Zend_Cache_Backend * Constructor * * @param array $options Associative array of options - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function __construct(array $options = array()) @@ -75,15 +81,15 @@ public function __construct(array $options = array()) * Set the frontend directives * * @param array $directives Assoc of directives - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setDirectives($directives) { - if (!is_array($directives)) Zend_Cache::throwException('Directives parameter must be an array'); + if (!is_array($directives)) Cache\Cache::throwException('Directives parameter must be an array'); while (list($name, $value) = each($directives)) { if (!is_string($name)) { - Zend_Cache::throwException("Incorrect option name : $name"); + Cache\Cache::throwException("Incorrect option name : $name"); } $name = strtolower($name); if (array_key_exists($name, $this->_directives)) { @@ -100,13 +106,13 @@ public function setDirectives($directives) * * @param string $name * @param mixed $value - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setOption($name, $value) { if (!is_string($name)) { - Zend_Cache::throwException("Incorrect option name : $name"); + Cache\Cache::throwException("Incorrect option name : $name"); } $name = strtolower($name); if (array_key_exists($name, $this->_options)) { @@ -150,7 +156,7 @@ public function isAutomaticCleaningAvailable() * inspired from Zend_File_Transfer_Adapter_Abstract * * @return string - * @throws Zend_Cache_Exception if unable to determine directory + * @throws \Zend\Cache\Exception if unable to determine directory */ public function getTmpDir() { @@ -197,7 +203,7 @@ public function getTmpDir() if ($this->_isGoodTmpDir('\\temp')) { return '\\temp'; } - Zend_Cache::throwException('Could not determine temp directory, please specify a cache_dir manually'); + Cache\Cache::throwException('Could not determine temp directory, please specify a cache_dir manually'); } /** @@ -221,7 +227,7 @@ protected function _isGoodTmpDir($dir) * is available. * Create a default log object if none is set. * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected function _loggerSanity() @@ -231,14 +237,14 @@ protected function _loggerSanity() } if (isset($this->_directives['logger'])) { - if ($this->_directives['logger'] instanceof Zend_Log) { + if ($this->_directives['logger'] instanceof Log\Logger) { return; } - Zend_Cache::throwException('Logger object is not an instance of Zend_Log class.'); + Cache\Cache::throwException('Logger object is not an instance of Zend_Log class.'); } // Create a default logger to the standard output stream - $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); + $logger = new Log\Logger(new Log\Writer\Stream('php://output')); $this->_directives['logger'] = $logger; } @@ -246,7 +252,7 @@ protected function _loggerSanity() * Log a message at the WARN (4) priority. * * @param string $message - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected function _log($message, $priority = 4) @@ -256,11 +262,11 @@ protected function _log($message, $priority = 4) } if (!isset($this->_directives['logger'])) { - Zend_Cache::throwException('Logging is enabled but logger is not set.'); + Cache\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.'); + if (!$logger instanceof Log\Logger) { + Cache\Cache::throwException('Logger object is not an instance of Zend_Log class.'); } $logger->log($message, $priority); } diff --git a/src/Backend/Interface.php b/src/Backend/BackendInterface.php similarity index 95% rename from src/Backend/Interface.php rename to src/Backend/BackendInterface.php index cee5cc539..8fe1e46f1 100644 --- a/src/Backend/Interface.php +++ b/src/Backend/BackendInterface.php @@ -20,6 +20,11 @@ * @version $Id$ */ +/** + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; /** * @package Zend_Cache @@ -27,7 +32,7 @@ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -interface Zend_Cache_Backend_Interface +interface BackendInterface { /** * Set the frontend directives @@ -94,6 +99,6 @@ public function remove($id); * @param array $tags Array of tags * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()); + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()); } diff --git a/src/Backend/BlackHole.php b/src/Backend/BlackHole.php index 1e4f14fe1..74fd9b45d 100644 --- a/src/Backend/BlackHole.php +++ b/src/Backend/BlackHole.php @@ -21,17 +21,23 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_ExtendedInterface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class BlackHole + extends Backend + implements ExtendedInterface { /** * Test if a cache is available for the given id and (if yes) return it (false else) @@ -101,7 +107,7 @@ public function remove($id) * @param tags array $tags array of tags * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { return true; } @@ -169,7 +175,7 @@ public function getIdsMatchingAnyTags($tags = array()) * Return the filling percentage of the backend storage * * @return int integer between 0 and 100 - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception */ public function getFillingPercentage() { diff --git a/src/Backend/ExtendedInterface.php b/src/Backend/ExtendedInterface.php index 763adb9a1..359f9fa2c 100644 --- a/src/Backend/ExtendedInterface.php +++ b/src/Backend/ExtendedInterface.php @@ -21,13 +21,18 @@ */ /** - * @uses Zend_Cache_Backend_Interface + * @namespace + */ +namespace Zend\Cache\Backend; + +/** + * @uses \Zend\Cache\Backend\BackendInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +interface ExtendedInterface extends BackendInterface { /** diff --git a/src/Backend/File.php b/src/Backend/File.php index accd43098..b16c4aa90 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend * @uses Zend_Cache_Backend_ExtendedInterfaceInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class File extends Backend implements ExtendedInterface { /** * Available options @@ -103,7 +109,7 @@ class Zend_Cache_Backend_File extends Zend_Cache_Backend implements Zend_Cache_B * Constructor * * @param array $options associative array of options - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function __construct(array $options = array()) @@ -116,11 +122,11 @@ public function __construct(array $options = array()) } 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_]'); + Cache\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'); + Cache\Cache::throwException('Invalid metadatas_array_max_size, must be > 10'); } if (isset($options['hashed_directory_umask']) && is_string($options['hashed_directory_umask'])) { // See #ZF-4422 @@ -137,16 +143,16 @@ public function __construct(array $options = array()) * * @param string $value * @param boolean $trailingSeparator If true, add a trailing separator is necessary - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setCacheDir($value, $trailingSeparator = true) { if (!is_dir($value)) { - Zend_Cache::throwException('cache_dir must be a directory'); + Cache\Cache::throwException('cache_dir must be a directory'); } if (!is_writable($value)) { - Zend_Cache::throwException('cache_dir is not writable'); + Cache\Cache::throwException('cache_dir is not writable'); } if ($trailingSeparator) { // add a trailing DIRECTORY_SEPARATOR if necessary @@ -273,7 +279,7 @@ public function remove($id) * @param tags array $tags array of tags * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { // We use this protected method to hide the recursive stuff clearstatcache(); @@ -342,7 +348,7 @@ public function getIdsMatchingAnyTags($tags = array()) /** * Return the filling percentage of the backend storage * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return int integer between 0 and 100 */ public function getFillingPercentage() @@ -350,7 +356,7 @@ 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'); + Cache\Cache::throwException('can\'t get disk_total_space'); } else { if ($free >= $total) { return 100; @@ -627,10 +633,10 @@ protected function _remove($file) * @param string $dir Directory to clean * @param string $mode Clean mode * @param array $tags Array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean True if no problem */ - protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + protected function _clean($dir, $mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { if (!is_dir($dir)) { return false; @@ -647,7 +653,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $fileName = basename($file); if ($this->_isMetadatasFile($fileName)) { // in CLEANING_MODE_ALL, we drop anything, even remainings old metadatas files - if ($mode != Zend_Cache::CLEANING_MODE_ALL) { + if ($mode != Cache\Cache::CLEANING_MODE_ALL) { continue; } } @@ -657,7 +663,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $metadatas = array('expire' => 1, 'tags' => array()); } switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: $res = $this->remove($id); if (!$res) { // in this case only, we accept a problem with the metadatas file drop @@ -665,12 +671,12 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a } $result = $result && $res; break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\Cache::CLEANING_MODE_OLD: if (time() > $metadatas['expire']) { $result = $this->remove($id) && $result; } break; - case Zend_Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: $matching = true; foreach ($tags as $tag) { if (!in_array($tag, $metadatas['tags'])) { @@ -682,7 +688,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $result = $this->remove($id) && $result; } break; - case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: $matching = false; foreach ($tags as $tag) { if (in_array($tag, $metadatas['tags'])) { @@ -694,7 +700,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a $result = $this->remove($id) && $result; } break; - case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $matching = false; foreach ($tags as $tag) { if (in_array($tag, $metadatas['tags'])) { @@ -707,7 +713,7 @@ protected function _clean($dir, $mode = Zend_Cache::CLEANING_MODE_ALL, $tags = a } break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } @@ -790,7 +796,7 @@ protected function _get($dir, $mode, $tags = array()) } break; default: - Zend_Cache::throwException('Invalid mode for _get() method'); + Cache\Cache::throwException('Invalid mode for _get() method'); break; } } @@ -825,7 +831,7 @@ protected function _expireTime($lifetime) * * @param string $data Data * @param string $controlType Type of control 'md5', 'crc32' or 'strlen' - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return string Control key */ protected function _hash($data, $controlType) @@ -840,7 +846,7 @@ protected function _hash($data, $controlType) case 'adler32': return hash('adler32', $data); default: - Zend_Cache::throwException("Incorrect hash function : $controlType"); + Cache\Cache::throwException("Incorrect hash function : $controlType"); } } diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index 995b82de0..54bb7cc60 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_ExtendedInterface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class Memcached extends Backend implements ExtendedInterface { /** * Default Values @@ -105,13 +111,13 @@ class Zend_Cache_Backend_Memcached extends Zend_Cache_Backend implements Zend_Ca * Constructor * * @param array $options associative array of options - * @throws Zend_Cache_Exception + * @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 !'); + Cache\Cache::throwException('The memcache extension must be loaded for using this backend !'); } parent::__construct($options); if (isset($this->_options['servers'])) { @@ -122,7 +128,7 @@ public function __construct(array $options = array()) } $this->setOption('servers', $value); } - $this->_memcache = new Memcache; + $this->_memcache = new \Memcache; foreach ($this->_options['servers'] as $server) { if (!array_key_exists('port', $server)) { $server['port'] = self::DEFAULT_PORT; @@ -244,25 +250,25 @@ public function remove($id) * * @param string $mode Clean mode * @param array $tags Array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean True if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: return $this->_memcache->flush(); break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\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: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_MEMCACHED_BACKEND); break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } @@ -281,7 +287,7 @@ public function isAutomaticCleaningAvailable() * Set the frontend directives * * @param array $directives Assoc of directives - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setDirectives($directives) @@ -365,7 +371,7 @@ public function getIdsMatchingAnyTags($tags = array()) /** * Return the filling percentage of the backend storage * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return int integer between 0 and 100 */ public function getFillingPercentage() @@ -391,7 +397,7 @@ public function getFillingPercentage() } if ($memSize === null || $memUsed === null) { - Zend_Cache::throwException('Can\'t get filling percentage'); + Cache\Cache::throwException('Can\'t get filling percentage'); } return ((int) (100. * ($memUsed / $memSize))); diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index 8280fc13d..46b7d9fa2 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_ExtendedInterface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Zend_Cache_Backend_Sqlite extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface +class Sqlite extends Backend implements ExtendedInterface { /** * Available options @@ -77,10 +83,10 @@ public function __construct(array $options = array()) { parent::__construct($options); if ($this->_options['cache_db_complete_path'] === null) { - Zend_Cache::throwException('cache_db_complete_path option has to set'); + Cache\Cache::throwException('cache_db_complete_path option has to set'); } if (!extension_loaded('sqlite')) { - Zend_Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment"); + Cache\Cache::throwException("Cannot use SQLite storage because the 'sqlite' extension is not loaded in the current PHP environment"); } $this->_getConnection(); } @@ -145,7 +151,7 @@ public function test($id) * @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) - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean True if no problem */ public function save($data, $id, $tags = array(), $specificLifetime = false) @@ -207,7 +213,7 @@ public function remove($id) * @param array $tags Array of tags * @return boolean True if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { $this->_checkAndBuildStructure(); $return = $this->_clean($mode, $tags); @@ -355,7 +361,7 @@ public function getIdsMatchingAnyTags($tags = array()) /** * Return the filling percentage of the backend storage * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return int integer between 0 and 100 */ public function getFillingPercentage() @@ -364,7 +370,7 @@ public function getFillingPercentage() $free = disk_free_space($dir); $total = disk_total_space($dir); if ($total == 0) { - Zend_Cache::throwException('can\'t get disk_total_space'); + Cache\Cache::throwException('can\'t get disk_total_space'); } else { if ($free >= $total) { return 100; @@ -475,7 +481,7 @@ public function ___expire($id) * * If we are not connected, the connection is made * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return resource Connection resource */ private function _getConnection() @@ -485,7 +491,7 @@ private function _getConnection() } else { $this->_db = @sqlite_open($this->_options['cache_db_complete_path']); if (!(is_resource($this->_db))) { - Zend_Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file"); + Cache\Cache::throwException("Impossible to open " . $this->_options['cache_db_complete_path'] . " cache DB file"); } return $this->_db; } @@ -604,21 +610,21 @@ private function _checkStructureVersion() * @param array $tags Array of tags * @return boolean True if no problem */ - private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + private function _clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: $res1 = $this->_query('DELETE FROM cache'); $res2 = $this->_query('DELETE FROM tag'); return $res1 && $res2; break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\Cache::CLEANING_MODE_OLD: $mktime = time(); $res1 = $this->_query("DELETE FROM tag WHERE id IN (SELECT id FROM cache WHERE expire>0 AND expire<=$mktime)"); $res2 = $this->_query("DELETE FROM cache WHERE expire>0 AND expire<=$mktime"); return $res1 && $res2; break; - case Zend_Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: $ids = $this->getIdsMatchingTags($tags); $result = true; foreach ($ids as $id) { @@ -626,7 +632,7 @@ private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } return $result; break; - case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: $ids = $this->getIdsNotMatchingTags($tags); $result = true; foreach ($ids as $id) { @@ -634,7 +640,7 @@ private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } return $result; break; - case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $ids = $this->getIdsMatchingAnyTags($tags); $result = true; foreach ($ids as $id) { @@ -651,7 +657,7 @@ private function _clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) /** * Check if the database structure is ok (with the good version), if no : build it * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean True if ok */ private function _checkAndBuildStructure() @@ -660,7 +666,7 @@ private function _checkAndBuildStructure() if (!$this->_checkStructureVersion()) { $this->_buildStructure(); if (!$this->_checkStructureVersion()) { - Zend_Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']); + Cache\Cache::throwException("Impossible to build cache structure in " . $this->_options['cache_db_complete_path']); } } $this->_structureChecked = true; diff --git a/src/Backend/Static.php b/src/Backend/StaticBackend.php similarity index 89% rename from src/Backend/Static.php rename to src/Backend/StaticBackend.php index 100b95660..151a216fe 100644 --- a/src/Backend/Static.php +++ b/src/Backend/StaticBackend.php @@ -21,22 +21,28 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_Interface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\BackendInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class StaticBackend + extends Backend + implements BackendInterface { const INNER_CACHE_NAME = 'zend_cache_backend_static_tagcache'; /** - * Static backend options + * StaticBackend backend options * @var array */ protected $_options = array( @@ -54,7 +60,7 @@ class Zend_Cache_Backend_Static /** * Cache for handling tags - * @var Zend_Cache_Core + * @var \Zend\Cache\Core */ protected $_tagCache = null; @@ -71,7 +77,7 @@ class Zend_Cache_Backend_Static * * @param string $name * @param mixed $value - * @return Zend_Cache_Backend_Static + * @return \Zend\Cache\Backend\StaticBackend */ public function setOption($name, $value) { @@ -122,10 +128,10 @@ public function load($id, $doNotTestCacheValidity = false) $id = $this->_decodeId($id); } if (!$this->_verifyPath($id)) { - Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); + Cache\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"); + $this->_log("Zend_Cache_Backend_Static::load() : \$doNotTestCacheValidity=true is unsupported by the StaticBackend backend"); } $fileName = basename($id); @@ -152,7 +158,7 @@ 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'); + Cache\Cache::throwException('Invalid cache id: does not match expected public_dir path'); } $fileName = basename($id); @@ -287,7 +293,7 @@ protected function _isSerialized($data) public function remove($id) { if (!$this->_verifyPath($id)) { - Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); + Cache\Cache::throwException('Invalid cache id: does not match expected public_dir path'); } $fileName = basename($id); if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { @@ -322,7 +328,7 @@ public function remove($id) public function removeRecursively($id) { if (!$this->_verifyPath($id)) { - Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); + Cache\Cache::throwException('Invalid cache id: does not match expected public_dir path'); } $fileName = basename($id); if (empty($fileName)) { @@ -335,7 +341,7 @@ public function removeRecursively($id) if (!is_writable($directory)) { return false; } - foreach (new DirectoryIterator($directory) as $file) { + foreach (new \DirectoryIterator($directory) as $file) { if (true === $file->isFile()) { if (false === unlink($file->getPathName())) { return false; @@ -370,14 +376,14 @@ public function removeRecursively($id) * @param array $tags Array of tags * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\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: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: if (empty($tags)) { - throw new Zend_Exception('Cannot use tag matching modes as no tags were defined'); + throw new end\Exception('Cannot use tag matching modes as no tags were defined'); } if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; @@ -396,7 +402,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME); $result = true; break; - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: if (is_null($this->_tagged)) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; @@ -412,12 +418,12 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $this->getInnerCache()->save($this->_tagged, self::INNER_CACHE_NAME); $result = true; break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\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: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: if (empty($tags)) { - throw new Zend_Exception('Cannot use tag matching modes as no tags were defined'); + throw new end\Exception('Cannot use tag matching modes as no tags were defined'); } if (is_null($this->_tagged)) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); @@ -438,7 +444,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $result = true; break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } return $result; @@ -450,10 +456,10 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) * should be completely cleaned as the mapping of tags to caches will * have been irrevocably lost. * - * @param Zend_Cache_Core + * @param \Zend\Cache\Core * @return void */ - public function setInnerCache(Zend_Cache_Core $cache) + public function setInnerCache(end\Cache\Core $cache) { $this->_tagCache = $cache; $this->_options['tag_cache'] = $cache; @@ -462,12 +468,12 @@ public function setInnerCache(Zend_Cache_Core $cache) /** * Get the Inner Cache if set * - * @return Zend_Cache_Core + * @return \Zend\Cache\Core */ public function getInnerCache() { if (is_null($this->_tagCache)) { - Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()'); + Cache\Cache::throwException('An Inner Cache has not been set; use setInnerCache()'); } return $this->_tagCache; } @@ -501,14 +507,14 @@ protected function _detectId() * Throw an exception if a problem is found * * @param string $string Cache id or tag - * @throws Zend_Cache_Exception + * @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'); + Cache\Cache::throwException('Invalid id or tag : must be a string'); } // Internal only checked in Frontend - not here! @@ -522,7 +528,7 @@ protected static function _validateIdOrTag($string) $string ) ) { - Zend_Cache::throwException("Invalid id or tag '$string' : must be a valid URL path"); + Cache\Cache::throwException("Invalid id or tag '$string' : must be a valid URL path"); } } diff --git a/src/Backend/Test.php b/src/Backend/Test.php index dcaa46742..2a1769053 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_Interface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\BackendInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class Test extends Backend implements ExtendedInterface { /** * Available options @@ -195,7 +201,7 @@ public function remove($id) * @param array $tags Array of tags * @return boolean True if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { $this->_addLog('clean', array($mode, $tags)); if ($mode=='false') { diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 9512ca4f8..6332746e3 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_ExtendedInterface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\ExtendedInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class TwoLevels extends Backend implements ExtendedInterface { /** * Available options @@ -83,14 +89,14 @@ class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Ca /** * Slow Backend * - * @var Zend_Cache_Backend + * @var \Zend\Cache\Backend\Backend */ protected $_slowBackend; /** * Fast Backend * - * @var Zend_Cache_Backend + * @var \Zend\Cache\Backend\Backend */ protected $_fastBackend; @@ -105,25 +111,25 @@ class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Ca * Constructor * * @param array $options Associative array of options - * @throws Zend_Cache_Exception + * @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'); + Cache\Cache::throwException('slow_backend option has to set'); } if ($this->_options['fast_backend'] === null) { - Zend_Cache::throwException('fast_backend option has to set'); + Cache\Cache::throwException('fast_backend option has to set'); } - $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']); - $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']); + $this->_slowBackend = Cache\Cache::_makeBackend($this->_options['slow_backend'], $this->_options['slow_backend_options'], $this->_options['slow_backend_custom_naming'], $this->_options['slow_backend_autoload']); + $this->_fastBackend = Cache\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->_slowBackend))) { - Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); + Cache\Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); } if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) { - Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); + Cache\Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); } $this->_slowBackend->setDirectives($this->_directives); $this->_fastBackend->setDirectives($this->_directives); @@ -238,20 +244,20 @@ public function remove($id) * * @param string $mode Clean mode * @param array $tags Array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\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); + case Cache\Cache::CLEANING_MODE_ALL: + $boolFast = $this->_fastBackend->clean(Cache\Cache::CLEANING_MODE_ALL); + $boolSlow = $this->_slowBackend->clean(Cache\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: + case Cache\Cache::CLEANING_MODE_OLD: + return $this->_slowBackend->clean(Cache\Cache::CLEANING_MODE_OLD); + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: $ids = $this->_slowBackend->getIdsMatchingTags($tags); $res = true; foreach ($ids as $id) { @@ -260,7 +266,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } return $res; break; - case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: $ids = $this->_slowBackend->getIdsNotMatchingTags($tags); $res = true; foreach ($ids as $id) { @@ -269,7 +275,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } return $res; break; - case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags); $res = true; foreach ($ids as $id) { @@ -279,7 +285,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) return $res; break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } diff --git a/src/Backend/Xcache.php b/src/Backend/Xcache.php index 76b113c74..340d605e6 100644 --- a/src/Backend/Xcache.php +++ b/src/Backend/Xcache.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_Interface + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\BackendInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class Xcache extends Backend implements BackendInterface { /** @@ -58,13 +64,13 @@ class Zend_Cache_Backend_Xcache extends Zend_Cache_Backend implements Zend_Cache * Constructor * * @param array $options associative array of options - * @throws Zend_Cache_Exception + * @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 !'); + Cache\Cache::throwException('The xcache extension must be loaded for using this backend !'); } parent::__construct($options); } @@ -152,13 +158,13 @@ public function remove($id) * * @param string $mode clean mode * @param array $tags array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: // Necessary because xcache_clear_cache() need basic authentification $backup = array(); if (isset($_SERVER['PHP_AUTH_USER'])) { @@ -180,16 +186,16 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } return true; break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\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: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $this->_log(self::TAGS_UNSUPPORTED_BY_CLEAN_OF_XCACHE_BACKEND); break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } diff --git a/src/Backend/ZendPlatform.php b/src/Backend/ZendPlatform.php index 7228253e3..d7d6ed375 100644 --- a/src/Backend/ZendPlatform.php +++ b/src/Backend/ZendPlatform.php @@ -20,18 +20,24 @@ * @version $Id$ */ +/** + * @namespace + */ +namespace Zend\Cache\Backend; +use Zend\Cache; + /** * Impementation of Zend Cache Backend using the Zend Platform (Output Content Caching) * - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_Interface + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\BackendInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class ZendPlatform extends Backend implements BackendInterface { /** * internal ZP prefix @@ -43,27 +49,27 @@ class Zend_Cache_Backend_ZendPlatform extends Zend_Cache_Backend implements Zend * Validate that the Zend Platform is loaded and licensed * * @param array $options Associative array of options - * @throws Zend_Cache_Exception + * @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 !'); + Cache\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']); + Cache\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'); + Cache\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 !'); + Cache\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 !'); + Cache\Cache::throwException('The cache copies directory \''. ini_get('zend_accelerator.output_cache_dir') .'\' must be writable !'); } parent:: __construct($options); } @@ -171,14 +177,14 @@ public function remove($id) * * @param string $mode Clean mode * @param array $tags Array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean True if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_OLD: $cache_dir = ini_get('zend_accelerator.output_cache_dir'); if (!$cache_dir) { return false; @@ -186,7 +192,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $cache_dir .= '/.php_cache_api/'; return $this->_clean($cache_dir, $mode); break; - case Zend_Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: $idlist = null; foreach ($tags as $tag) { $next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']); @@ -208,11 +214,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) } return true; break; - case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: $this->_log("Zend_Cache_Backend_ZendPlatform::clean() : CLEANING_MODE_NOT_MATCHING_TAG is not supported by the Zend Platform backend"); return false; break; - case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG: + case Cache\Cache::CLEANING_MODE_MATCHING_ANY_TAG: $idlist = null; foreach ($tags as $tag) { $next_idlist = output_cache_get(self::TAGS_PREFIX.$tag, $this->_directives['lifetime']); @@ -235,7 +241,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) return true; break; default: - Zend_Cache::throwException('Invalid mode for clean() method'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } @@ -246,7 +252,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) * 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() + * @param string $mode The same parameter as in \Zend\Cache\Backend\ZendPlatform::clean() * @return boolean True if ok */ private function _clean($dir, $mode) @@ -264,9 +270,9 @@ private function _clean($dir, $mode) if (is_dir($file)) { $result = ($this->_clean($file .'/', $mode)) && ($result); } else { - if ($mode == Zend_Cache::CLEANING_MODE_ALL) { + if ($mode == Cache\Cache::CLEANING_MODE_ALL) { $result = ($this->_remove($file)) && ($result); - } else if ($mode == Zend_Cache::CLEANING_MODE_OLD) { + } else if ($mode == Cache\Cache::CLEANING_MODE_OLD) { // Files older than lifetime get deleted from cache if ($this->_directives['lifetime'] !== null) { if ((time() - @filemtime($file)) > $this->_directives['lifetime']) { diff --git a/src/Backend/ZendServer/Disk.php b/src/Backend/ZendServer/Disk.php old mode 100755 new mode 100644 index 92ea0ecdf..0c5bc5da4 --- a/src/Backend/ZendServer/Disk.php +++ b/src/Backend/ZendServer/Disk.php @@ -21,26 +21,31 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend_Interface - * @uses Zend_Cache_Backend_ZendServer + * @namespace + */ +namespace Zend\Cache\Backend\ZendServer; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\BackendInterface + * @uses \Zend\Cache\Backend\ZendServer\ZendServer * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class Disk extends ZendServer implements \Zend\Cache\Backend\BackendInterface { /** * Constructor * * @param array $options associative array of options - * @throws Zend_Cache_Exception + * @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.'); + \Zend\Cache\Cache::throwException('Zend_Cache_ZendServer_Disk backend has to be used within Zend Server environment.'); } parent::__construct($options); } diff --git a/src/Backend/ZendServer/ShMem.php b/src/Backend/ZendServer/ShMem.php old mode 100755 new mode 100644 index 15ac4f71d..f10709632 --- a/src/Backend/ZendServer/ShMem.php +++ b/src/Backend/ZendServer/ShMem.php @@ -21,26 +21,31 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend_Interface - * @uses Zend_Cache_Backend_ZendServer + * @namespace + */ +namespace Zend\Cache\Backend\ZendServer; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\BackendInterface + * @uses \Zend\Cache\Backend\ZendServer\ZendServer * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +class ShMem extends ZendServer implements \Zend\Cache\Backend\BackendInterface { /** * Constructor * * @param array $options associative array of options - * @throws Zend_Cache_Exception + * @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.'); + \Zend\Cache\Cache::throwException('Zend_Cache_ZendServer_ShMem backend has to be used within Zend Server environment.'); } parent::__construct($options); } diff --git a/src/Backend/ZendServer.php b/src/Backend/ZendServer/ZendServer.php old mode 100755 new mode 100644 similarity index 84% rename from src/Backend/ZendServer.php rename to src/Backend/ZendServer/ZendServer.php index 1d1f6942f..757d20f66 --- a/src/Backend/ZendServer.php +++ b/src/Backend/ZendServer/ZendServer.php @@ -21,15 +21,21 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Backend - * @uses Zend_Cache_Backend_Interface + * @namespace + */ +namespace Zend\Cache\Backend\ZendServer; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Backend\Backend + * @uses \Zend\Cache\Backend\BackendInterface * @package Zend_Cache * @subpackage Zend_Cache_Backend * @copyright Copyright (c) 2005-2010 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 +abstract class ZendServer extends Cache\Backend\Backend implements Cache\Backend\BackendInterface { /** * Available options @@ -49,7 +55,7 @@ abstract class Zend_Cache_Backend_ZendServer extends Zend_Cache_Backend implemen * @param mixed $data Object to store * @param string $id Cache id * @param int $timeToLive Time to live in seconds - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception */ abstract protected function _store($data, $id, $timeToLive); @@ -57,7 +63,7 @@ abstract protected function _store($data, $id, $timeToLive); * Fetch data * * @param string $id Cache id - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception */ abstract protected function _fetch($id); @@ -94,14 +100,14 @@ public function load($id, $doNotTestCacheValidity = false) * * @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 + * @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' ); + Cache\Cache::throwException('Cache metadata for \'' . $id . '\' id is corrupted' ); } return $tmp['mtime']; } @@ -175,27 +181,27 @@ public function remove($id) * * @param string $mode clean mode * @param array $tags array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean true if no problem */ - public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { - case Zend_Cache::CLEANING_MODE_ALL: + case Cache\Cache::CLEANING_MODE_ALL: $this->_clear(); return true; break; - case Zend_Cache::CLEANING_MODE_OLD: + case Cache\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: + case Cache\Cache::CLEANING_MODE_MATCHING_TAG: + case Cache\Cache::CLEANING_MODE_NOT_MATCHING_TAG: + case Cache\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'); + Cache\Cache::throwException('Invalid mode for clean() method'); break; } } diff --git a/src/Cache.php b/src/Cache.php new file mode 100644 index 000000000..5757f55bb --- /dev/null +++ b/src/Cache.php @@ -0,0 +1,249 @@ +setBackend($backendObject); + return $frontendObject; + } + + /** + * Backend Constructor + * + * @param string $backend + * @param array $backendOptions + * @param boolean $customBackendNaming + * @param boolean $autoload + * @return \Zend\Cache\Backend\Backend + */ + public static function _makeBackend($backend, $backendOptions, $customBackendNaming = false, $autoload = false) + { + if (!$customBackendNaming) { + $backend = self::_normalizeName($backend); + } + if (in_array($backend, Cache::$standardBackends)) { + // we use a standard backend + $backendClass = 'Zend_Cache_Backend_' . $backend; + // security controls are explicit + require_once str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php'; + } else { + // we use a custom backend + if (!preg_match('~^[\w]+$~D', $backend)) { + Cache::throwException("Invalid backend name [$backend]"); + } + if (!$customBackendNaming) { + // we use this boolean to avoid an API break + $backendClass = 'Zend_Cache_Backend_' . $backend; + } else { + $backendClass = $backend; + } + if (!$autoload) { + $file = str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php'; + if (!(self::_isReadable($file))) { + self::throwException("file $file not found in include_path"); + } + require_once $file; + } + } + return new $backendClass($backendOptions); + } + + /** + * Frontend Constructor + * + * @param string $frontend + * @param array $frontendOptions + * @param boolean $customFrontendNaming + * @param boolean $autoload + * @return Zend_Cache_Core|Zend_Cache_Frontend + */ + public static function _makeFrontend($frontend, $frontendOptions = array(), $customFrontendNaming = false, $autoload = false) + { + if (!$customFrontendNaming) { + $frontend = self::_normalizeName($frontend); + } + if (in_array($frontend, self::$standardFrontends)) { + // we use a standard frontend + // For perfs reasons, with frontend == 'Core', we can interact with the Core itself + $frontendClass = 'Zend_Cache_' . ($frontend != 'Core' ? 'Frontend_' : '') . $frontend; + // security controls are explicit + require_once str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; + } else { + // we use a custom frontend + if (!preg_match('~^[\w]+$~D', $frontend)) { + Cache::throwException("Invalid frontend name [$frontend]"); + } + if (!$customFrontendNaming) { + // we use this boolean to avoid an API break + $frontendClass = 'Zend_Cache_Frontend_' . $frontend; + } else { + $frontendClass = $frontend; + } + if (!$autoload) { + $file = str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; + if (!(self::_isReadable($file))) { + self::throwException("file $file not found in include_path"); + } + require_once $file; + } + } + return new $frontendClass($frontendOptions); + } + + /** + * Throw an exception + * + * Note : for perf reasons, the "load" of Zend/Cache/Exception is dynamic + * @param string $msg Message for the exception + * @throws \Zend\Cache\Exception + */ + public static function throwException($msg, \Exception $e = null) + { + // For perfs reasons, we use this dynamic inclusion + require_once 'Zend/Cache/Exception.php'; + throw new Exception($msg, 0, $e); + } + + /** + * Normalize frontend and backend names to allow multiple words TitleCased + * + * @param string $name Name to normalize + * @return string + */ + protected static function _normalizeName($name) + { + $name = ucfirst(strtolower($name)); + $name = str_replace(array('-', '_', '.'), ' ', $name); + $name = ucwords($name); + $name = str_replace(' ', '', $name); + return $name; + } + + /** + * Returns TRUE if the $filename is readable, or FALSE otherwise. + * This function uses the PHP include_path, where PHP's is_readable() + * does not. + * + * Note : this method comes from Zend_Loader (see #ZF-2891 for details) + * + * @param string $filename + * @return boolean + */ + private static function _isReadable($filename) + { + if (!$fh = @fopen($filename, 'r', true)) { + return false; + } + @fclose($fh); + return true; + } + +} diff --git a/src/Core.php b/src/Core.php index 13e151934..860a2c523 100644 --- a/src/Core.php +++ b/src/Core.php @@ -19,16 +19,22 @@ * @version $Id$ */ +/** + * @namespace + */ +namespace Zend\Cache; +use Zend\Config; +use Zend\Log; /** - * @uses Zend_Cache - * @uses Zend_Log - * @uses Zend_Log_Writer_Stream + * @uses \Zend\Cache\Cache + * @uses \Zend\Log\Logger + * @uses \Zend\Log\Writer\Stream * @package Zend_Cache * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Zend_Cache_Core +class Core { /** * Messages @@ -133,17 +139,17 @@ class Zend_Cache_Core /** * Constructor * - * @param array|Zend_Config $options Associative array of options or Zend_Config instance - * @throws Zend_Cache_Exception + * @param array|\Zend\Config\Config $options Associative array of options or \Zend\Config\Config instance + * @throws \Zend\Cache\Exception * @return void */ public function __construct($options = array()) { - if ($options instanceof Zend_Config) { + if ($options instanceof Config\Config) { $options = $options->toArray(); } if (!is_array($options)) { - Zend_Cache::throwException("Options passed were not an array" + Cache::throwException("Options passed were not an array" . " or Zend_Config instance."); } while (list($name, $value) = each($options)) { @@ -155,10 +161,10 @@ public function __construct($options = array()) /** * Set options using an instance of type Zend_Config * - * @param Zend_Config $config - * @return Zend_Cache_Core + * @param \Zend\Config\Config $config + * @return \Zend\Cache\Core */ - public function setConfig(Zend_Config $config) + public function setConfig(Config\Config $config) { $options = $config->toArray(); while (list($name, $value) = each($options)) { @@ -171,16 +177,16 @@ public function setConfig(Zend_Config $config) * Set the backend * * @param object $backendObject - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ - public function setBackend(Zend_Cache_Backend $backendObject) + public function setBackend(Backend\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) { + foreach (Core::$_directivesList as $directive) { $directives[$directive] = $this->_options[$directive]; } $this->_backend->setDirectives($directives); @@ -208,13 +214,13 @@ public function getBackend() * * @param string $name Name of the option * @param mixed $value Value of the option - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setOption($name, $value) { if (!is_string($name)) { - Zend_Cache::throwException("Incorrect option name : $name"); + Cache::throwException("Incorrect option name : $name"); } $name = strtolower($name); if (array_key_exists($name, $this->_options)) { @@ -233,7 +239,7 @@ public function setOption($name, $value) * Public frontend to get an option value * * @param string $name Name of the option - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return mixed option value */ public function getOption($name) @@ -249,7 +255,7 @@ public function getOption($name) return $this->_specificOptions[$name]; } } - Zend_Cache::throwException("Incorrect option name : $name"); + Cache::throwException("Incorrect option name : $name"); } /** @@ -257,13 +263,13 @@ public function getOption($name) * * @param string $name Name of the option * @param mixed $value Value of the option - * @throws Zend_Cache_Exception + * @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"); + Cache::throwException("Incorrect option name : $name"); } if ($name == 'lifetime' && empty($value)) { $value = null; @@ -340,7 +346,7 @@ public function test($id) * @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 + * @throws \Zend\Cache\Exception * @return boolean True if no problem */ public function save($data, $id = null, $tags = array(), $specificLifetime = false, $priority = 8) @@ -360,7 +366,7 @@ public function save($data, $id = null, $tags = array(), $specificLifetime = fal $data = serialize($data); } else { if (!is_string($data)) { - Zend_Cache::throwException("Datas must be string or set automatic_serialization = true"); + Cache::throwException("Datas must be string or set automatic_serialization = true"); } } // automatic cleaning @@ -370,14 +376,14 @@ public function save($data, $id = null, $tags = array(), $specificLifetime = fal if ($this->_extendedBackend) { // New way if ($this->_backendCapabilities['automatic_cleaning']) { - $this->clean(Zend_Cache::CLEANING_MODE_OLD); + $this->clean(Cache::CLEANING_MODE_OLD); } else { $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend'); } } else { // Deprecated way (will be removed in next major version) if (method_exists($this->_backend, 'isAutomaticCleaningAvailable') && ($this->_backend->isAutomaticCleaningAvailable())) { - $this->clean(Zend_Cache::CLEANING_MODE_OLD); + $this->clean(Cache::CLEANING_MODE_OLD); } else { $this->_log('Zend_Cache_Core::save() / automatic cleaning is not available/necessary with this backend'); } @@ -445,7 +451,7 @@ public function remove($id) * * @param string $mode * @param array|string $tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return boolean True if ok */ public function clean($mode = 'all', $tags = array()) @@ -453,12 +459,12 @@ 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'); + if (!in_array($mode, array(Cache::CLEANING_MODE_ALL, + Cache::CLEANING_MODE_OLD, + Cache::CLEANING_MODE_MATCHING_TAG, + Cache::CLEANING_MODE_NOT_MATCHING_TAG, + Cache::CLEANING_MODE_MATCHING_ANY_TAG))) { + Cache::throwException('Invalid cleaning mode'); } self::_validateTagsArray($tags); return $this->_backend->clean($mode, $tags); @@ -475,10 +481,10 @@ public function clean($mode = 'all', $tags = array()) public function getIdsMatchingTags($tags = array()) { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } $ids = $this->_backend->getIdsMatchingTags($tags); @@ -508,10 +514,10 @@ public function getIdsMatchingTags($tags = array()) public function getIdsNotMatchingTags($tags = array()) { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } $ids = $this->_backend->getIdsNotMatchingTags($tags); @@ -541,10 +547,10 @@ public function getIdsNotMatchingTags($tags = array()) public function getIdsMatchingAnyTags($tags = array()) { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } $ids = $this->_backend->getIdsMatchingAnyTags($tags); @@ -571,7 +577,7 @@ public function getIdsMatchingAnyTags($tags = array()) public function getIds() { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } $ids = $this->_backend->getIds(); @@ -598,10 +604,10 @@ public function getIds() public function getTags() { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); } return $this->_backend->getTags(); } @@ -614,7 +620,7 @@ public function getTags() public function getFillingPercentage() { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } return $this->_backend->getFillingPercentage(); } @@ -633,7 +639,7 @@ public function getFillingPercentage() public function getMetadatas($id) { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } $id = $this->_id($id); // cache id may need prefix return $this->_backend->getMetadatas($id); @@ -649,7 +655,7 @@ public function getMetadatas($id) public function touch($id, $extraLifetime) { if (!$this->_extendedBackend) { - Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); + Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } $id = $this->_id($id); // cache id may need prefix return $this->_backend->touch($id, $extraLifetime); @@ -661,19 +667,19 @@ public function touch($id, $extraLifetime) * Throw an exception if a problem is found * * @param string $string Cache id or tag - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected static function _validateIdOrTag($string) { if (!is_string($string)) { - Zend_Cache::throwException('Invalid id or tag : must be a string'); + 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'); + 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_]"); + Cache::throwException("Invalid id or tag '$string' : must use only [a-zA-Z0-9_]"); } } @@ -683,13 +689,13 @@ protected static function _validateIdOrTag($string) * Throw an exception if a problem is found * * @param array $tags Array of tags - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected static function _validateTagsArray($tags) { if (!is_array($tags)) { - Zend_Cache::throwException('Invalid tags array : must be an array'); + Cache::throwException('Invalid tags array : must be an array'); } foreach($tags as $tag) { self::_validateIdOrTag($tag); @@ -702,7 +708,7 @@ protected static function _validateTagsArray($tags) * is available. * Create a default log object if none is set. * - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected function _loggerSanity() @@ -711,12 +717,12 @@ protected function _loggerSanity() return; } - if (isset($this->_options['logger']) && $this->_options['logger'] instanceof Zend_Log) { + if (isset($this->_options['logger']) && $this->_options['logger'] instanceof Log\Logger) { return; } // Create a default logger to the standard output stream - $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); + $logger = new Log\Logger(new Log\Writer\Stream('php://output')); $this->_options['logger'] = $logger; } @@ -724,7 +730,7 @@ protected function _loggerSanity() * Log a message at the WARN (4) priority. * * @param string $message - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected function _log($message, $priority = 4) @@ -732,8 +738,8 @@ 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'); + if (!(isset($this->_options['logger']) || $this->_options['logger'] instanceof Log\Logger)) { + Cache::throwException('Logging is enabled but logger is not set'); } $logger = $this->_options['logger']; $logger->log($message, $priority); diff --git a/src/Exception.php b/src/Exception.php index a67b765da..fcb1ba2a2 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -20,9 +20,14 @@ */ /** - * @uses Zend_Exception + * @namespace + */ +namespace Zend\Cache; + +/** + * @uses \Zend\Exception * @package Zend_Cache * @copyright Copyright (c) 2005-2010 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 {} +class Exception extends \Zend\Exception {} diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index 7fb88a5af..6453c74be 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -21,13 +21,18 @@ */ /** - * @uses Zend_Cache_Core + * @namespace + */ +namespace Zend\Cache\Frontend; + +/** + * @uses \Zend\Cache\Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 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 +class Capture extends \Zend\Cache\Core { /** * Page identifiers @@ -70,7 +75,7 @@ public function _flush($data) { $id = array_pop($this->_idStack); if (is_null($id)) { - Zend_Cache::throwException('use of _flush() without a start()'); + \Zend\Cache\Cache::throwException('use of _flush() without a start()'); } if ($this->_extension) { $this->save(serialize(array($data, $this->_extension)), $id, $this->_tags); diff --git a/src/Frontend/Class.php b/src/Frontend/ClassFrontend.php similarity index 93% rename from src/Frontend/Class.php rename to src/Frontend/ClassFrontend.php index 8449fa648..a48967400 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/ClassFrontend.php @@ -21,13 +21,19 @@ */ /** - * @uses Zend_Cache_Core + * @namespace + */ +namespace Zend\Cache\Frontend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 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 +class ClassFrontend extends Cache\Core { /** * Available options @@ -97,7 +103,7 @@ class Zend_Cache_Frontend_Class extends Zend_Cache_Core * Constructor * * @param array $options Associative array of options - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function __construct(array $options = array()) @@ -106,7 +112,7 @@ public function __construct(array $options = array()) $this->setOption($name, $value); } if ($this->_specificOptions['cached_entity'] === null) { - Zend_Cache::throwException('cached_entity must be set !'); + Cache\Cache::throwException('cached_entity must be set !'); } $this->setCachedEntity($this->_specificOptions['cached_entity']); $this->setOption('automatic_serialization', true); @@ -140,7 +146,7 @@ public function setPriority($priority) * * @param string $name Name of the option * @param mixed $value Value of the option - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setOption($name, $value) @@ -163,14 +169,14 @@ public function setOption($name, $value) public function setCachedEntity($cachedEntity) { if (!is_string($cachedEntity) && !is_object($cachedEntity)) { - Zend_Cache::throwException('cached_entity must be an object or a class name'); + Cache\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); + $ro = new \ReflectionObject($this->_cachedEntity); $this->_cachedEntityLabel = $ro->getName(); } } diff --git a/src/Frontend/File.php b/src/Frontend/File.php index 0b0f6ee2e..0e1f47e23 100644 --- a/src/Frontend/File.php +++ b/src/Frontend/File.php @@ -21,13 +21,19 @@ */ /** - * @uses Zend_Cache_Core + * @namespace + */ +namespace Zend\Cache\Frontend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 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 +class File extends Cache\Core { /** @@ -77,7 +83,7 @@ class Zend_Cache_Frontend_File extends Zend_Cache_Core * Constructor * * @param array $options Associative array of options - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function __construct(array $options = array()) @@ -86,7 +92,7 @@ public function __construct(array $options = array()) $this->setOption($name, $value); } if (!isset($this->_specificOptions['master_files'])) { - Zend_Cache::throwException('master_files option must be set'); + Cache\Cache::throwException('master_files option must be set'); } } @@ -105,7 +111,7 @@ public function setMasterFiles($masterFiles) foreach ($masterFiles as $masterFile) { $this->_masterFile_mtimes[$i] = @filemtime($masterFile); if ((!($this->_specificOptions['ignore_missing_master_files'])) && (!($this->_masterFile_mtimes[$i]))) { - Zend_Cache::throwException('Unable to read master_file : '.$masterFile); + Cache\Cache::throwException('Unable to read master_file : '.$masterFile); } $i++; } @@ -131,7 +137,7 @@ public function setMasterFile($masterFile) * * @param string $name Name of the option * @param mixed $value Value of the option - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ public function setOption($name, $value) diff --git a/src/Frontend/Function.php b/src/Frontend/FunctionFrontend.php similarity index 92% rename from src/Frontend/Function.php rename to src/Frontend/FunctionFrontend.php index 5d93902c4..a47c81743 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/FunctionFrontend.php @@ -21,13 +21,19 @@ */ /** - * @uses Zend_Cache_Core + * @namespace + */ +namespace Zend\Cache\Frontend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 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 +class FunctionFrontend extends Cache\Core { /** * This frontend specific options @@ -109,16 +115,16 @@ public function call($name, $parameters = array(), $tags = array(), $specificLif * * @param string $name Function name * @param array $parameters Function parameters - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return string Cache id */ private function _makeId($name, $parameters) { if (!is_string($name)) { - Zend_Cache::throwException('Incorrect function name'); + Cache\Cache::throwException('Incorrect function name'); } if (!is_array($parameters)) { - Zend_Cache::throwException('parameters argument must be an array'); + Cache\Cache::throwException('parameters argument must be an array'); } return md5($name . serialize($parameters)); } diff --git a/src/Frontend/Output.php b/src/Frontend/Output.php index 7111cc6f7..d5afde651 100644 --- a/src/Frontend/Output.php +++ b/src/Frontend/Output.php @@ -21,13 +21,18 @@ */ /** - * @uses Zend_Cache_Core + * @namespace + */ +namespace Zend\Cache\Frontend; + +/** + * @uses \Zend\Cache\Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 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 +class Output extends \Zend\Cache\Core { private $_idStack = array(); @@ -89,7 +94,7 @@ public function end($tags = array(), $specificLifetime = false, $forcedDatas = n } $id = array_pop($this->_idStack); if ($id === null) { - Zend_Cache::throwException('use of end() without a start()'); + \Zend\Cache\Cache::throwException('use of end() without a start()'); } $this->save($data, $id, $tags, $specificLifetime, $priority); if ($echoData) { diff --git a/src/Frontend/Page.php b/src/Frontend/Page.php index 8c5bf0cd3..b30283ac2 100644 --- a/src/Frontend/Page.php +++ b/src/Frontend/Page.php @@ -21,13 +21,19 @@ */ /** - * @uses Zend_Cache_Core + * @namespace + */ +namespace Zend\Cache\Frontend; +use Zend\Cache; + +/** + * @uses \Zend\Cache\Core * @package Zend_Cache * @subpackage Zend_Cache_Frontend * @copyright Copyright (c) 2005-2010 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 +class Page extends Cache\Core { /** * This frontend specific options @@ -118,7 +124,7 @@ class Zend_Cache_Frontend_Page extends Zend_Cache_Core * * @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 + * @throws \Zend\Cache\Exception * @return void */ public function __construct(array $options = array()) @@ -141,7 +147,7 @@ public function __construct(array $options = array()) } if (isset($this->_specificOptions['http_conditional'])) { if ($this->_specificOptions['http_conditional']) { - Zend_Cache::throwException('http_conditional is not implemented for the moment !'); + Cache\Cache::throwException('http_conditional is not implemented for the moment !'); } } $this->setOption('automatic_serialization', true); @@ -151,17 +157,17 @@ public function __construct(array $options = array()) * Specific setter for the 'default_options' option (with some additional tests) * * @param array $options Associative array - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected function _setDefaultOptions($options) { if (!is_array($options)) { - Zend_Cache::throwException('default_options must be an array !'); + Cache\Cache::throwException('default_options must be an array !'); } foreach ($options as $key=>$value) { if (!is_string($key)) { - Zend_Cache::throwException("invalid option [$key] !"); + Cache\Cache::throwException("invalid option [$key] !"); } $key = strtolower($key); if (isset($this->_specificOptions['default_options'][$key])) { @@ -200,22 +206,22 @@ protected function _setContentTypeMemorization($value) * Specific setter for the 'regexps' option (with some additional tests) * * @param array $options Associative array - * @throws Zend_Cache_Exception + * @throws \Zend\Cache\Exception * @return void */ protected function _setRegexps($regexps) { if (!is_array($regexps)) { - Zend_Cache::throwException('regexps option must be an array !'); + Cache\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 !'); + Cache\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] !"); + Cache\Cache::throwException("unknown option [$key] !"); } $key = strtolower($key); if (!in_array($key, $validKeys)) { diff --git a/src/Manager.php b/src/Manager.php index e17e257d5..e8cf78494 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -20,14 +20,20 @@ */ /** - * @uses Zend_Cache - * @uses Zend_Cache_Exception + * @namespace + */ +namespace Zend\Cache; +use Zend\Config; + +/** + * @uses \Zend\Cache\Cache + * @uses \Zend\Cache\Exception * @category Zend * @package Zend_Cache * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Zend_Cache_Manager +class Manager { /** * Constant holding reserved name for default Page Cache @@ -117,10 +123,10 @@ class Zend_Cache_Manager * Set a new cache for the Cache Manager to contain * * @param string $name - * @param Zend_Cache_Core $cache - * @return Zend_Cache_Manager + * @param \Zend\Cache\Core $cache + * @return \Zend\Cache\Manager */ - public function setCache($name, Zend_Cache_Core $cache) + public function setCache($name, Core $cache) { $this->_caches[$name] = $cache; return $this; @@ -148,7 +154,7 @@ public function hasCache($name) * using a named configuration template * * @param string $name - * @return Zend_Cache_Core + * @return \Zend\Cache\Core */ public function getCache($name) { @@ -158,12 +164,12 @@ public function getCache($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'] instanceof Core) ) { $this->_optionTemplates[$name]['backend']['options']['tag_cache'] = $this->getCache(self::PAGETAGCACHE ); } - $this->_caches[$name] = Zend_Cache::factory( + $this->_caches[$name] = Cache::factory( $this->_optionTemplates[$name]['frontend']['name'], $this->_optionTemplates[$name]['backend']['name'], isset($this->_optionTemplates[$name]['frontend']['options']) ? $this->_optionTemplates[$name]['frontend']['options'] : array(), @@ -179,14 +185,14 @@ public function getCache($name) * * @param string $name * @param array $options - * @return Zend_Cache_Manager + * @return \Zend\Cache\Manager */ public function setCacheTemplate($name, $options) { - if ($options instanceof Zend_Config) { + if ($options instanceof Config\Config) { $options = $options->toArray(); } elseif (!is_array($options)) { - throw new Zend_Cache_Exception('Options passed must be in' + throw new Exception('Options passed must be in' . ' an associative array or instance of Zend_Config'); } $this->_optionTemplates[$name] = $options; @@ -227,19 +233,19 @@ public function getCacheTemplate($name) * * @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 + * @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) { + if ($options instanceof Config\Config) { $options = $options->toArray(); } elseif (!is_array($options)) { - throw new Zend_Cache_Exception('Options passed must be in' + throw new 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' + throw new Exception('A cache configuration template' . ' does not exist with the name "' . $name . '"'); } $this->_optionTemplates[$name] diff --git a/test/ApcBackendTest.php b/test/ApcBackendTest.php index b04cfad9b..dd97c4132 100644 --- a/test/ApcBackendTest.php +++ b/test/ApcBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,14 +31,14 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ApcBackendTest extends Zend_Cache_TestCommonExtendedBackend +class ApcBackendTest extends \ZendTest\Cache\TestCommonExtendedBackend { protected $_instance; public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_Apc', $data, $dataName); + parent::__construct('Zend\Cache\Backend\Apc', $data, $dataName); } public function setUp($notag = true) @@ -43,7 +46,7 @@ public function setUp($notag = true) if (!constant('TESTS_ZEND_CACHE_APC_ENABLED')) { $this->markTestSkipped('Zend_Cache APC tests not enabled'); } - $this->_instance = new Zend_Cache_Backend_Apc(array()); + $this->_instance = new Cache\Backend\Apc(array()); parent::setUp($notag); } @@ -55,7 +58,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Apc(); + $test = new Cache\Backend\Apc(); } public function testCleanModeOld() { diff --git a/test/ClassFrontendTest.php b/test/ClassFrontendTest.php index 604ea6087..6c76dec6e 100644 --- a/test/ClassFrontendTest.php +++ b/test/ClassFrontendTest.php @@ -20,13 +20,8 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ +namespace ZendTest\Cache; +use Zend\Cache; /** * @todo: Should this class be named Zend_Cache_Something? @@ -63,7 +58,7 @@ public function foobar2($param1, $param2) { * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ClassFrontendTest extends PHPUnit_Framework_TestCase { +class ClassFrontendTest extends \PHPUnit_Framework_TestCase { private $_instance1; private $_instance2; @@ -74,16 +69,16 @@ public function setUp() $options1 = array( 'cached_entity' => 'test' ); - $this->_instance1 = new Zend_Cache_Frontend_Class($options1); - $this->_backend1 = new Zend_Cache_Backend_Test(); + $this->_instance1 = new Cache\Frontend\ClassFrontend($options1); + $this->_backend1 = new Cache\Backend\Test(); $this->_instance1->setBackend($this->_backend1); } if (!$this->_instance2) { $options2 = array( 'cached_entity' => new test() ); - $this->_instance2 = new Zend_Cache_Frontend_Class($options2); - $this->_backend2 = new Zend_Cache_Backend_Test(); + $this->_instance2 = new Cache\Frontend\ClassFrontend($options2); + $this->_backend2 = new Cache\Backend\Test(); $this->_instance2->setBackend($this->_backend2); } } @@ -100,7 +95,7 @@ public function testConstructorCorrectCall1() 'cache_by_default' => false, 'cached_entity' => 'test' ); - $test = new Zend_Cache_Frontend_Class($options); + $test = new Cache\Frontend\ClassFrontend($options); } public function testConstructorCorrectCall2() @@ -109,7 +104,7 @@ public function testConstructorCorrectCall2() 'cache_by_default' => false, 'cached_entity' => new test() ); - $test = new Zend_Cache_Frontend_Class($options); + $test = new Cache\Frontend\ClassFrontend($options); } public function testConstructorBadCall() @@ -119,11 +114,11 @@ public function testConstructorBadCall() 0 => true, ); try { - $test = new Zend_Cache_Frontend_Class($options); - } catch (Zend_Cache_Exception $e) { + $test = new Cache\Frontend\ClassFrontend($options); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testCallCorrectCall1() @@ -226,11 +221,11 @@ public function testConstructorWithABadCachedEntity() $options = array( 'cached_entity' => array() ); - $instance = new Zend_Cache_Frontend_Class($options); - } catch (Zend_Cache_Exception $e) { + $instance = new Cache\Frontend\ClassFrontend($options); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } /** @@ -242,7 +237,7 @@ public function testCallingConstructorWithInvalidOptionShouldNotRaiseException() 'cached_entity' => new test(), 'this_key_does_not_exist' => true ); - $test = new Zend_Cache_Frontend_Class($options); + $test = new Cache\Frontend\ClassFrontend($options); } } diff --git a/test/CoreTest.php b/test/CoreTest.php index 03bb08618..b6615bba4 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -20,14 +20,9 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ - +namespace ZendTest\Cache; +use Zend\Cache; +use Zend\Config\Config as ZendConfig; /** * @category Zend @@ -37,15 +32,15 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_CoreTest extends PHPUnit_Framework_TestCase +class CoreTest extends \PHPUnit_Framework_TestCase { private $_instance; public function setUp() { if (!$this->_instance) { - $this->_instance = new Zend_Cache_Core(array()); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance = new Cache\Core(array()); + $this->_backend = new Cache\Backend\Test(); $this->_instance->setBackend($this->_backend); } } @@ -57,7 +52,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Core(array('lifetime' => 3600, 'caching' => true)); + $test = new Cache\Core(array('lifetime' => 3600, 'caching' => true)); } /** @@ -65,8 +60,8 @@ public function testConstructorCorrectCall() */ public function testConstructorCorrectCallWithZendConfig() { - $test = new Zend_Cache_Core( - new Zend_Config(array('lifetime' => 3600, 'caching' => true)) + $test = new Cache\Core( + new ZendConfig(array('lifetime' => 3600, 'caching' => true)) ); } @@ -75,8 +70,8 @@ public function testConstructorCorrectCallWithZendConfig() */ public function testSettingOptionsWithZendConfig() { - $config = new Zend_Config(array('lifetime' => 3600, 'caching' => true)); - $test = new Zend_Cache_Core(); + $config = new ZendConfig(array('lifetime' => 3600, 'caching' => true)); + $test = new Cache\Core(); $test->setConfig($config); $this->assertEquals(3600, $test->getOption('lifetime')); } @@ -86,8 +81,8 @@ public function testSettingOptionsWithZendConfig() */ public function testSettingLifetimeAsEmptyIsInterpretedAsNull() { - $config = new Zend_Config(array('lifetime' => '', 'caching' => true)); - $test = new Zend_Cache_Core(); + $config = new ZendConfig(array('lifetime' => '', 'caching' => true)); + $test = new Cache\Core(); $test->setConfig($config); $this->assertSame(NULL, $test->getOption('lifetime')); } @@ -95,11 +90,11 @@ public function testSettingLifetimeAsEmptyIsInterpretedAsNull() public function testConstructorBadOption() { try { - $test = new Zend_Cache_Core(array(0 => 'bar', 'lifetime' => 3600)); - } catch (Zend_Cache_Exception $e) { + $test = new Cache\Core(array(0 => 'bar', 'lifetime' => 3600)); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSetLifeTime() @@ -109,13 +104,13 @@ public function testSetLifeTime() public function testSetBackendCorrectCall1() { - $backend = new Zend_Cache_Backend_File(array()); + $backend = new Cache\Backend\File(array()); $this->_instance->setBackend($backend); } public function testSetBackendCorrectCall2() { - $backend = new Zend_Cache_Backend_Test(array()); + $backend = new Cache\Backend\Test(array()); $this->_instance->setBackend($backend); $log = $backend->getLastLog(); $this->assertEquals('setDirectives', $log['methodName']); @@ -131,10 +126,10 @@ public function testSetOptionBadCall() { try { $this->_instance->setOption(array('lifetime'), 1200); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } /** @@ -147,14 +142,14 @@ public function testSetOptionUnknownOption() { try { $this->_instance->setOption(0, 1200); - $this->fail('Zend_Cache_Exception was expected but not thrown'); - } catch (Zend_Cache_Exception $e) { + $this->fail('Cache\Exception was expected but not thrown'); + } catch (Cache\Exception $e) { } try { $this->_instance->setOption('foo', 1200); - } catch (Zend_Cache_Exception $e) { - $this->fail('Zend_Cache_Exception was thrown but should not have been'); + } catch (Cache\Exception $e) { + $this->fail('Cache\Exception was thrown but should not have been'); } } @@ -162,60 +157,60 @@ public function testSaveCorrectBadCall1() { try { $this->_instance->save('data', 'foo bar'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveCorrectBadCall2() { try { $this->_instance->save('data', 'foobar', array('tag1', 'foo bar')); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveCorrectBadCall3() { try { $this->_instance->save(array('data'), 'foobar'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveWithABadCacheId() { try { $this->_instance->save(array('data'), true); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveWithABadCacheId2() { try { $this->_instance->save(array('data'), 'internal_foo'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveWithABadTags() { try { $this->_instance->save(array('data'), 'foo', 'foobar'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveCorrectCallNoCaching() @@ -337,10 +332,10 @@ public function testTestBadCall() { try { $this->_instance->test('foo bar'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testTestCorrectCall1() @@ -377,10 +372,10 @@ public function testGetBadCall() { try { $res = $this->_instance->load('foo bar'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testGetCorrectCall1() @@ -406,10 +401,10 @@ public function testRemoveBadCall() { try { $res = $this->_instance->remove('foo bar'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testRemoveCorrectCallNoCaching() @@ -440,20 +435,20 @@ public function testCleanBadCall1() { try { $res = $this->_instance->clean('matchingTag', array('foo bar', 'foo')); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testCleanBadCall2() { try { $res = $this->_instance->clean('foo'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testCleanCorrectCallNoCaching() diff --git a/test/FactoryException.php b/test/FactoryException.php index a00255a3f..bf94ce6c1 100644 --- a/test/FactoryException.php +++ b/test/FactoryException.php @@ -20,6 +20,8 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; /** * @category Zend @@ -28,34 +30,34 @@ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Zend_Cache_FactoryException extends PHPUnit_Extensions_ExceptionTestCase +class FactoryException extends \PHPUnit_Extensions_ExceptionTestCase { function setUp(){ - $this->setExpectedException('Zend_Cache_Exception'); + $this->setExpectedException('Cache\Exception'); } public function testBadFrontend() { - Zend_Cache::factory('badFrontend', 'File'); + Cache\Cache::factory('badFrontend', 'File'); } public function testBadBackend() { - Zend_Cache::factory('Output', 'badBackend'); + Cache\Cache::factory('Output', 'badBackend'); } public function testFrontendBadParam() { - Zend_Cache::factory('badFrontend', 'File', array('badParam'=>true)); + Cache\Cache::factory('badFrontend', 'File', array('badParam'=>true)); } public function testBackendBadParam() { - Zend_Cache::factory('Output', 'badBackend', array(), array('badParam'=>true)); + Cache\Cache::factory('Output', 'badBackend', array(), array('badParam'=>true)); } public function testThrowMethod() { - Zend_Cache::throwException('test'); + Cache\Cache::throwException('test'); } } diff --git a/test/FactoryTest.php b/test/FactoryTest.php index 9484e9d12..3e72c3be7 100644 --- a/test/FactoryTest.php +++ b/test/FactoryTest.php @@ -20,20 +20,14 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ - +namespace ZendTest\Cache; +use Zend\Cache; -class Zend_Cache_Backend_FooBarTest extends Zend_Cache_Backend_File { } -class FooBarTestBackend extends Zend_Cache_Backend_File { } +class Zend_Cache_Backend_FooBarTest extends \Zend\Cache\Backend\File { } +class FooBarTestBackend extends \Zend\Cache\Backend\File { } -class Zend_Cache_Frontend_FooBarTest extends Zend_Cache_Core { } -class FooBarTestFrontend extends Zend_Cache_Core { } +class Zend_Cache_Frontend_FooBarTest extends \Zend\Cache\Core { } +class FooBarTestFrontend extends \Zend\Cache\Core { } /** * @category Zend @@ -43,7 +37,7 @@ class FooBarTestFrontend extends Zend_Cache_Core { } * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_FactoryTest extends PHPUnit_Framework_TestCase +class FactoryTest extends \PHPUnit_Framework_TestCase { public function setUp() @@ -56,38 +50,38 @@ public function tearDown() public function testFactoryCorrectCall() { - $generated_frontend = Zend_Cache::factory('Core', 'File'); - $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('Core', 'File'); + $this->assertEquals('Cache\Cache_Core', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomBackend() { - $generated_frontend = Zend_Cache::factory('Core', 'FooBarTest', array(), array(), false, false, true); - $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('Core', 'FooBarTest', array(), array(), false, false, true); + $this->assertEquals('Cache\Cache_Core', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomBackend2() { - $generated_frontend = Zend_Cache::factory('Core', 'FooBarTestBackend', array(), array(), false, true, true); - $this->assertEquals('Zend_Cache_Core', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('Core', 'FooBarTestBackend', array(), array(), false, true, true); + $this->assertEquals('Cache\Cache_Core', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomFrontend() { - $generated_frontend = Zend_Cache::factory('FooBarTest', 'File', array(), array(), false, false, true); - $this->assertEquals('Zend_Cache_Frontend_FooBarTest', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('FooBarTest', 'File', array(), array(), false, false, true); + $this->assertEquals('Cache\Cache_Frontend_FooBarTest', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomFrontend2() { - $generated_frontend = Zend_Cache::factory('FooBarTestFrontend', 'File', array(), array(), true, false, true); + $generated_frontend = Cache\Cache::factory('FooBarTestFrontend', 'File', array(), array(), true, false, true); $this->assertEquals('FooBarTestFrontend', get_class($generated_frontend)); } public function testFactoryLoadsPlatformBackend() { try { - $cache = Zend_Cache::factory('Core', 'Zend-Platform'); - } catch (Zend_Cache_Exception $e) { + $cache = Cache\Cache::factory('Core', 'Zend-Platform'); + } catch (Cache\Exception $e) { $message = $e->getMessage(); if (strstr($message, 'Incorrect backend')) { $this->fail('Zend Platform is a valid backend'); @@ -98,8 +92,8 @@ public function testFactoryLoadsPlatformBackend() public function testBadFrontend() { try { - Zend_Cache::factory('badFrontend', 'File'); - } catch (Zend_Exception $e) { + Cache\Cache::factory('badFrontend', 'File'); + } catch (Cache\Exception $e) { return; } $this->fail('Zend_Exception was expected but not thrown'); @@ -108,8 +102,8 @@ public function testBadFrontend() public function testBadBackend() { try { - Zend_Cache::factory('Output', 'badBackend'); - } catch (Zend_Exception $e) { + Cache\Cache::factory('Output', 'badBackend'); + } catch (Cache\Exception $e) { return; } $this->fail('Zend_Exception was expected but not thrown'); diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php index 94b6ffaa9..c4c07026c 100644 --- a/test/FileBackendTest.php +++ b/test/FileBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,7 +31,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_FileBackendTest extends Zend_Cache_TestCommonExtendedBackend +class FileBackendTest extends TestCommonExtendedBackend { protected $_instance; @@ -37,18 +40,18 @@ class Zend_Cache_FileBackendTest extends Zend_Cache_TestCommonExtendedBackend public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_File', $data, $dataName); + parent::__construct('Zend\Cache\Backend\File', $data, $dataName); } public function setUp($notag = false) { $this->mkdir(); $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; - $this->_instance = new Zend_Cache_Backend_File(array( + $this->_instance = new Cache\Backend\File(array( 'cache_dir' => $this->_cache_dir, )); - $logger = new Zend_Log(new Zend_Log_Writer_Null()); + $logger = new \Zend\Log\Logger(new \Zend\Log\Writer\Null()); $this->_instance->setDirectives(array('logger' => $logger)); parent::setUp($notag); @@ -62,19 +65,19 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_File(array()); + $test = new Cache\Backend\File(array()); } public function testConstructorWithABadFileNamePrefix() { try { - $class = new Zend_Cache_Backend_File(array( + $class = new Cache\Backend\File(array( 'file_name_prefix' => 'foo bar' )); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testGetWithANonExistingCacheIdAndANullLifeTime() diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php index 300b30f54..efeadfc83 100644 --- a/test/FileFrontendTest.php +++ b/test/FileFrontendTest.php @@ -20,13 +20,8 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ +namespace ZendTest\Cache; +use Zend\Cache; /** * @category Zend @@ -36,7 +31,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_FileFrontendTest extends PHPUnit_Framework_TestCase { +class FileFrontendTest extends \PHPUnit_Framework_TestCase { private $_instance1; private $_instance2; @@ -60,28 +55,28 @@ public function setUp() } if (!$this->_instance1) { touch($this->_masterFile, 123455); - $this->_instance1 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance1 = new Cache\Frontend\File(array('master_file' => $this->_masterFile)); + $this->_backend = new Cache\Backend\Test(); $this->_instance1->setBackend($this->_backend); } if (!$this->_instance2) { touch($this->_masterFile); - $this->_instance2 = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile)); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance2 = new Cache\Frontend\File(array('master_file' => $this->_masterFile)); + $this->_backend = new Cache\Backend\Test(); $this->_instance2->setBackend($this->_backend); } if (!$this->_instance3) { touch($this->_masterFile1, 123455); touch($this->_masterFile2, 123455); - $this->_instance3 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance3 = new Cache\Frontend\File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); + $this->_backend = new Cache\Backend\Test(); $this->_instance3->setBackend($this->_backend); } if (!$this->_instance4) { touch($this->_masterFile1); touch($this->_masterFile2); - $this->_instance4 = new Zend_Cache_Frontend_File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance4 = new Cache\Frontend\File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); + $this->_backend = new Cache\Backend\Test(); $this->_instance4->setBackend($this->_backend); } } @@ -136,29 +131,29 @@ private function _getTmpDirUnix() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 'lifetime' => 3600, 'caching' => true)); + $test = new Cache\Frontend\File(array('master_file' => $this->_masterFile, 'lifetime' => 3600, 'caching' => true)); } public function testConstructorBadCall1() { # no masterfile try { - $test = new Zend_Cache_Frontend_File(array('lifetime' => 3600, 'caching' => true)); - } catch (Zend_Cache_Exception $e) { + $test = new Cache\Frontend\File(array('lifetime' => 3600, 'caching' => true)); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testConstructorBadCall2() { # incorrect option try { - $test = new Zend_Cache_Frontend_File(array('master_file' => $this->_masterFile, 0 => 3600)); - } catch (Zend_Cache_Exception $e) { + $test = new Cache\Frontend\File(array('master_file' => $this->_masterFile, 0 => 3600)); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testTestCorrectCall1() @@ -204,11 +199,11 @@ public function testGetCorrectCall3() public function testConstructorWithABadMasterFile() { try { - $instance = new Zend_Cache_Frontend_File(array('master_file' => '/foo/bar/ljhfdjh/qhskldhqjk')); - } catch (Zend_Cache_Exception $e) { + $instance = new Cache\Frontend\File(array('master_file' => '/foo/bar/ljhfdjh/qhskldhqjk')); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testGetWithDoNotTestCacheValidity() diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index 3648851de..5b820ccfd 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -20,13 +20,8 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ +namespace ZendTest\Cache; +use Zend\Cache; function foobar($param1, $param2) { echo "foobar_output($param1, $param2)"; @@ -41,15 +36,16 @@ function foobar($param1, $param2) { * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_FunctionFrontendTest extends PHPUnit_Framework_TestCase { +class FunctionFrontendTest extends \PHPUnit_Framework_TestCase +{ private $_instance; public function setUp() { if (!$this->_instance) { - $this->_instance = new Zend_Cache_Frontend_Function(array()); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance = new Cache\Frontend\FunctionFrontend(array()); + $this->_backend = new Cache\Backend\Test(); $this->_instance->setBackend($this->_backend); } } @@ -65,7 +61,7 @@ public function testConstructorCorrectCall() 'cache_by_default' => false, 'cached_functions' => array('foo', 'bar') ); - $test = new Zend_Cache_Frontend_Function($options); + $test = new Cache\Frontend\FunctionFrontend($options); } public function testConstructorBadCall() @@ -75,11 +71,11 @@ public function testConstructorBadCall() 0 => array('foo', 'bar') ); try { - $test = new Zend_Cache_Frontend_Function($options); - } catch (Zend_Cache_Exception $e) { + $test = new Cache\Frontend\FunctionFrontend($options); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testCallCorrectCall1() @@ -156,20 +152,20 @@ public function testCallWithABadSyntax1() { try { $this->_instance->call(1, array()); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testCallWithABadSyntax2() { try { $this->_instance->call('foo', 1); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } } diff --git a/test/ManagerTest.php b/test/ManagerTest.php index bcf9a8694..8008c3c77 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -18,7 +18,9 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ - + +namespace ZendTest\Cache; +use Zend\Cache; /** * @category Zend_Cache @@ -26,13 +28,13 @@ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Zend_Cache_ManagerTest extends PHPUnit_Framework_TestCase +class ManagerTest extends \PHPUnit_Framework_TestCase { public function setUp() { $this->_cache_dir = $this->mkdir(); - $this->_cache = Zend_Cache::factory( + $this->_cache = Cache\Cache::factory( 'Core', 'File', array('automatic_serialization'=>true), array('cache_dir'=>$this->_cache_dir) @@ -47,14 +49,14 @@ public function tearDown() public function testSetsCacheObject() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $manager->setCache('cache1', $this->_cache); - $this->assertTrue($manager->getCache('cache1') instanceof Zend_Cache_Core); + $this->assertTrue($manager->getCache('cache1') instanceof Cache\Core); } public function testLazyLoadsDefaultPageCache() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( @@ -63,12 +65,12 @@ public function testLazyLoadsDefaultPageCache() ) )); $cache = $manager->getCache('page'); - $this->assertTrue($cache instanceof Zend_Cache_Core); + $this->assertTrue($cache instanceof Cache\Core); } public function testCanOverrideCacheFrontendNameConfiguration() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( @@ -81,13 +83,13 @@ public function testCanOverrideCacheFrontendNameConfiguration() 'name'=> 'Page' ) )); - $this->assertTrue($manager->getCache('page') instanceof Zend_Cache_Frontend_Page); + $this->assertTrue($manager->getCache('page') instanceof Cache\Frontend\Page); } public function testCanMergeTemplateCacheOptionsFromZendConfig() { - $manager = new Zend_Cache_Manager; - $config = new Zend_Config(array( + $manager = new Cache\Manager; + $config = new \Zend\Config\Config(array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir @@ -101,7 +103,7 @@ public function testCanMergeTemplateCacheOptionsFromZendConfig() public function testCanOverrideCacheBackendendNameConfiguration() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( @@ -114,12 +116,12 @@ public function testCanOverrideCacheBackendendNameConfiguration() 'name'=> 'File' ) )); - $this->assertTrue($manager->getCache('page')->getBackend() instanceof Zend_Cache_Backend_File); + $this->assertTrue($manager->getCache('page')->getBackend() instanceof Cache\Backend\File); } public function testCanOverrideCacheFrontendOptionsConfiguration() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $manager->setTemplateOptions('page', array( 'frontend' => array( 'options'=> array( @@ -133,7 +135,7 @@ public function testCanOverrideCacheFrontendOptionsConfiguration() public function testCanOverrideCacheBackendOptionsConfiguration() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $manager->setTemplateOptions('page', array( 'backend' => array( 'options'=> array( @@ -147,7 +149,7 @@ public function testCanOverrideCacheBackendOptionsConfiguration() public function testSetsConfigTemplate() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $config = array( 'frontend' => array( 'name' => 'Core', @@ -168,7 +170,7 @@ public function testSetsConfigTemplate() public function testSetsConfigTemplateWithoutMultipartNameNormalisation() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $config = array( 'frontend' => array( 'name' => 'Core', @@ -186,7 +188,7 @@ public function testSetsConfigTemplateWithoutMultipartNameNormalisation() public function testSetsOptionsTemplateUsingZendConfig() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $config = array( 'frontend' => array( 'name' => 'Core', @@ -201,24 +203,24 @@ public function testSetsOptionsTemplateUsingZendConfig() ) ) ); - $manager->setCacheTemplate('myCache', new Zend_Config($config)); + $manager->setCacheTemplate('myCache', new \Zend\Config\Config($config)); $this->assertSame($config, $manager->getCacheTemplate('myCache')); } public function testConfigTemplatesDetectedAsAvailableCaches() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $this->assertTrue($manager->hasCache('page')); } public function testGettingPageCacheAlsoCreatesTagCache() { - $manager = new Zend_Cache_Manager; + $manager = new Cache\Manager; $pagetagConfig = $manager->getCacheTemplate('pagetag'); $pagetagConfig['backend']['options']['cache_dir'] = $this->getTmpDir(); $manager->setCacheTemplate('pagetag', $pagetagConfig); $pagetag = $manager->getCache('page')->getBackend()->getOption('tag_cache'); - $this->assertTrue($pagetag instanceof Zend_Cache_Core); + $this->assertTrue($pagetag instanceof Cache\Core); } // Helper Methods diff --git a/test/MemcachedBackendTest.php b/test/MemcachedBackendTest.php index 1d7bea895..f5e0324e1 100644 --- a/test/MemcachedBackendTest.php +++ b/test/MemcachedBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,14 +31,14 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_MemcachedBackendTest extends Zend_Cache_TestCommonExtendedBackend +class MemcachedBackendTest extends TestCommonExtendedBackend { protected $_instance; public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_Memcached', $data, $dataName); + parent::__construct('Zend\Cache\Backend\Memcached', $data, $dataName); } public function setUp($notag = true) @@ -56,7 +59,7 @@ public function setUp($notag = true) $options = array( 'servers' => array($serverValid, $serverFail) ); - $this->_instance = new Zend_Cache_Backend_Memcached($options); + $this->_instance = new Cache\Backend\Memcached($options); parent::setUp($notag); } @@ -70,7 +73,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Memcached(); + $test = new Cache\Backend\Memcached(); } public function testCleanModeOld() @@ -113,7 +116,7 @@ public function testConstructorWithAnAlternativeSyntax() $options = array( 'servers' => $server ); - $this->_instance = new Zend_Cache_Backend_Memcached($options); + $this->_instance = new Cache\Backend\Memcached($options); $this->testGetWithAnExistingCacheIdAndUTFCharacters(); } diff --git a/test/OutputFrontendTest.php b/test/OutputFrontendTest.php index 71b96de83..42fb649d8 100644 --- a/test/OutputFrontendTest.php +++ b/test/OutputFrontendTest.php @@ -20,13 +20,7 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ +namespace ZendTest\Cache; /** * @category Zend @@ -36,15 +30,15 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_OutputFrontendTest extends PHPUnit_Framework_TestCase { +class Zend_Cache_OutputFrontendTest extends \PHPUnit_Framework_TestCase { private $_instance; public function setUp() { if (!$this->_instance) { - $this->_instance = new Zend_Cache_Frontend_Output(array()); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance = new Cache\Frontend\Output(array()); + $this->_backend = new Cache\Backend\Test(); $this->_instance->setBackend($this->_backend); } } @@ -56,7 +50,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Frontend_Output(array('lifetime' => 3600, 'caching' => true)); + $test = new Cache\Frontend\Output(array('lifetime' => 3600, 'caching' => true)); } public function testStartEndCorrectCall1() diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php index 25eb37676..dcbe40b23 100644 --- a/test/PageFrontendTest.php +++ b/test/PageFrontendTest.php @@ -20,13 +20,8 @@ * @version $Id$ */ -/** - * Zend_Cache - */ - -/** - * PHPUnit test case - */ +namespace ZendTest\Cache; +use Zend\Cache; /** * @category Zend @@ -36,15 +31,15 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_PageFrontendTest extends PHPUnit_Framework_TestCase { +class PageFrontendTest extends \PHPUnit_Framework_TestCase { private $_instance; public function setUp() { if (!$this->_instance) { - $this->_instance = new Zend_Cache_Frontend_Page(array()); - $this->_backend = new Zend_Cache_Backend_Test(); + $this->_instance = new Cache\Frontend\Page(array()); + $this->_backend = new Cache\Backend\Test(); $this->_instance->setBackend($this->_backend); } } @@ -56,27 +51,27 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Frontend_Page(array('lifetime' => 3600, 'caching' => true)); + $test = new Cache\Frontend\Page(array('lifetime' => 3600, 'caching' => true)); } public function testConstructorUnimplementedOption() { try { - $test = new Zend_Cache_Frontend_Page(array('http_conditional' => true)); + $test = new Cache\Frontend\Page(array('http_conditional' => true)); } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testConstructorWithBadDefaultOptions() { try { - $test = new Zend_Cache_Frontend_Page(array('default_options' => 'foo')); + $test = new Cache\Frontend\Page(array('default_options' => 'foo')); } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } /** @@ -86,31 +81,31 @@ public function testConstructorWithBadDefaultOptions() public function testConstructorWithBadDefaultOptions2() { try { - $test = new Zend_Cache_Frontend_Page(array('default_options' => array('cache' => true, 1 => 'bar'))); + $test = new Cache\Frontend\Page(array('default_options' => array('cache' => true, 1 => 'bar'))); } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testConstructorWithBadRegexps() { try { - $test = new Zend_Cache_Frontend_Page(array('regexps' => 'foo')); + $test = new Cache\Frontend\Page(array('regexps' => 'foo')); } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testConstructorWithBadRegexps2() { try { - $test = new Zend_Cache_Frontend_Page(array('regexps' => array('foo', 'bar'))); + $test = new Cache\Frontend\Page(array('regexps' => array('foo', 'bar'))); } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } /** @@ -130,11 +125,11 @@ public function testConstructorWithBadRegexps3() ) ); try { - $test = new Zend_Cache_Frontend_Page(array('regexps' => $array)); + $test = new Cache\Frontend\Page(array('regexps' => $array)); } catch (Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testConstructorWithGoodRegexps() @@ -149,12 +144,12 @@ public function testConstructorWithGoodRegexps() 'make_id_with_post_variables' => true, ) ); - $test = new Zend_Cache_Frontend_Page(array('regexps' => $array)); + $test = new Cache\Frontend\Page(array('regexps' => $array)); } public function testConstructorWithGoodDefaultOptions() { - $test = new Zend_Cache_Frontend_Page(array('default_options' => array('cache' => true))); + $test = new Cache\Frontend\Page(array('default_options' => array('cache' => true))); } public function testStartEndCorrectCall1() diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php index ca05ce83b..fe6243ba2 100644 --- a/test/SqliteBackendTest.php +++ b/test/SqliteBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,7 +31,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_SqliteBackendTest extends Zend_Cache_TestCommonExtendedBackend +class Zend_Cache_SqliteBackendTest extends TestCommonExtendedBackend { protected $_instance; @@ -43,7 +46,7 @@ public function setUp($notag = false) { @mkdir($this->getTmpDir()); $this->_cache_dir = $this->getTmpDir() . DIRECTORY_SEPARATOR; - $this->_instance = new Zend_Cache_Backend_Sqlite(array( + $this->_instance = new Cache\Backend\Sqlite(array( 'cache_db_complete_path' => $this->_cache_dir . 'cache.db' )); parent::setUp($notag); @@ -59,22 +62,22 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Sqlite(array('cache_db_complete_path' => $this->_cache_dir . 'cache.db')); + $test = new Cache\Backend\Sqlite(array('cache_db_complete_path' => $this->_cache_dir . 'cache.db')); } public function testConstructorWithABadDBPath() { try { - $test = new Zend_Cache_Backend_Sqlite(array('cache_db_complete_path' => '/foo/bar/lfjlqsdjfklsqd/cache.db')); - } catch (Zend_Cache_Exception $e) { + $test = new Cache\Backend\Sqlite(array('cache_db_complete_path' => '/foo/bar/lfjlqsdjfklsqd/cache.db')); + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testCleanModeAllWithVacuum() { - $this->_instance = new Zend_Cache_Backend_Sqlite(array( + $this->_instance = new Cache\Backend\Sqlite(array( 'cache_db_complete_path' => $this->_cache_dir . 'cache.db', 'automatic_vacuum_factor' => 1 )); @@ -86,7 +89,7 @@ public function testCleanModeAllWithVacuum() public function testRemoveCorrectCallWithVacuum() { - $this->_instance = new Zend_Cache_Backend_Sqlite(array( + $this->_instance = new Cache\Backend\Sqlite(array( 'cache_db_complete_path' => $this->_cache_dir . 'cache.db', 'automatic_vacuum_factor' => 1 )); diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index bb76f2722..04a4af42e 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -4,11 +4,14 @@ * @subpackage UnitTests */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @package Zend_Cache * @subpackage UnitTests */ -class Zend_Cache_StaticBackendTest extends Zend_Cache_TestCommonBackend +class Zend_Cache_StaticBackendTest extends TestCommonBackend { protected $_instance; @@ -19,7 +22,7 @@ class Zend_Cache_StaticBackendTest extends Zend_Cache_TestCommonBackend public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_Static', $data, $dataName); + parent::__construct('\Zend\Cache\Backend\Static', $data, $dataName); } public function setUp($notag = false) @@ -28,15 +31,15 @@ public function setUp($notag = false) $this->_cache_dir = $this->mkdir(); @mkdir($this->_cache_dir.'/tags'); - $this->_innerCache = Zend_Cache::factory('Core','File', + $this->_innerCache = Cache\Cache::factory('Core','File', array('automatic_serialization'=>true), array('cache_dir'=>$this->_cache_dir.'/tags') ); - $this->_instance = new Zend_Cache_Backend_Static(array( + $this->_instance = new Cache\Backend\StaticBackend(array( 'public_dir' => $this->_cache_dir, 'tag_cache' => $this->_innerCache )); - $logger = new Zend_Log(new Zend_Log_Writer_Null()); + $logger = new \Zend\Log\Logger(new \Zend\Log\Writer\Null()); $this->_instance->setDirectives(array('logger' => $logger)); $this->_requestUriOld = @@ -60,7 +63,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Static(array()); + $test = new Cache\Backend\StaticBackend(array()); } public function testRemoveCorrectCall() @@ -73,8 +76,8 @@ public function testRemoveCorrectCall() public function testOptionsSetTagCache() { - $test = new Zend_Cache_Backend_Static(array('tag_cache'=>$this->_innerCache)); - $this->assertTrue($test->getInnerCache() instanceof Zend_Cache_Core); + $test = new Cache\Backend\StaticBackend(array('tag_cache'=>$this->_innerCache)); + $this->assertTrue($test->getInnerCache() instanceof Cache\Core); } public function testSaveCorrectCall() diff --git a/test/TestCommonBackend.php b/test/TestCommonBackend.php index 446f39428..49f8be83d 100644 --- a/test/TestCommonBackend.php +++ b/test/TestCommonBackend.php @@ -20,8 +20,7 @@ * @version $Id$ */ - -PHPUnit_Util_Filter::addFileToFilter(__FILE__); +namespace ZendTest\Cache; /** * PHPUnit test case @@ -35,7 +34,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -abstract class Zend_Cache_TestCommonBackend extends PHPUnit_Framework_TestCase +abstract class TestCommonBackend extends \PHPUnit_Framework_TestCase { protected $_instance; @@ -113,10 +112,10 @@ public function testConstructorBadOption() try { $class = $this->_className; $test = new $class(array(1 => 'bar')); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSetDirectivesCorrectCall() @@ -128,10 +127,10 @@ public function testSetDirectivesBadArgument() { try { $this->_instance->setDirectives('foo'); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSetDirectivesBadDirective() @@ -145,10 +144,10 @@ public function testSetDirectivesBadDirective2() { try { $this->_instance->setDirectives(array('foo' => true, 12 => 3600)); - } catch (Zend_Cache_Exception $e) { + } catch (Cache\Exception $e) { return; } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + $this->fail('Cache\Exception was expected but not thrown'); } public function testSaveCorrectCall() diff --git a/test/TestCommonExtendedBackend.php b/test/TestCommonExtendedBackend.php index e6bf9d14e..b4a3bd6f8 100644 --- a/test/TestCommonExtendedBackend.php +++ b/test/TestCommonExtendedBackend.php @@ -20,8 +20,7 @@ * @version $Id$ */ - -PHPUnit_Util_Filter::addFileToFilter(__FILE__); +namespace ZendTest\Cache; /** * @category Zend @@ -31,7 +30,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_TestCommonExtendedBackend extends Zend_Cache_TestCommonBackend +class TestCommonExtendedBackend extends TestCommonBackend { private $_capabilities; @@ -58,7 +57,7 @@ public function testGetFillingPercentage() public function testGetFillingPercentageOnEmptyBackend() { $this->_instance->setDirectives(array('logging' => false)); // ??? - $this->_instance->clean(Zend_Cache::CLEANING_MODE_ALL); + $this->_instance->clean(Cache\Cache::CLEANING_MODE_ALL); $res = $this->_instance->getFillingPercentage(); $this->_instance->setDirectives(array('logging' => true)); // ??? $this->assertTrue(is_integer($res)); diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php index bf1f4c7ed..93be115d8 100644 --- a/test/TwoLevelsBackendTest.php +++ b/test/TwoLevelsBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,7 +31,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_TwoLevelsBackendTest extends Zend_Cache_TestCommonExtendedBackend +class TwoLevelsBackendTest extends TestCommonExtendedBackend { protected $_instance; @@ -36,7 +39,7 @@ class Zend_Cache_TwoLevelsBackendTest extends Zend_Cache_TestCommonExtendedBacke public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_TwoLevels', $data, $dataName); + parent::__construct('Zend\Cache\Backend\TwoLevels', $data, $dataName); } public function setUp($notag = false) @@ -53,7 +56,7 @@ public function setUp($notag = false) ); $fastBackendOptions = array( ); - $this->_instance = new Zend_Cache_Backend_TwoLevels(array( + $this->_instance = new Cache\Backend\TwoLevels(array( 'fast_backend' => $fastBackend, 'slow_backend' => $slowBackend, 'fast_backend_options' => $fastBackendOptions, @@ -77,7 +80,7 @@ public function testConstructorCorrectCall() ); $fastBackendOptions = array( ); - $test = new Zend_Cache_Backend_TwoLevels(array( + $test = new Cache\Backend\TwoLevels(array( 'fast_backend' => $fastBackend, 'slow_backend' => $slowBackend, 'fast_backend_options' => $fastBackendOptions, diff --git a/test/XcacheBackendTest.php b/test/XcacheBackendTest.php index bfb987b8d..65a3e6d56 100644 --- a/test/XcacheBackendTest.php +++ b/test/XcacheBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,14 +31,14 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_XcacheBackendTest extends Zend_Cache_TestCommonBackend +class XcacheBackendTest extends TestCommonBackend { protected $_instance; public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_Xcache', $data, $dataName); + parent::__construct('Zend\Cache\Backend\Xcache', $data, $dataName); } public function setUp($notag = true) @@ -43,7 +46,7 @@ public function setUp($notag = true) if (!constant('TESTS_ZEND_CACHE_XCACHE_ENABLED')) { $this->markTestSkipped('Zend_Cache XCache tests not enabled'); } - $this->_instance = new Zend_Cache_Backend_Xcache(array( + $this->_instance = new Cache\Backend\Xcache(array( 'user' => TESTS_ZEND_CACHE_XCACHE_USER, 'password' => TESTS_ZEND_CACHE_XCACHE_PASSWORD )); @@ -58,7 +61,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_Xcache(); + $test = new Cache\Backend\Xcache(); } public function testCleanModeOld() { diff --git a/test/ZendPlatformBackendTest.php b/test/ZendPlatformBackendTest.php index 3c8cddee8..f68bc1f6b 100644 --- a/test/ZendPlatformBackendTest.php +++ b/test/ZendPlatformBackendTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,14 +31,14 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ZendPlatformBackendTest extends Zend_Cache_TestCommonBackend +class ZendPlatformBackendTest extends TestCommonBackend { protected $_instance; public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_ZendPlatform', $data, $dataName); + parent::__construct('Zend\Cache\Backend\ZendPlatform', $data, $dataName); } public function setUp($notag = false) @@ -44,7 +47,7 @@ public function setUp($notag = false) $this->markTestSkipped('Zend Platform is not installed, skipping test'); return; } - $this->_instance = new Zend_Cache_Backend_ZendPlatform(array()); + $this->_instance = new Cache\Backend\ZendPlatform(array()); parent::setUp($notag); } @@ -56,7 +59,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_ZendPlatform(); + $test = new Cache\Backend\ZendPlatform(); } public function testRemoveCorrectCall() diff --git a/test/ZendServerDiskTest.php b/test/ZendServerDiskTest.php index 75d61069a..80e342ec3 100755 --- a/test/ZendServerDiskTest.php +++ b/test/ZendServerDiskTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,14 +31,14 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ZendServerDiskTest extends Zend_Cache_TestCommonBackend +class ZendServerDiskTest extends TestCommonBackend { protected $_instance; public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_ZendServer_Disk', $data, $dataName); + parent::__construct('Zend\Cache\Backend\ZendServer\Disk', $data, $dataName); } public function setUp($notag = true) @@ -43,7 +46,7 @@ public function setUp($notag = true) if (!function_exists('zend_disk_cache_store')) { $this->markTestSkipped('Zend_Cache Zend Server disk backend tests not enabled'); } - $this->_instance = new Zend_Cache_Backend_ZendServer_Disk(); + $this->_instance = new Cache\Backend\ZendServer\Disk(); parent::setUp(true); } @@ -55,7 +58,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_ZendServer_Disk(); + $test = new Cache\Backend\ZendServer\Disk(); } public function testCleanModeOld() { diff --git a/test/ZendServerShMemTest.php b/test/ZendServerShMemTest.php index 1732bb72a..e08dc4746 100755 --- a/test/ZendServerShMemTest.php +++ b/test/ZendServerShMemTest.php @@ -20,6 +20,9 @@ * @version $Id$ */ +namespace ZendTest\Cache; +use Zend\Cache; + /** * @category Zend * @package Zend_Cache @@ -28,14 +31,14 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_ZendServerShMemTest extends Zend_Cache_TestCommonBackend +class ZendServerShMemTest extends TestCommonBackend { protected $_instance; public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_ZendServer_Disk', $data, $dataName); + parent::__construct('Zend\Cache\Backend\ZendServer\Disk', $data, $dataName); } public function setUp($notag = true) @@ -43,7 +46,7 @@ public function setUp($notag = true) if (!function_exists('zend_shm_cache_store')) { $this->markTestSkipped('Zend_Cache Zend Server ShMem backend tests not enabled'); } - $this->_instance = new Zend_Cache_Backend_ZendServer_ShMem(); + $this->_instance = new Cache\Backend\ZendServer\ShMem(); parent::setUp(true); } @@ -55,7 +58,7 @@ public function tearDown() public function testConstructorCorrectCall() { - $test = new Zend_Cache_Backend_ZendServer_ShMem(); + $test = new Cache\Backend\ZendServer\ShMem(); } public function testCleanModeOld() { From 17373ce73b7ff8d28f6b0df0c700e6cf6c631bc6 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 29 Mar 2010 13:25:05 -0400 Subject: [PATCH 075/311] fixed autoloader implementation so we can move forward --- src/Backend/BackendInterface.php | 2 +- test/CoreTest.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Backend/BackendInterface.php b/src/Backend/BackendInterface.php index 8fe1e46f1..bae29e57c 100644 --- a/src/Backend/BackendInterface.php +++ b/src/Backend/BackendInterface.php @@ -24,7 +24,7 @@ * @namespace */ namespace Zend\Cache\Backend; -use Zend\Cache; +use \Zend\Cache; /** * @package Zend_Cache diff --git a/test/CoreTest.php b/test/CoreTest.php index b6615bba4..cb3bd6b66 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -21,6 +21,7 @@ */ namespace ZendTest\Cache; + use Zend\Cache; use Zend\Config\Config as ZendConfig; From 5f6b766f6f44db3aa2c2fbdfb8e51805259bc6af Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 29 Mar 2010 14:26:57 -0400 Subject: [PATCH 076/311] [NS] Renamed Test backend to TestBackend; updated autoloader implementation for ZendTest --- src/Backend/{Test.php => TestBackend.php} | 2 +- test/CoreTest.php | 9 +++++---- test/FileFrontendTest.php | 12 +++++++----- test/FunctionFrontendTest.php | 6 ++++-- test/OutputFrontendTest.php | 5 ++++- test/PageFrontendTest.php | 6 ++++-- 6 files changed, 25 insertions(+), 15 deletions(-) rename src/Backend/{Test.php => TestBackend.php} (99%) diff --git a/src/Backend/Test.php b/src/Backend/TestBackend.php similarity index 99% rename from src/Backend/Test.php rename to src/Backend/TestBackend.php index 2a1769053..e6e1496af 100644 --- a/src/Backend/Test.php +++ b/src/Backend/TestBackend.php @@ -35,7 +35,7 @@ * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Test extends Backend implements ExtendedInterface +class TestBackend extends Backend implements ExtendedInterface { /** * Available options diff --git a/test/CoreTest.php b/test/CoreTest.php index cb3bd6b66..f49d23f0e 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -22,8 +22,9 @@ namespace ZendTest\Cache; -use Zend\Cache; -use Zend\Config\Config as ZendConfig; +use Zend\Cache, + Zend\Config\Config as ZendConfig, + Zend\Cache\Backend\TestBackend; /** * @category Zend @@ -41,7 +42,7 @@ public function setUp() { if (!$this->_instance) { $this->_instance = new Cache\Core(array()); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance->setBackend($this->_backend); } } @@ -111,7 +112,7 @@ public function testSetBackendCorrectCall1() public function testSetBackendCorrectCall2() { - $backend = new Cache\Backend\Test(array()); + $backend = new TestBackend(array()); $this->_instance->setBackend($backend); $log = $backend->getLastLog(); $this->assertEquals('setDirectives', $log['methodName']); diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php index efeadfc83..32de1b6a9 100644 --- a/test/FileFrontendTest.php +++ b/test/FileFrontendTest.php @@ -21,7 +21,9 @@ */ namespace ZendTest\Cache; -use Zend\Cache; + +use Zend\Cache, + Zend\Cache\Backend\TestBackend; /** * @category Zend @@ -56,27 +58,27 @@ public function setUp() if (!$this->_instance1) { touch($this->_masterFile, 123455); $this->_instance1 = new Cache\Frontend\File(array('master_file' => $this->_masterFile)); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance1->setBackend($this->_backend); } if (!$this->_instance2) { touch($this->_masterFile); $this->_instance2 = new Cache\Frontend\File(array('master_file' => $this->_masterFile)); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance2->setBackend($this->_backend); } if (!$this->_instance3) { touch($this->_masterFile1, 123455); touch($this->_masterFile2, 123455); $this->_instance3 = new Cache\Frontend\File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance3->setBackend($this->_backend); } if (!$this->_instance4) { touch($this->_masterFile1); touch($this->_masterFile2); $this->_instance4 = new Cache\Frontend\File(array('master_files' => array($this->_masterFile1, $this->_masterFile2))); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance4->setBackend($this->_backend); } } diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index 5b820ccfd..990cf9518 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -21,7 +21,9 @@ */ namespace ZendTest\Cache; -use Zend\Cache; + +use Zend\Cache, + Zend\Cache\Backend\TestBackend; function foobar($param1, $param2) { echo "foobar_output($param1, $param2)"; @@ -45,7 +47,7 @@ public function setUp() { if (!$this->_instance) { $this->_instance = new Cache\Frontend\FunctionFrontend(array()); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance->setBackend($this->_backend); } } diff --git a/test/OutputFrontendTest.php b/test/OutputFrontendTest.php index 42fb649d8..ddd95fa5f 100644 --- a/test/OutputFrontendTest.php +++ b/test/OutputFrontendTest.php @@ -22,6 +22,9 @@ namespace ZendTest\Cache; +use Zend\Cache, + Zend\Cache\Backend\TestBackend; + /** * @category Zend * @package Zend_Cache @@ -38,7 +41,7 @@ public function setUp() { if (!$this->_instance) { $this->_instance = new Cache\Frontend\Output(array()); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance->setBackend($this->_backend); } } diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php index dcbe40b23..8704f125a 100644 --- a/test/PageFrontendTest.php +++ b/test/PageFrontendTest.php @@ -21,7 +21,9 @@ */ namespace ZendTest\Cache; -use Zend\Cache; + +use Zend\Cache, + Zend\Cache\Backend\TestBackend; /** * @category Zend @@ -39,7 +41,7 @@ public function setUp() { if (!$this->_instance) { $this->_instance = new Cache\Frontend\Page(array()); - $this->_backend = new Cache\Backend\Test(); + $this->_backend = new TestBackend(); $this->_instance->setBackend($this->_backend); } } From eb74bc5726ad660acf887722ad79eed115710155 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 29 Mar 2010 15:27:56 -0400 Subject: [PATCH 077/311] [NS] Converted Zend_Locale to namespaces --- src/Cache.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Cache.php b/src/Cache.php index 5757f55bb..103385d39 100644 --- a/src/Cache.php +++ b/src/Cache.php @@ -131,9 +131,9 @@ public static function _makeBackend($backend, $backendOptions, $customBackendNam } if (in_array($backend, Cache::$standardBackends)) { // we use a standard backend - $backendClass = 'Zend_Cache_Backend_' . $backend; + $backendClass = 'Zend\\Cache\\Backend\\' . $backend; // security controls are explicit - require_once str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php'; + require_once str_replace('\\', DIRECTORY_SEPARATOR, $backendClass) . '.php'; } else { // we use a custom backend if (!preg_match('~^[\w]+$~D', $backend)) { @@ -141,12 +141,12 @@ public static function _makeBackend($backend, $backendOptions, $customBackendNam } if (!$customBackendNaming) { // we use this boolean to avoid an API break - $backendClass = 'Zend_Cache_Backend_' . $backend; + $backendClass = 'Zend\\Cache\\Backend\\' . $backend; } else { $backendClass = $backend; } if (!$autoload) { - $file = str_replace('_', DIRECTORY_SEPARATOR, $backendClass) . '.php'; + $file = str_replace('\\', DIRECTORY_SEPARATOR, $backendClass) . '.php'; if (!(self::_isReadable($file))) { self::throwException("file $file not found in include_path"); } @@ -173,9 +173,9 @@ public static function _makeFrontend($frontend, $frontendOptions = array(), $cus if (in_array($frontend, self::$standardFrontends)) { // we use a standard frontend // For perfs reasons, with frontend == 'Core', we can interact with the Core itself - $frontendClass = 'Zend_Cache_' . ($frontend != 'Core' ? 'Frontend_' : '') . $frontend; + $frontendClass = 'Zend\\Cache\\' . ($frontend != 'Core' ? 'Frontend\\' : '') . $frontend; // security controls are explicit - require_once str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; + require_once str_replace('\\', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; } else { // we use a custom frontend if (!preg_match('~^[\w]+$~D', $frontend)) { @@ -183,12 +183,12 @@ public static function _makeFrontend($frontend, $frontendOptions = array(), $cus } if (!$customFrontendNaming) { // we use this boolean to avoid an API break - $frontendClass = 'Zend_Cache_Frontend_' . $frontend; + $frontendClass = 'Zend\\Cache\\Frontend\\' . $frontend; } else { $frontendClass = $frontend; } if (!$autoload) { - $file = str_replace('_', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; + $file = str_replace('\\', DIRECTORY_SEPARATOR, $frontendClass) . '.php'; if (!(self::_isReadable($file))) { self::throwException("file $file not found in include_path"); } From 922bce752a5acc98bba042417b57c594010e92d7 Mon Sep 17 00:00:00 2001 From: Ralph Schindler Date: Mon, 29 Mar 2010 17:24:23 -0500 Subject: [PATCH 078/311] Zend_Cache namespace conversion plus running unit tests --- src/Backend/File.php | 4 ++-- src/Backend/Sqlite.php | 4 ++-- src/Backend/StaticBackend.php | 4 ++-- src/Backend/TestBackend.php | 10 +++++++++- src/Cache.php | 8 +++----- src/Core.php | 2 +- src/Manager.php | 7 +++++-- test/ClassFrontendTest.php | 6 +++--- test/FactoryClasses.php | 7 +++++++ test/FactoryTest.php | 23 ++++++++++------------- test/FileBackendTest.php | 2 +- test/FunctionFrontendTest.php | 6 +++--- test/PageFrontendTest.php | 12 ++++++------ test/SqliteBackendTest.php | 4 ++-- test/StaticBackendTest.php | 4 ++-- test/TestCommonBackend.php | 1 + test/TestCommonExtendedBackend.php | 1 + 17 files changed, 60 insertions(+), 45 deletions(-) create mode 100644 test/FactoryClasses.php diff --git a/src/Backend/File.php b/src/Backend/File.php index b16c4aa90..75193d122 100644 --- a/src/Backend/File.php +++ b/src/Backend/File.php @@ -279,7 +279,7 @@ public function remove($id) * @param tags array $tags array of tags * @return boolean true if no problem */ - public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\Cache::CLEANING_MODE_ALL, $tags = array()) { // We use this protected method to hide the recursive stuff clearstatcache(); @@ -636,7 +636,7 @@ protected function _remove($file) * @throws \Zend\Cache\Exception * @return boolean True if no problem */ - protected function _clean($dir, $mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) + protected function _clean($dir, $mode = Cache\Cache::CLEANING_MODE_ALL, $tags = array()) { if (!is_dir($dir)) { return false; diff --git a/src/Backend/Sqlite.php b/src/Backend/Sqlite.php index 46b7d9fa2..a9f2d8b82 100644 --- a/src/Backend/Sqlite.php +++ b/src/Backend/Sqlite.php @@ -213,7 +213,7 @@ public function remove($id) * @param array $tags Array of tags * @return boolean True if no problem */ - public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\Cache::CLEANING_MODE_ALL, $tags = array()) { $this->_checkAndBuildStructure(); $return = $this->_clean($mode, $tags); @@ -610,7 +610,7 @@ private function _checkStructureVersion() * @param array $tags Array of tags * @return boolean True if no problem */ - private function _clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) + private function _clean($mode = Cache\Cache::CLEANING_MODE_ALL, $tags = array()) { switch ($mode) { case Cache\Cache::CLEANING_MODE_ALL: diff --git a/src/Backend/StaticBackend.php b/src/Backend/StaticBackend.php index 151a216fe..2396138f7 100644 --- a/src/Backend/StaticBackend.php +++ b/src/Backend/StaticBackend.php @@ -376,7 +376,7 @@ public function removeRecursively($id) * @param array $tags Array of tags * @return boolean true if no problem */ - public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = array()) + public function clean($mode = Cache\Cache::CLEANING_MODE_ALL, $tags = array()) { $result = false; switch ($mode) { @@ -459,7 +459,7 @@ public function clean($mode = Cache\CacheCache\Cache::CLEANING_MODE_ALL, $tags = * @param \Zend\Cache\Core * @return void */ - public function setInnerCache(end\Cache\Core $cache) + public function setInnerCache(Cache\Core $cache) { $this->_tagCache = $cache; $this->_options['tag_cache'] = $cache; diff --git a/src/Backend/TestBackend.php b/src/Backend/TestBackend.php index e6e1496af..0f01c7d9d 100644 --- a/src/Backend/TestBackend.php +++ b/src/Backend/TestBackend.php @@ -104,7 +104,12 @@ public function load($id, $doNotTestCacheValidity = false) if ( $id == 'false' || $id == 'd8523b3ee441006261eeffa5c3d3a0a7' || $id == 'e83249ea22178277d5befc2c5e2e9ace' - || $id == '40f649b94977c0a6e76902e2a0b43587') + || $id == '40f649b94977c0a6e76902e2a0b43587' + || $id == 'ace7797c586c72fecc4d0d3413de4d57' + || $id == '574aea2816b51d1c8aa6d5fd0c1144ac' + || $id == 'c687b54c872594de4a635a94935ee4b5' + || $id == '90ed42644de581cc298d2a74e61de288' + ) { return false; } @@ -120,6 +125,9 @@ public function load($id, $doNotTestCacheValidity = false) if (($id=='8a02d218a5165c467e7a5747cc6bd4b6') or ($id=='648aca1366211d17cbf48e65dc570bee')) { return serialize(array('foo', 'bar')); } + if ($id=='f93593d664b080ec712db169cc41f50e' || $id == '263b963032376e23204188ea488bee2a') { + return serialize(array('foo', 'bar')); + } return 'foo'; } diff --git a/src/Cache.php b/src/Cache.php index 103385d39..e9b7d38ab 100644 --- a/src/Cache.php +++ b/src/Cache.php @@ -96,7 +96,7 @@ public static function factory($frontend, $backend, $frontendOptions = array(), if (is_string($backend)) { $backendObject = self::_makeBackend($backend, $backendOptions, $customBackendNaming, $autoload); } else { - if ((is_object($backend)) && (in_array('Zend_Cache_Backend_Interface', class_implements($backend)))) { + if ((is_object($backend)) && (in_array('Zend\\Cache\\Backend\\BackendInterface', class_implements($backend)))) { $backendObject = $backend; } else { self::throwException('backend must be a backend name (string) or an object which implements Zend_Cache_Backend_Interface'); @@ -141,7 +141,7 @@ public static function _makeBackend($backend, $backendOptions, $customBackendNam } if (!$customBackendNaming) { // we use this boolean to avoid an API break - $backendClass = 'Zend\\Cache\\Backend\\' . $backend; + $backendClass = '\\Zend\\Cache\\Backend\\' . $backend; } else { $backendClass = $backend; } @@ -183,7 +183,7 @@ public static function _makeFrontend($frontend, $frontendOptions = array(), $cus } if (!$customFrontendNaming) { // we use this boolean to avoid an API break - $frontendClass = 'Zend\\Cache\\Frontend\\' . $frontend; + $frontendClass = '\\Zend\\Cache\\Frontend\\' . $frontend; } else { $frontendClass = $frontend; } @@ -207,8 +207,6 @@ public static function _makeFrontend($frontend, $frontendOptions = array(), $cus */ public static function throwException($msg, \Exception $e = null) { - // For perfs reasons, we use this dynamic inclusion - require_once 'Zend/Cache/Exception.php'; throw new Exception($msg, 0, $e); } diff --git a/src/Core.php b/src/Core.php index 860a2c523..ef5d53091 100644 --- a/src/Core.php +++ b/src/Core.php @@ -190,7 +190,7 @@ public function setBackend(Backend\Backend $backendObject) $directives[$directive] = $this->_options[$directive]; } $this->_backend->setDirectives($directives); - if (in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_backend))) { + if (in_array('Zend\Cache\Backend\ExtendedInterface', class_implements($this->_backend))) { $this->_extendedBackend = true; $this->_backendCapabilities = $this->_backend->getCapabilities(); } diff --git a/src/Manager.php b/src/Manager.php index e8cf78494..53245f3f7 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -94,7 +94,7 @@ class Manager ), ), 'backend' => array( - 'name' => 'Static', + 'name' => 'StaticBackend', 'options' => array( 'public_dir' => '../public', ), @@ -173,7 +173,10 @@ public function getCache($name) $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]['backend']['options']) ? $this->_optionTemplates[$name]['backend']['options'] : array(), + false, + false, + true ); return $this->_caches[$name]; } diff --git a/test/ClassFrontendTest.php b/test/ClassFrontendTest.php index 6c76dec6e..db07b2835 100644 --- a/test/ClassFrontendTest.php +++ b/test/ClassFrontendTest.php @@ -67,10 +67,10 @@ public function setUp() { if (!$this->_instance1) { $options1 = array( - 'cached_entity' => 'test' + 'cached_entity' => '\ZendTest\Cache\test' ); $this->_instance1 = new Cache\Frontend\ClassFrontend($options1); - $this->_backend1 = new Cache\Backend\Test(); + $this->_backend1 = new Cache\Backend\TestBackend(); $this->_instance1->setBackend($this->_backend1); } if (!$this->_instance2) { @@ -78,7 +78,7 @@ public function setUp() 'cached_entity' => new test() ); $this->_instance2 = new Cache\Frontend\ClassFrontend($options2); - $this->_backend2 = new Cache\Backend\Test(); + $this->_backend2 = new Cache\Backend\TestBackend(); $this->_instance2->setBackend($this->_backend2); } } diff --git a/test/FactoryClasses.php b/test/FactoryClasses.php new file mode 100644 index 000000000..53a1dcc54 --- /dev/null +++ b/test/FactoryClasses.php @@ -0,0 +1,7 @@ +markTestSkipped('Skipping test that duplicated Loader or PluginLoader efforts.'); } public function tearDown() @@ -51,31 +48,31 @@ public function tearDown() public function testFactoryCorrectCall() { $generated_frontend = Cache\Cache::factory('Core', 'File'); - $this->assertEquals('Cache\Cache_Core', get_class($generated_frontend)); + $this->assertEquals('Zend\Cache\Core', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomBackend() { $generated_frontend = Cache\Cache::factory('Core', 'FooBarTest', array(), array(), false, false, true); - $this->assertEquals('Cache\Cache_Core', get_class($generated_frontend)); + $this->assertEquals('Zend\Cache\Core', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomBackend2() { - $generated_frontend = Cache\Cache::factory('Core', 'FooBarTestBackend', array(), array(), false, true, true); - $this->assertEquals('Cache\Cache_Core', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('Core', '\ZendTest\Cache\FooBarTestBackend', array(), array(), false, true, true); + $this->assertEquals('Zend\Cache\Core', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomFrontend() { - $generated_frontend = Cache\Cache::factory('FooBarTest', 'File', array(), array(), false, false, true); - $this->assertEquals('Cache\Cache_Frontend_FooBarTest', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('\FooBarTest', 'File', array(), array(), false, false, true); + $this->assertEquals('ZendTest\Cache\Zend_Cache_Frontend_FooBarTest', get_class($generated_frontend)); } public function testFactoryCorrectCallWithCustomFrontend2() { - $generated_frontend = Cache\Cache::factory('FooBarTestFrontend', 'File', array(), array(), true, false, true); - $this->assertEquals('FooBarTestFrontend', get_class($generated_frontend)); + $generated_frontend = Cache\Cache::factory('\FooBarTestFrontend', 'File', array(), array(), true, false, true); + $this->assertEquals('ZendTest\Cache\FooBarTestFrontend', get_class($generated_frontend)); } public function testFactoryLoadsPlatformBackend() { diff --git a/test/FileBackendTest.php b/test/FileBackendTest.php index c4c07026c..24bcbb927 100644 --- a/test/FileBackendTest.php +++ b/test/FileBackendTest.php @@ -40,7 +40,7 @@ class FileBackendTest extends TestCommonExtendedBackend public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend\Cache\Backend\File', $data, $dataName); + parent::__construct('\Zend\Cache\Backend\File', $data, $dataName); } public function setUp($notag = false) diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index 990cf9518..48d0ea5d8 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -96,7 +96,7 @@ public function testCallCorrectCall2() { ob_start(); ob_implicit_flush(false); - $return = $this->_instance->call('foobar', array('param3', 'param4')); + $return = $this->_instance->call('\ZendTest\Cache\foobar', array('param3', 'param4')); $data = ob_get_contents(); ob_end_clean(); ob_implicit_flush(true); @@ -110,7 +110,7 @@ public function testCallCorrectCall3() $this->_instance->setOption('cache_by_default', false); ob_start(); ob_implicit_flush(false); - $return = $this->_instance->call('foobar', array('param1', 'param2')); + $return = $this->_instance->call('\ZendTest\Cache\foobar', array('param1', 'param2')); $data = ob_get_contents(); ob_end_clean(); ob_implicit_flush(true); @@ -142,7 +142,7 @@ public function testCallCorrectCall5() $this->_instance->setOption('non_cached_functions', array('foobar')); ob_start(); ob_implicit_flush(false); - $return = $this->_instance->call('foobar', array('param1', 'param2')); + $return = $this->_instance->call('\ZendTest\Cache\foobar', array('param1', 'param2')); $data = ob_get_contents(); ob_end_clean(); ob_implicit_flush(true); diff --git a/test/PageFrontendTest.php b/test/PageFrontendTest.php index 8704f125a..db070ab96 100644 --- a/test/PageFrontendTest.php +++ b/test/PageFrontendTest.php @@ -60,7 +60,7 @@ public function testConstructorUnimplementedOption() { try { $test = new Cache\Frontend\Page(array('http_conditional' => true)); - } catch (Exception $e) { + } catch (Cache\Exception $e) { return; } $this->fail('Cache\Exception was expected but not thrown'); @@ -70,7 +70,7 @@ public function testConstructorWithBadDefaultOptions() { try { $test = new Cache\Frontend\Page(array('default_options' => 'foo')); - } catch (Exception $e) { + } catch (Cache\Exception $e) { return; } $this->fail('Cache\Exception was expected but not thrown'); @@ -84,7 +84,7 @@ public function testConstructorWithBadDefaultOptions2() { try { $test = new Cache\Frontend\Page(array('default_options' => array('cache' => true, 1 => 'bar'))); - } catch (Exception $e) { + } catch (Cache\Exception $e) { return; } $this->fail('Cache\Exception was expected but not thrown'); @@ -94,7 +94,7 @@ public function testConstructorWithBadRegexps() { try { $test = new Cache\Frontend\Page(array('regexps' => 'foo')); - } catch (Exception $e) { + } catch (Cache\Exception $e) { return; } $this->fail('Cache\Exception was expected but not thrown'); @@ -104,7 +104,7 @@ public function testConstructorWithBadRegexps2() { try { $test = new Cache\Frontend\Page(array('regexps' => array('foo', 'bar'))); - } catch (Exception $e) { + } catch (Cache\Exception $e) { return; } $this->fail('Cache\Exception was expected but not thrown'); @@ -128,7 +128,7 @@ public function testConstructorWithBadRegexps3() ); try { $test = new Cache\Frontend\Page(array('regexps' => $array)); - } catch (Exception $e) { + } catch (Cache\Exception $e) { return; } $this->fail('Cache\Exception was expected but not thrown'); diff --git a/test/SqliteBackendTest.php b/test/SqliteBackendTest.php index fe6243ba2..d45581a3f 100644 --- a/test/SqliteBackendTest.php +++ b/test/SqliteBackendTest.php @@ -31,7 +31,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class Zend_Cache_SqliteBackendTest extends TestCommonExtendedBackend +class SqliteBackendTest extends TestCommonExtendedBackend { protected $_instance; @@ -39,7 +39,7 @@ class Zend_Cache_SqliteBackendTest extends TestCommonExtendedBackend public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('Zend_Cache_Backend_Sqlite', $data, $dataName); + parent::__construct('Zend\Cache\Backend\Sqlite', $data, $dataName); } public function setUp($notag = false) diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index 04a4af42e..7d429860a 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -11,7 +11,7 @@ * @package Zend_Cache * @subpackage UnitTests */ -class Zend_Cache_StaticBackendTest extends TestCommonBackend +class StaticBackendTest extends TestCommonBackend { protected $_instance; @@ -22,7 +22,7 @@ class Zend_Cache_StaticBackendTest extends TestCommonBackend public function __construct($name = null, array $data = array(), $dataName = '') { - parent::__construct('\Zend\Cache\Backend\Static', $data, $dataName); + parent::__construct('\Zend\Cache\Backend\StaticBackend', $data, $dataName); } public function setUp($notag = false) diff --git a/test/TestCommonBackend.php b/test/TestCommonBackend.php index 49f8be83d..f10b48833 100644 --- a/test/TestCommonBackend.php +++ b/test/TestCommonBackend.php @@ -21,6 +21,7 @@ */ namespace ZendTest\Cache; +use Zend\Cache; /** * PHPUnit test case diff --git a/test/TestCommonExtendedBackend.php b/test/TestCommonExtendedBackend.php index b4a3bd6f8..0db9f05a1 100644 --- a/test/TestCommonExtendedBackend.php +++ b/test/TestCommonExtendedBackend.php @@ -21,6 +21,7 @@ */ namespace ZendTest\Cache; +use Zend\Cache; /** * @category Zend From 9ef4e61091b0f23d0d6511ca9aa58ab002b6412b Mon Sep 17 00:00:00 2001 From: Alexander Veremyev Date: Tue, 6 Apr 2010 15:07:49 +0400 Subject: [PATCH 079/311] Added save method to Zend\Cache\Frontend interface. --- src/Frontend.php | 81 ++++++++++++++++++++++++++++-------------------- 1 file changed, 47 insertions(+), 34 deletions(-) diff --git a/src/Frontend.php b/src/Frontend.php index d567993ce..084ff333a 100644 --- a/src/Frontend.php +++ b/src/Frontend.php @@ -33,127 +33,140 @@ interface Frontend { /** * Set a frontend option - * - * @param string $name - * @param mixed $value + * + * @param string $name + * @param mixed $value * @return void */ public function setOption($name, $value); /** * Retrieve an option value - * - * @param string $name + * + * @param string $name * @return mixed */ public function getOption($name); /** * Set cache lifetime - * - * @param int $newLifetime + * + * @param int $newLifetime * @return void */ public function setLifetime($newLifetime); /** * Set the cache backend - * - * @param Backend $backendObject + * + * @param Backend $backendObject * @return void */ public function setBackend(Backend $backendObject); /** * Retrieve the cache backend - * + * * @return Backend */ public function getBackend(); /** * Load a cached item - * - * @param string $id - * @param bool $doNotTestCacheValidity - * @param bool $doNotUnserialize + * + * @param string $id + * @param bool $doNotTestCacheValidity + * @param bool $doNotUnserialize * @return mixed */ public function load($id, $doNotTestCacheValidity = false, $doNotUnserialize = false); /** * Test if a cache exists for a given identifier - * - * @param string $id + * + * @param string $id * @return bool */ public function 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); + /** * Remove a cached item - * - * @param string $id + * + * @param string $id * @return void */ public function remove($id); /** * Clean the cache of multiple or all items - * - * @param string $mode - * @param array $tags + * + * @param string $mode + * @param array $tags * @return void */ public function clean($mode = 'all', $tags = array()); /** * Retrieve all cache identifiers matching ALL the given tags - * - * @param array $tags + * + * @param array $tags * @return array */ public function getIdsMatchingTags($tags = array()); /** * Get cache identifiers matching NONE of the given tags - * - * @param array $tags + * + * @param array $tags * @return array */ public function getIdsNotMatchingTags($tags = array()); /** * Get cache identifiers matching ANY of the given tags - * - * @param array $tags + * + * @param array $tags * @return array */ public function getIdsMatchingAnyTags($tags = array()); /** * Get all cache identifiers - * + * * @return array */ public function getIds(); /** * Get all tags - * + * * @return array */ public function getTags(); /** * Retrieve the filling percentage of the backend storage - * + * * @return int */ public function getFillingPercentage(); /** * Retrieve all metadata for a given cache identifier - * + * * @param string $id * @return array */ @@ -161,9 +174,9 @@ public function getMetadatas($id); /** * Extend the lifetime of a given cache identifier - * - * @param string $id - * @param int $extraLifetime + * + * @param string $id + * @param int $extraLifetime * @return bool */ public function touch($id, $extraLifetime); From 16389beead6a3aaeb3bf647e055c2aa86ae5b233 Mon Sep 17 00:00:00 2001 From: mabe Date: Mon, 19 Apr 2010 17:43:37 +0000 Subject: [PATCH 080/311] ZF-9699: missed static backend tests on AllTests git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21949 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/AllTests.php | 1 + 1 file changed, 1 insertion(+) diff --git a/test/AllTests.php b/test/AllTests.php index 51f597c46..11a9d6045 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -68,6 +68,7 @@ public static function suite() $suite->addTestSuite('Zend_Cache_FactoryTest'); $suite->addTestSuite('Zend_Cache_CoreTest'); $suite->addTestSuite('Zend_Cache_FileBackendTest'); + $suite->addTestSuite('Zend_Cache_StaticBackendTest'); $suite->addTestSuite('Zend_Cache_OutputFrontendTest'); $suite->addTestSuite('Zend_Cache_FunctionFrontendTest'); $suite->addTestSuite('Zend_Cache_ClassFrontendTest'); From 04166db4ff304244a4d921dbacec802c4fa82bdc Mon Sep 17 00:00:00 2001 From: mabe Date: Mon, 19 Apr 2010 19:15:49 +0000 Subject: [PATCH 081/311] ZF-9705: TwoLevels backend didn't update fast cache if full git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21953 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/TwoLevels.php | 43 +++++++++++++++++++++++++++-------- test/TwoLevelsBackendTest.php | 27 ++++++++++++++++++++++ 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 74b3278c7..0dc930e69 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -121,20 +121,39 @@ class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Ca 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 = Zend_Cache::_makeBackend($this->_options['slow_backend'], $this->_options['slow_backend_options'], $this->_options['slow_backend_custom_naming'], $this->_options['slow_backend_autoload']); - $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->_slowBackend))) { - Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface'); - } - 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); } @@ -177,8 +196,14 @@ public function save($data, $id, $tags = array(), $specificLifetime = false, $pr 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); + } } - $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime); + return ($boolFast && $boolSlow); } diff --git a/test/TwoLevelsBackendTest.php b/test/TwoLevelsBackendTest.php index 9eed99916..8219d4753 100644 --- a/test/TwoLevelsBackendTest.php +++ b/test/TwoLevelsBackendTest.php @@ -97,6 +97,33 @@ public function testConstructorCorrectCall() )); } + public function testSaveOverwritesIfFastIsFull() + { + $slowBackend = 'File'; + $fastBackend = $this->getMock('Zend_Cache_Backend_Apc', array('getFillingPercentage')); + $fastBackend->expects($this->at(0)) + ->method('getFillingPercentage') + ->will($this->returnValue(0)); + $fastBackend->expects($this->at(1)) + ->method('getFillingPercentage') + ->will($this->returnValue(90)); + $slowBackendOptions = array( + 'cache_dir' => $this->_cache_dir + ); + $cache = new Zend_Cache_Backend_TwoLevels(array( + 'fast_backend' => $fastBackend, + 'slow_backend' => $slowBackend, + 'slow_backend_options' => $slowBackendOptions, + 'stats_update_factor' => 1 + )); + + $id = 'test'.uniqid(); + $cache->save(10, $id); //fast usage at 0% + + $cache->save(100, $id); //fast usage at 90% + $this->assertEquals(100, $cache->load($id)); + } + } From 5c3e48739ebce77f87919ccc69f993107c3ce567 Mon Sep 17 00:00:00 2001 From: alexander Date: Fri, 23 Apr 2010 19:35:33 +0000 Subject: [PATCH 082/311] Zend_Cache: improved cache template options processing. Closes [ZF-9737]. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21977 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Manager.php b/src/Manager.php index a409a2b81..932bcc191 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -37,7 +37,7 @@ class Zend_Cache_Manager * Constant holding reserved name for default Page Cache */ const PAGECACHE = 'page'; - + /** * Constant holding reserved name for default Page Tag Cache */ @@ -160,8 +160,8 @@ public function getCache($name) return $this->_caches[$name]; } if (isset($this->_optionTemplates[$name])) { - if ($name == self::PAGECACHE - && (!isset($this->_optionTemplates[$name]['backend']['options']['tag_cache']) + 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'] @@ -171,7 +171,10 @@ public function getCache($name) $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]['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]; } From 7832a17cd8cb757d64acc97593841f473c6cd694 Mon Sep 17 00:00:00 2001 From: jan Date: Sat, 24 Apr 2010 11:42:40 +0000 Subject: [PATCH 083/311] [ZF-9740] Zend_Cache_Core: const BACKEND_NOT_SUPPORTS_TAG typo git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@21980 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Core.php b/src/Core.php index 7555c3b71..77e57fd0c 100644 --- a/src/Core.php +++ b/src/Core.php @@ -475,7 +475,7 @@ public function getIdsMatchingTags($tags = array()) Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG); } $ids = $this->_backend->getIdsMatchingTags($tags); @@ -508,7 +508,7 @@ public function getIdsNotMatchingTags($tags = array()) Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG); } $ids = $this->_backend->getIdsNotMatchingTags($tags); @@ -541,7 +541,7 @@ public function getIdsMatchingAnyTags($tags = array()) Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG); } $ids = $this->_backend->getIdsMatchingAnyTags($tags); @@ -598,7 +598,7 @@ public function getTags() Zend_Cache::throwException(self::BACKEND_NOT_IMPLEMENTS_EXTENDED_IF); } if (!($this->_backendCapabilities['tags'])) { - Zend_Cache::throwException(self::BACKEND_NOT_SUPPORT_TAG); + Zend_Cache::throwException(self::BACKEND_NOT_SUPPORTS_TAG); } return $this->_backend->getTags(); } From 62e0f0fa4eb6cbfbdb8944ae85379c6d3528d06f Mon Sep 17 00:00:00 2001 From: padraic Date: Thu, 29 Apr 2010 15:13:50 +0000 Subject: [PATCH 084/311] Fixes test errors from ZF-9188 git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22056 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Manager.php | 2 +- test/AllTests.php | 1 + test/ManagerTest.php | 14 +++++++------- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Manager.php b/src/Manager.php index 932bcc191..8bde702e6 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -165,7 +165,7 @@ public function getCache($name) || !$this->_optionTemplates[$name]['backend']['options']['tag_cache'] instanceof Zend_Cache_Core) ) { $this->_optionTemplates[$name]['backend']['options']['tag_cache'] - = $this->getCache(self::PAGETAGCACHE ); + = $this->getCache(self::PAGETAGCACHE); } $this->_caches[$name] = Zend_Cache::factory( $this->_optionTemplates[$name]['frontend']['name'], diff --git a/test/AllTests.php b/test/AllTests.php index 11a9d6045..ae0a433f1 100644 --- a/test/AllTests.php +++ b/test/AllTests.php @@ -74,6 +74,7 @@ public static function suite() $suite->addTestSuite('Zend_Cache_ClassFrontendTest'); $suite->addTestSuite('Zend_Cache_FileFrontendTest'); $suite->addTestSuite('Zend_Cache_PageFrontendTest'); + $suite->addTestSuite('Zend_Cache_ManagerTest'); /* * Check if SQLite tests are enabled, and if extension and driver are available. diff --git a/test/ManagerTest.php b/test/ManagerTest.php index 9a9170322..62002f25c 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -58,20 +58,20 @@ public function testSetsCacheObject() public function testLazyLoadsDefaultPageCache() { $manager = new Zend_Cache_Manager; - $manager->setTemplateOptions('tagCache',array( + $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir ) ) )); - $this->assertTrue($manager->getCache('page') instanceof Zend_Cache_Frontend_Output); + $this->assertTrue($manager->getCache('page') instanceof Zend_Cache_Frontend_Capture); } public function testCanOverrideCacheFrontendNameConfiguration() { $manager = new Zend_Cache_Manager; - $manager->setTemplateOptions('tagCache',array( + $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir @@ -96,15 +96,15 @@ public function testCanMergeTemplateCacheOptionsFromZendConfig() ) ) )); - $manager->setTemplateOptions('tagCache', $config); - $options = $manager->getCacheTemplate('tagCache'); + $manager->setTemplateOptions('pagetag', $config); + $options = $manager->getCacheTemplate('pagetag'); $this->assertEquals($this->_cache_dir, $options['backend']['options']['cache_dir']); } public function testCanOverrideCacheBackendendNameConfiguration() { $manager = new Zend_Cache_Manager; - $manager->setTemplateOptions('tagCache',array( + $manager->setTemplateOptions('pagetag',array( 'backend' => array( 'options' => array( 'cache_dir' => $this->_cache_dir @@ -218,7 +218,7 @@ public function testGettingPageCacheAlsoCreatesTagCache() $manager = new Zend_Cache_Manager; $tagCacheConfig = $manager->getCacheTemplate('tagCache'); $tagCacheConfig['backend']['options']['cache_dir'] = $this->getTmpDir(); - $manager->setCacheTemplate('tagCache', $tagCacheConfig); + $manager->setCacheTemplate('pagetag', $tagCacheConfig); $tagCache = $manager->getCache('page')->getBackend()->getOption('tag_cache'); $this->assertTrue($tagCache instanceof Zend_Cache_Core); } From d4f21040211527f03066b8bc0c2649c375b8153c Mon Sep 17 00:00:00 2001 From: padraic Date: Thu, 29 Apr 2010 15:20:11 +0000 Subject: [PATCH 085/311] Fixed small test error in Zend_Cache_Manager git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22058 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/ManagerTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/ManagerTest.php b/test/ManagerTest.php index 62002f25c..9f62b375f 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -218,7 +218,7 @@ public function testGettingPageCacheAlsoCreatesTagCache() $manager = new Zend_Cache_Manager; $tagCacheConfig = $manager->getCacheTemplate('tagCache'); $tagCacheConfig['backend']['options']['cache_dir'] = $this->getTmpDir(); - $manager->setCacheTemplate('pagetag', $tagCacheConfig); + $manager->setTemplateOptions('pagetag', $tagCacheConfig); $tagCache = $manager->getCache('page')->getBackend()->getOption('tag_cache'); $this->assertTrue($tagCache instanceof Zend_Cache_Core); } From 1d88cab64dc8be1cac978251a6a7da65b35ea17f Mon Sep 17 00:00:00 2001 From: mabe Date: Thu, 20 May 2010 16:47:16 +0000 Subject: [PATCH 086/311] ZF-9848: Use class constant instead of string git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22207 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Memcached.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend/Memcached.php b/src/Backend/Memcached.php index b66eb3266..66e770ac7 100644 --- a/src/Backend/Memcached.php +++ b/src/Backend/Memcached.php @@ -224,7 +224,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $result = @$this->_memcache->set($id, array($data, time(), $lifetime), $flag, $lifetime); if (count($tags) > 0) { - $this->_log("Zend_Cache_Backend_Memcached::save() : tags are unsupported by the Memcached backend"); + $this->_log(self::TAGS_UNSUPPORTED_BY_SAVE_OF_MEMCACHED_BACKEND); } return $result; From 507bbb82d092d41b259409a1e6e0e6552b13bd00 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 29 Jun 2010 17:18:05 +0000 Subject: [PATCH 087/311] ZF-9979 & ZF-9422: allow function cache to use all types of callbacks git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22503 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Test.php | 12 +++--- src/Frontend/Function.php | 72 ++++++++++++++++++++++++++--------- test/FunctionFrontendTest.php | 67 ++++++++++++++++++++++++++++---- 3 files changed, 121 insertions(+), 30 deletions(-) diff --git a/src/Backend/Test.php b/src/Backend/Test.php index cb2493d0d..9e50517b9 100644 --- a/src/Backend/Test.php +++ b/src/Backend/Test.php @@ -103,10 +103,13 @@ public function setDirectives($directives) public function load($id, $doNotTestCacheValidity = false) { $this->_addLog('get', array($id, $doNotTestCacheValidity)); + if ( $id == 'false' || $id == 'd8523b3ee441006261eeffa5c3d3a0a7' || $id == 'e83249ea22178277d5befc2c5e2e9ace' - || $id == '40f649b94977c0a6e76902e2a0b43587') + || $id == '40f649b94977c0a6e76902e2a0b43587' + || $id == '88161989b73a4cbfd0b701c446115a99' + || $id == '205fc79cba24f0f0018eb92c7c8b3ba4') { return false; } @@ -116,10 +119,9 @@ public function load($id, $doNotTestCacheValidity = false) if ($id=='serialized2') { return serialize(array('headers' => array(), 'data' => 'foo')); } - if (($id=='71769f39054f75894288e397df04e445') or ($id=='615d222619fb20b527168340cebd0578')) { - return serialize(array('foo', 'bar')); - } - if (($id=='8a02d218a5165c467e7a5747cc6bd4b6') or ($id=='648aca1366211d17cbf48e65dc570bee')) { + if ( $id == '71769f39054f75894288e397df04e445' || $id == '615d222619fb20b527168340cebd0578' + || $id == '8a02d218a5165c467e7a5747cc6bd4b6' || $id == '648aca1366211d17cbf48e65dc570bee' + || $id == '4a923ef02d7f997ca14d56dfeae25ea7') { return serialize(array('foo', 'bar')); } return 'foo'; diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index 337623f86..dc8e72cbe 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -72,25 +72,29 @@ public function __construct(array $options = array()) /** * Main method : call the specified function or get the result from cache * - * @param string $name Function name - * @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 + * @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($name, $parameters = array(), $tags = array(), $specificLifetime = false, $priority = 8) + 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) { - // We do not have not cache - return call_user_func_array($name, $parameters); + // Caching of this callback is disabled + return call_user_func_array($callback, $parameters); } - $id = $this->_makeId($name, $parameters); + $id = $this->_makeId($callback, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) { // A cache is available $output = $rs[0]; @@ -99,7 +103,7 @@ public function call($name, $parameters = array(), $tags = array(), $specificLif // A cache is not available (or not valid for this frontend) ob_start(); ob_implicit_flush(false); - $return = call_user_func_array($name, $parameters); + $return = call_user_func_array($callback, $parameters); $output = ob_get_contents(); ob_end_clean(); $data = array($output, $return); @@ -113,20 +117,54 @@ public function call($name, $parameters = array(), $tags = array(), $specificLif /** * Make a cache id from the function name and parameters * - * @param string $name Function name + * @param callback $callback A valid callback * @param array $parameters Function parameters * @throws Zend_Cache_Exception * @return string Cache id */ - private function _makeId($name, $parameters) + private function _makeId($callback, array $args) { - if (!is_string($name)) { - Zend_Cache::throwException('Incorrect function name'); + 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; } - if (!is_array($parameters)) { - Zend_Cache::throwException('parameters argument must be an array'); + + // 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 . serialize($parameters)); + + return md5($name . $argsStr); } } diff --git a/test/FunctionFrontendTest.php b/test/FunctionFrontendTest.php index c7953a79b..6ebcb757a 100644 --- a/test/FunctionFrontendTest.php +++ b/test/FunctionFrontendTest.php @@ -37,6 +37,21 @@ function foobar($param1, $param2) { return "foobar_return($param1, $param2)"; } +class fooclass { + private static $_instanceCounter = 0; + + public function __construct() + { + self::$_instanceCounter++; + } + + public function foobar($param1, $param2) + { + return foobar($param1, $param2) + . ':' . self::$_instanceCounter; + } +} + /** * @category Zend * @package Zend_Cache @@ -156,24 +171,60 @@ public function testCallCorrectCall5() $this->assertEquals('foobar_output(param1, param2)', $data); } - public function testCallWithABadSyntax1() + public function testCallObjectMethodCorrectCall1() { - try { - $this->_instance->call(1, array()); - } catch (Zend_Cache_Exception $e) { - return; + // cacheByDefault = true + // nonCachedFunctions = array('foobar') + $this->_instance->setOption('cache_by_default', true); + $this->_instance->setOption('non_cached_functions', array('foobar')); + ob_start(); + ob_implicit_flush(false); + $object = new fooclass(); + $return = $this->_instance->call(array($object, 'foobar'), array('param1', 'param2')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param1, param2):1', $return); + $this->assertEquals('foobar_output(param1, param2)', $data); + } + + public function testCallObjectMethodCorrectCall2() + { + // cacheByDefault = true + // nonCachedFunctions = array('foobar') + $this->_instance->setOption('cache_by_default', true); + $this->_instance->setOption('non_cached_functions', array('foobar')); + ob_start(); + ob_implicit_flush(false); + $object = new fooclass(); + $return = $this->_instance->call(array($object, 'foobar'), array('param1', 'param2')); + $data = ob_get_contents(); + ob_end_clean(); + ob_implicit_flush(true); + $this->assertEquals('foobar_return(param1, param2):2', $return); + $this->assertEquals('foobar_output(param1, param2)', $data); + } + + public function testCallClosureThrowsException() + { + if (version_compare(PHP_VERSION, '5.3', '<')) { + $this->markTestSkipped(); } - $this->fail('Zend_Cache_Exception was expected but not thrown'); + + $this->setExpectedException('Zend_Cache_Exception'); + eval('$closure = function () {};'); // no parse error on php < 5.3 + $this->_instance->call($closure); } - public function testCallWithABadSyntax2() + public function testCallWithABadSyntax1() { try { - $this->_instance->call('foo', 1); + $this->_instance->call(1, array()); } catch (Zend_Cache_Exception $e) { return; } $this->fail('Zend_Cache_Exception was expected but not thrown'); } + } From 485a5d72a7d99519b89c7619776bb4ce9ce9bc0c Mon Sep 17 00:00:00 2001 From: mabe Date: Wed, 30 Jun 2010 17:19:17 +0000 Subject: [PATCH 088/311] ZF-9741: write the real class name instead of 'object' within phpdocs git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22505 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/TwoLevels.php | 4 ++-- src/Core.php | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Backend/TwoLevels.php b/src/Backend/TwoLevels.php index 0dc930e69..cda20596a 100644 --- a/src/Backend/TwoLevels.php +++ b/src/Backend/TwoLevels.php @@ -93,14 +93,14 @@ class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Ca /** * Slow Backend * - * @var Zend_Cache_Backend + * @var Zend_Cache_Backend_ExtendedInterface */ protected $_slowBackend; /** * Fast Backend * - * @var Zend_Cache_Backend + * @var Zend_Cache_Backend_ExtendedInterface */ protected $_fastBackend; diff --git a/src/Core.php b/src/Core.php index 77e57fd0c..2af8eb4ab 100644 --- a/src/Core.php +++ b/src/Core.php @@ -36,7 +36,7 @@ class Zend_Cache_Core /** * Backend Object * - * @var object $_backend + * @var Zend_Cache_Backend_Interface $_backend */ protected $_backend = null; @@ -167,7 +167,7 @@ public function setConfig(Zend_Config $config) /** * Set the backend * - * @param object $backendObject + * @param Zend_Cache_Backend $backendObject * @throws Zend_Cache_Exception * @return void */ @@ -191,7 +191,7 @@ public function setBackend(Zend_Cache_Backend $backendObject) /** * Returns the backend * - * @return object backend object + * @return Zend_Cache_Backend backend object */ public function getBackend() { From 5e78bffa348f0c6c7822bc6b868900bb07692d16 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 12 Jul 2010 12:23:07 -0400 Subject: [PATCH 089/311] s/dirname(__FILE__)/__DIR__/g - Replaced dirname(__FILE__) calls with __DIR__ throughout the codebase --- test/TestCommonBackend.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/TestCommonBackend.php b/test/TestCommonBackend.php index f10b48833..08a169431 100644 --- a/test/TestCommonBackend.php +++ b/test/TestCommonBackend.php @@ -45,7 +45,7 @@ abstract class TestCommonBackend extends \PHPUnit_Framework_TestCase public function __construct($name = null, array $data = array(), $dataName = '') { $this->_className = $name; - $this->_root = dirname(__FILE__); + $this->_root = __DIR__; date_default_timezone_set('UTC'); parent::__construct($name, $data, $dataName); } From 953075a386c7b333a88796577c6ef59cc0f184ce Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 19 Jul 2010 13:54:03 -0400 Subject: [PATCH 090/311] DB -> Db - Renamed Zend\DB to Zend\Db; updated all dependent classes - Also renamed all adapters to use MixedCase instead of ACRONYM case (PDO, MySQLi, etc.) --- src/Cache.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Cache.php b/src/Cache.php index 312039af2..65ded1fd8 100644 --- a/src/Cache.php +++ b/src/Cache.php @@ -143,7 +143,6 @@ public static function _makeBackend($backend, $backendOptions, $customBackendNam if (!$customBackendNaming) { $backend = self::_normalizeName($backend); } -echo "Normalized backend name: $backend\n"; if (in_array($backend, self::$standardBackends)) { // we use a standard backend $backendClass = 'Zend\\Cache\\Backend\\' . $backend; From 589a2fb79439cd1bea46bca36d603386700e8bd1 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 07:24:18 +0000 Subject: [PATCH 091/311] ZF-9970: class and function cache: set makeId public to give access to the used internal cache id git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22642 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/Class.php | 4 ++-- src/Frontend/Function.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index e4aef9452..a5b9157ed 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -209,7 +209,7 @@ public function __call($name, $parameters) return call_user_func_array(array($this->_cachedEntity, $name), $parameters); } - $id = $this->_makeId($name, $parameters); + $id = $this->makeId($name, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1]) ) { // A cache is available $output = $rs[0]; @@ -236,7 +236,7 @@ public function __call($name, $parameters) * @param array $parameters Method parameters * @return string Cache id */ - private function _makeId($name, $parameters) + public function makeId($name, $parameters) { return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($parameters)); } diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index dc8e72cbe..969c56470 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -94,7 +94,7 @@ public function call($callback, array $parameters = array(), $tags = array(), $s return call_user_func_array($callback, $parameters); } - $id = $this->_makeId($callback, $parameters); + $id = $this->makeId($callback, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) { // A cache is available $output = $rs[0]; @@ -122,7 +122,7 @@ public function call($callback, array $parameters = array(), $tags = array(), $s * @throws Zend_Cache_Exception * @return string Cache id */ - private function _makeId($callback, array $args) + public function makeId($callback, array $args) { if (!is_callable($callback, true, $name)) { Zend_Cache::throwException('Invalid callback'); From e5a148f108972fe9b09026a582bc6b671f3373bc Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 07:45:05 +0000 Subject: [PATCH 092/311] ZF-9642: create directories recursive using third argument of mkdir git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22644 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index 030e832ae..b7b0fe31a 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -36,8 +36,8 @@ * @copyright Copyright (c) 2005-2010 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 +class Zend_Cache_Backend_Static + extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface { const INNER_CACHE_NAME = 'zend_cache_backend_static_tagcache'; @@ -153,7 +153,7 @@ public function load($id, $doNotTestCacheValidity = false) * Test if a cache is available or not (for the given id) * * @param string $id cache id - * @return bool + * @return bool */ public function test($id) { @@ -172,7 +172,7 @@ public function test($id) return false; } $pathName = $this->_options['public_dir'] . dirname($id); - + // Switch extension if needed if (isset($this->_tagged[$id])) { $extension = $this->_tagged[$id]['extension']; @@ -255,12 +255,19 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $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) + && !@mkdir($path, $this->_options['cache_directory_umask'], true)) { + $lastErr = error_get_last(); + Zend_Cache::throwException("Can't create directory: {$lastErr['message']}"); + } + + /* $parts = explode('/', $path); $directory = ''; foreach ($parts as $part) { @@ -269,8 +276,9 @@ protected function _createDirectoriesFor($path) mkdir($directory, $this->_octdec($this->_options['cache_directory_umask'])); } } + */ } - + /** * Detect serialization of data (cannot predict since this is the only way * to obey the interface yet pass in another parameter). @@ -481,8 +489,8 @@ public function getInnerCache() /** * Verify path exists and is non-empty - * - * @param string $path + * + * @param string $path * @return bool */ protected function _verifyPath($path) @@ -494,7 +502,7 @@ protected function _verifyPath($path) /** * Determine the page to save from the request - * + * * @return string */ protected function _detectId() @@ -525,14 +533,14 @@ protected static function _validateIdOrTag($string) // Validation assumes no query string, fragments or scheme included - only the path if (!preg_match( - '/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/', + '/^(?:\/(?:(?:%[[: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) @@ -547,7 +555,7 @@ protected function _octdec($val) } return $val; } - + /** * Decode a request URI from the provided ID */ From d96a12295118be0ba3fe8637067e981f97724005 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 14:43:27 +0000 Subject: [PATCH 093/311] ZF-9970: fixed BC break: use the old private method "_makeId" to call the new public method "makeId" git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22648 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/Class.php | 18 ++++++++++++++---- src/Frontend/Function.php | 16 +++++++++++++--- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index a5b9157ed..b8ec4a5aa 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -229,16 +229,26 @@ public function __call($name, $parameters) 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 $parameters Method parameters + * @param string $name Method name + * @param array $args Method parameters * @return string Cache id */ - public function makeId($name, $parameters) + public function makeId($name, array $args = array()) { - return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($parameters)); + return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($args)); } } diff --git a/src/Frontend/Function.php b/src/Frontend/Function.php index 969c56470..b4f9b8b79 100644 --- a/src/Frontend/Function.php +++ b/src/Frontend/Function.php @@ -94,7 +94,7 @@ public function call($callback, array $parameters = array(), $tags = array(), $s return call_user_func_array($callback, $parameters); } - $id = $this->makeId($callback, $parameters); + $id = $this->_makeId($callback, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) { // A cache is available $output = $rs[0]; @@ -114,15 +114,25 @@ public function call($callback, array $parameters = array(), $tags = array(), $s 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 $parameters Function parameters + * @param array $args Function parameters * @throws Zend_Cache_Exception * @return string Cache id */ - public function makeId($callback, array $args) + public function makeId($callback, array $args = array()) { if (!is_callable($callback, true, $name)) { Zend_Cache::throwException('Invalid callback'); From 7cb070c4a921494b80f8ba24f387ae161d37ad2f Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 14:47:29 +0000 Subject: [PATCH 094/311] ZF-9970: call private method of _makeId internally git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22649 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/Class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Frontend/Class.php b/src/Frontend/Class.php index b8ec4a5aa..1ce9f3613 100644 --- a/src/Frontend/Class.php +++ b/src/Frontend/Class.php @@ -209,7 +209,7 @@ public function __call($name, $parameters) return call_user_func_array(array($this->_cachedEntity, $name), $parameters); } - $id = $this->makeId($name, $parameters); + $id = $this->_makeId($name, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1]) ) { // A cache is available $output = $rs[0]; From 3e718f6736c210c2e530e96b2dde66827071ddaf Mon Sep 17 00:00:00 2001 From: ramon Date: Wed, 21 Jul 2010 04:19:44 +0000 Subject: [PATCH 095/311] [ZF-10189] Zend_Cache: - fixed added require_once 'Zend/Log.php'. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22651 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Core.php | 1 + test/CoreTest.php | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Core.php b/src/Core.php index 2af8eb4ab..26ec49c8d 100644 --- a/src/Core.php +++ b/src/Core.php @@ -714,6 +714,7 @@ protected function _loggerSanity() // Create a default logger to the standard output stream require_once 'Zend/Log/Writer/Stream.php'; + require_once 'Zend/Log.php'; $logger = new Zend_Log(new Zend_Log_Writer_Stream('php://output')); $this->_options['logger'] = $logger; } diff --git a/test/CoreTest.php b/test/CoreTest.php index c46656e67..32bcb246f 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -86,7 +86,7 @@ public function testSettingOptionsWithZendConfig() $test->setConfig($config); $this->assertEquals(3600, $test->getOption('lifetime')); } - + /** * @group ZF-9092 */ @@ -522,4 +522,18 @@ public function testGetIdsMatchingAnyTags() $this->assertContains('id6', $ids); } + /** + * @group ZF-10189 + */ + public function testIfFileZendLogWasIncluded() + { + if (class_exists('Zend_Log', false)) { + $this->markTestSkipped('File Zend/Log.php already included'); + } + + $cacheCore = new Zend_Cache_Core( + array('logging' => true) + ); + $this->assertTrue($cacheCore->getOption('logger') instanceof Zend_Log); + } } From c070bd2e72d1870e28550fb9d49300c94a2bc9d7 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 07:45:05 +0000 Subject: [PATCH 096/311] ZF-9642: create directories recursive using third argument of mkdir git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22644 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/StaticBackend.php | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/Backend/StaticBackend.php b/src/Backend/StaticBackend.php index 8b5ff5885..1ee20af33 100644 --- a/src/Backend/StaticBackend.php +++ b/src/Backend/StaticBackend.php @@ -151,7 +151,7 @@ public function load($id, $doNotTestCacheValidity = false) * Test if a cache is available or not (for the given id) * * @param string $id cache id - * @return bool + * @return bool */ public function test($id) { @@ -170,7 +170,7 @@ public function test($id) return false; } $pathName = $this->_options['public_dir'] . dirname($id); - + // Switch extension if needed if (isset($this->_tagged[$id])) { $extension = $this->_tagged[$id]['extension']; @@ -253,12 +253,19 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $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) + && !@mkdir($path, $this->_options['cache_directory_umask'], true)) { + $lastErr = error_get_last(); + Zend_Cache::throwException("Can't create directory: {$lastErr['message']}"); + } + + /* $parts = explode('/', $path); $directory = ''; foreach ($parts as $part) { @@ -267,8 +274,9 @@ protected function _createDirectoriesFor($path) mkdir($directory, $this->_octdec($this->_options['cache_directory_umask'])); } } + */ } - + /** * Detect serialization of data (cannot predict since this is the only way * to obey the interface yet pass in another parameter). @@ -479,8 +487,8 @@ public function getInnerCache() /** * Verify path exists and is non-empty - * - * @param string $path + * + * @param string $path * @return bool */ protected function _verifyPath($path) @@ -492,7 +500,7 @@ protected function _verifyPath($path) /** * Determine the page to save from the request - * + * * @return string */ protected function _detectId() @@ -523,14 +531,14 @@ protected static function _validateIdOrTag($string) // Validation assumes no query string, fragments or scheme included - only the path if (!preg_match( - '/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/', + '/^(?:\/(?:(?:%[[:xdigit:]]{2}|[A-Za-z0-9-_.!~*\'()\[\]:@&=+$,;])*)?)+$/', $string ) ) { Cache\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) @@ -545,7 +553,7 @@ protected function _octdec($val) } return $val; } - + /** * Decode a request URI from the provided ID */ From 0d667d5ffec53a3652c757f07c850bf1f44bd52c Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 14:43:27 +0000 Subject: [PATCH 097/311] ZF-9970: fixed BC break: use the old private method "_makeId" to call the new public method "makeId" git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22648 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/ClassFrontend.php | 18 ++++++++++++++---- src/Frontend/FunctionFrontend.php | 16 +++++++++++++--- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/Frontend/ClassFrontend.php b/src/Frontend/ClassFrontend.php index ce85ec058..0784706d2 100644 --- a/src/Frontend/ClassFrontend.php +++ b/src/Frontend/ClassFrontend.php @@ -231,16 +231,26 @@ public function __call($name, $parameters) 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 $parameters Method parameters + * @param string $name Method name + * @param array $args Method parameters * @return string Cache id */ - public function makeId($name, $parameters) + public function makeId($name, array $args = array()) { - return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($parameters)); + return md5($this->_cachedEntityLabel . '__' . $name . '__' . serialize($args)); } } diff --git a/src/Frontend/FunctionFrontend.php b/src/Frontend/FunctionFrontend.php index 1b2c7cee0..3071b3657 100644 --- a/src/Frontend/FunctionFrontend.php +++ b/src/Frontend/FunctionFrontend.php @@ -95,7 +95,7 @@ public function call($callback, array $parameters = array(), $tags = array(), $s return call_user_func_array($callback, $parameters); } - $id = $this->makeId($callback, $parameters); + $id = $this->_makeId($callback, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1])) { // A cache is available $output = $rs[0]; @@ -115,15 +115,25 @@ public function call($callback, array $parameters = array(), $tags = array(), $s 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 $parameters Function parameters + * @param array $args Function parameters * @throws \Zend\Cache\Exception * @return string Cache id */ - public function makeId($callback, array $args) + public function makeId($callback, array $args = array()) { if (!is_callable($callback, true, $name)) { Cache::throwException('Invalid callback'); From 50e3e875351129eaea3c4281a8cbf6a749628230 Mon Sep 17 00:00:00 2001 From: mabe Date: Tue, 20 Jul 2010 14:47:29 +0000 Subject: [PATCH 098/311] ZF-9970: call private method of _makeId internally git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22649 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Frontend/ClassFrontend.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Frontend/ClassFrontend.php b/src/Frontend/ClassFrontend.php index 0784706d2..3209cb744 100644 --- a/src/Frontend/ClassFrontend.php +++ b/src/Frontend/ClassFrontend.php @@ -211,7 +211,7 @@ public function __call($name, $parameters) return call_user_func_array(array($this->_cachedEntity, $name), $parameters); } - $id = $this->makeId($name, $parameters); + $id = $this->_makeId($name, $parameters); if ( ($rs = $this->load($id)) && isset($rs[0], $rs[1]) ) { // A cache is available $output = $rs[0]; From 8d14b71734cf4f17c600c82eb5bfdf4b5f8ef34c Mon Sep 17 00:00:00 2001 From: ramon Date: Wed, 21 Jul 2010 04:19:44 +0000 Subject: [PATCH 099/311] [ZF-10189] Zend_Cache: - fixed added require_once 'Zend/Log.php'. git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22651 44c647ce-9c0f-0410-b52a-842ac1e357ba --- test/CoreTest.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/test/CoreTest.php b/test/CoreTest.php index 121eab698..4e28473b4 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -77,7 +77,7 @@ public function testSettingOptionsWithZendConfig() $test->setConfig($config); $this->assertEquals(3600, $test->getOption('lifetime')); } - + /** * @group ZF-9092 */ @@ -513,4 +513,18 @@ public function testGetIdsMatchingAnyTags() $this->assertContains('id6', $ids); } + /** + * @group ZF-10189 + */ + public function testIfFileZendLogWasIncluded() + { + if (class_exists('Zend_Log', false)) { + $this->markTestSkipped('File Zend/Log.php already included'); + } + + $cacheCore = new Zend_Cache_Core( + array('logging' => true) + ); + $this->assertTrue($cacheCore->getOption('logger') instanceof Zend_Log); + } } From 4130b152084f08c4a3c034c9ad6c5e8ab1762d23 Mon Sep 17 00:00:00 2001 From: mabe Date: Sat, 24 Jul 2010 16:37:10 +0000 Subject: [PATCH 100/311] ZF-5413: use "$var === null" instaed of "is_null($var)" git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22660 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 24 ++++++++++++------------ src/Frontend/Capture.php | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index b7b0fe31a..eca947661 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -166,7 +166,7 @@ public function test($id) if (empty($fileName)) { $fileName = $this->_options['index_filename']; } - if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if ($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return false; @@ -211,7 +211,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } clearstatcache(); - if (is_null($id) || strlen($id) == 0) { + if ($id === NULL) || strlen($id) == 0) { $id = $this->_detectId(); } else { $id = $this->_decodeId($id); @@ -225,7 +225,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $pathName = realpath($this->_options['public_dir']) . dirname($id); $this->_createDirectoriesFor($pathName); - if (is_null($id) || strlen($id) == 0) { + if ($id === NULL) || strlen($id) == 0) { $dataUnserialized = unserialize($data); $data = $dataUnserialized['data']; } @@ -239,9 +239,9 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } @chmod($file, $this->_octdec($this->_options['cache_file_umask'])); - if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if ($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; - } elseif (is_null($this->_tagged)) { + } elseif ($this->_tagged === NULL)) { $this->_tagged = array(); } if (!isset($this->_tagged[$id])) { @@ -305,7 +305,7 @@ public function remove($id) Zend_Cache::throwException('Invalid cache id: does not match expected public_dir path'); } $fileName = basename($id); - if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if ($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return false; @@ -394,7 +394,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) if (empty($tags)) { throw new Zend_Exception('Cannot use tag matching modes as no tags were defined'); } - if (is_null($this->_tagged) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if ($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return true; @@ -412,11 +412,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $result = true; break; case Zend_Cache::CLEANING_MODE_ALL: - if (is_null($this->_tagged)) { + if ($this->_tagged === NULL)) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; } - if (is_null($this->_tagged) || empty($this->_tagged)) { + if ($this->_tagged === NULL) || empty($this->_tagged)) { return true; } $urls = array_keys($this->_tagged); @@ -434,11 +434,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) if (empty($tags)) { throw new Zend_Exception('Cannot use tag matching modes as no tags were defined'); } - if (is_null($this->_tagged)) { + if ($this->_tagged === NULL)) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; } - if (is_null($this->_tagged) || empty($this->_tagged)) { + if ($this->_tagged === NULL) || empty($this->_tagged)) { return true; } $urls = array_keys($this->_tagged); @@ -481,7 +481,7 @@ public function setInnerCache(Zend_Cache_Core $cache) */ public function getInnerCache() { - if (is_null($this->_tagCache)) { + if ($this->_tagCache === NULL)) { Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()'); } return $this->_tagCache; diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index 3da6a5bda..a009932f3 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -75,7 +75,7 @@ public function start($id, array $tags, $extension = null) public function _flush($data) { $id = array_pop($this->_idStack); - if (is_null($id)) { + if ($id === NULL)) { Zend_Cache::throwException('use of _flush() without a start()'); } if ($this->_extension) { From 8c8be3766bb06242e25c88084844858d1c3849f1 Mon Sep 17 00:00:00 2001 From: mabe Date: Sat, 24 Jul 2010 16:55:09 +0000 Subject: [PATCH 101/311] ZF-5413: fixed my last commit is_null -> === null git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22661 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 24 ++++++++++++------------ src/Frontend/Capture.php | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index eca947661..b6469aa26 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -166,7 +166,7 @@ public function test($id) if (empty($fileName)) { $fileName = $this->_options['index_filename']; } - if ($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if (($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return false; @@ -211,7 +211,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } clearstatcache(); - if ($id === NULL) || strlen($id) == 0) { + if (($id === NULL) || strlen($id) == 0) { $id = $this->_detectId(); } else { $id = $this->_decodeId($id); @@ -225,7 +225,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $pathName = realpath($this->_options['public_dir']) . dirname($id); $this->_createDirectoriesFor($pathName); - if ($id === NULL) || strlen($id) == 0) { + if (($id === NULL) || strlen($id) == 0) { $dataUnserialized = unserialize($data); $data = $dataUnserialized['data']; } @@ -239,9 +239,9 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } @chmod($file, $this->_octdec($this->_options['cache_file_umask'])); - if ($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if (($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; - } elseif ($this->_tagged === NULL)) { + } elseif (($this->_tagged === NULL)) { $this->_tagged = array(); } if (!isset($this->_tagged[$id])) { @@ -305,7 +305,7 @@ public function remove($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)) { + if (($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return false; @@ -394,7 +394,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) 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)) { + if (($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return true; @@ -412,11 +412,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $result = true; break; case Zend_Cache::CLEANING_MODE_ALL: - if ($this->_tagged === NULL)) { + if (($this->_tagged === NULL)) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; } - if ($this->_tagged === NULL) || empty($this->_tagged)) { + if (($this->_tagged === NULL) || empty($this->_tagged)) { return true; } $urls = array_keys($this->_tagged); @@ -434,11 +434,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) if (empty($tags)) { throw new Zend_Exception('Cannot use tag matching modes as no tags were defined'); } - if ($this->_tagged === NULL)) { + if (($this->_tagged === NULL)) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; } - if ($this->_tagged === NULL) || empty($this->_tagged)) { + if (($this->_tagged === NULL) || empty($this->_tagged)) { return true; } $urls = array_keys($this->_tagged); @@ -481,7 +481,7 @@ public function setInnerCache(Zend_Cache_Core $cache) */ public function getInnerCache() { - if ($this->_tagCache === NULL)) { + if (($this->_tagCache === NULL)) { Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()'); } return $this->_tagCache; diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index a009932f3..f2fc87afa 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -75,7 +75,7 @@ public function start($id, array $tags, $extension = null) public function _flush($data) { $id = array_pop($this->_idStack); - if ($id === NULL)) { + if (($id === NULL)) { Zend_Cache::throwException('use of _flush() without a start()'); } if ($this->_extension) { From bbc7ba7fe96d5b6881777b77f45c32a00826ca5d Mon Sep 17 00:00:00 2001 From: mabe Date: Sat, 24 Jul 2010 17:37:36 +0000 Subject: [PATCH 102/311] ZF-5413: no double parentheses | NULL -> null git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@22662 44c647ce-9c0f-0410-b52a-842ac1e357ba --- src/Backend/Static.php | 24 ++++++++++++------------ src/Frontend/Capture.php | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Backend/Static.php b/src/Backend/Static.php index b6469aa26..d06bf4b58 100644 --- a/src/Backend/Static.php +++ b/src/Backend/Static.php @@ -166,7 +166,7 @@ public function test($id) if (empty($fileName)) { $fileName = $this->_options['index_filename']; } - if (($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return false; @@ -211,7 +211,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } clearstatcache(); - if (($id === NULL) || strlen($id) == 0) { + if ($id === null || strlen($id) == 0) { $id = $this->_detectId(); } else { $id = $this->_decodeId($id); @@ -225,7 +225,7 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) $pathName = realpath($this->_options['public_dir']) . dirname($id); $this->_createDirectoriesFor($pathName); - if (($id === NULL) || strlen($id) == 0) { + if ($id === null || strlen($id) == 0) { $dataUnserialized = unserialize($data); $data = $dataUnserialized['data']; } @@ -239,9 +239,9 @@ public function save($data, $id, $tags = array(), $specificLifetime = false) } @chmod($file, $this->_octdec($this->_options['cache_file_umask'])); - if (($this->_tagged === NULL) && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { + if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; - } elseif (($this->_tagged === NULL)) { + } elseif ($this->_tagged === null) { $this->_tagged = array(); } if (!isset($this->_tagged[$id])) { @@ -305,7 +305,7 @@ public function remove($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)) { + if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return false; @@ -394,7 +394,7 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) 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)) { + if ($this->_tagged === null && $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME)) { $this->_tagged = $tagged; } elseif (!$this->_tagged) { return true; @@ -412,11 +412,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) $result = true; break; case Zend_Cache::CLEANING_MODE_ALL: - if (($this->_tagged === NULL)) { + if ($this->_tagged === null) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; } - if (($this->_tagged === NULL) || empty($this->_tagged)) { + if ($this->_tagged === null || empty($this->_tagged)) { return true; } $urls = array_keys($this->_tagged); @@ -434,11 +434,11 @@ public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array()) if (empty($tags)) { throw new Zend_Exception('Cannot use tag matching modes as no tags were defined'); } - if (($this->_tagged === NULL)) { + if ($this->_tagged === null) { $tagged = $this->getInnerCache()->load(self::INNER_CACHE_NAME); $this->_tagged = $tagged; } - if (($this->_tagged === NULL) || empty($this->_tagged)) { + if ($this->_tagged === null || empty($this->_tagged)) { return true; } $urls = array_keys($this->_tagged); @@ -481,7 +481,7 @@ public function setInnerCache(Zend_Cache_Core $cache) */ public function getInnerCache() { - if (($this->_tagCache === NULL)) { + if ($this->_tagCache === null) { Zend_Cache::throwException('An Inner Cache has not been set; use setInnerCache()'); } return $this->_tagCache; diff --git a/src/Frontend/Capture.php b/src/Frontend/Capture.php index f2fc87afa..0381ae33f 100644 --- a/src/Frontend/Capture.php +++ b/src/Frontend/Capture.php @@ -75,7 +75,7 @@ public function start($id, array $tags, $extension = null) public function _flush($data) { $id = array_pop($this->_idStack); - if (($id === NULL)) { + if ($id === null) { Zend_Cache::throwException('use of _flush() without a start()'); } if ($this->_extension) { From 7a696c0688ab6e08c389a642df62a02420ef5ac3 Mon Sep 17 00:00:00 2001 From: Jonathan Maron Date: Wed, 18 Aug 2010 09:22:26 +0200 Subject: [PATCH 103/311] merging --- src/Backend/StaticBackend.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Backend/StaticBackend.php b/src/Backend/StaticBackend.php index 3637d3c8b..4c0f4470b 100644 --- a/src/Backend/StaticBackend.php +++ b/src/Backend/StaticBackend.php @@ -559,6 +559,6 @@ protected function _octdec($val) */ protected function _decodeId($id) { - return pack('H*', $id); + return pack('H*', $id);; } } From ac77c92ba6d0471a8945290df7f03556a7ad4b3c Mon Sep 17 00:00:00 2001 From: Bill Karwin Date: Sat, 16 Oct 2010 12:36:55 -0700 Subject: [PATCH 104/311] Fix unit tests, they were not working because of namespace changes and class refactoring. --- test/CoreTest.php | 4 ++++ test/ManagerTest.php | 11 +++++++---- test/SkipTests.php | 7 ------- test/StaticBackendTest.php | 19 +++++++++++++++++++ 4 files changed, 30 insertions(+), 11 deletions(-) diff --git a/test/CoreTest.php b/test/CoreTest.php index eed32904b..8df61f73c 100644 --- a/test/CoreTest.php +++ b/test/CoreTest.php @@ -521,6 +521,10 @@ public function testIfFileZendLogWasIncluded() $this->markTestSkipped('File Zend/Log.php already included'); } + if (!class_exists('Zend_Cache_Core', true)) { + $this->markTestIncomplete('File Zend/Cache/Core.php cannot be found'); + } + $cacheCore = new Zend_Cache_Core( array('logging' => true) ); diff --git a/test/ManagerTest.php b/test/ManagerTest.php index 45dc37048..5832f36c5 100644 --- a/test/ManagerTest.php +++ b/test/ManagerTest.php @@ -12,8 +12,9 @@ * 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_Cache - * @package UnitTests + * @category Zend + * @package Zend_Cache + * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -22,8 +23,10 @@ use Zend\Cache; /** - * @category Zend_Cache - * @package UnitTests + * @category Zend + * @package Zend_Cache + * @subpackage UnitTests + * @group Zend_Cache * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ diff --git a/test/SkipTests.php b/test/SkipTests.php index cf0339c38..90769b600 100644 --- a/test/SkipTests.php +++ b/test/SkipTests.php @@ -19,13 +19,6 @@ * @license http://framework.zend.com/license/new-bsd New BSD License */ -/** - * PHPUnit_Framework_TestCase - */ - - -PHPUnit_Util_Filter::addFileToFilter(__FILE__); - /** * @category Zend * @package Zend_Cache diff --git a/test/StaticBackendTest.php b/test/StaticBackendTest.php index ca2d1970a..57dcfd6c0 100644 --- a/test/StaticBackendTest.php +++ b/test/StaticBackendTest.php @@ -1,15 +1,34 @@ Date: Wed, 5 Oct 2011 12:06:31 -0500 Subject: [PATCH 105/311] [TESTS] Fixed issues in FileFrontendTest - Referenced non-existent property - s/is_boolean/is_bool/ (former is not a valid PHP function) --- test/FileFrontendTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/FileFrontendTest.php b/test/FileFrontendTest.php index 3870d187f..206ba8b81 100644 --- a/test/FileFrontendTest.php +++ b/test/FileFrontendTest.php @@ -214,8 +214,8 @@ public function testGetWithDoNotTestCacheValidity() public function testGetOptions() { - $this->assertTrue(is_array($this->_instance->getOption())); - $this->assertTrue(is_boolean($this->_instance->getOption('file_locking'))); + $this->assertTrue(is_array($this->_instance1->getOption())); + $this->assertTrue(is_bool($this->_instance1->getOption('write_control'))); } } From 18e77f384c3f15f33c72b0fc68bea454e49357c6 Mon Sep 17 00:00:00 2001 From: marc-mabe Date: Thu, 1 Dec 2011 21:17:09 +0100 Subject: [PATCH 106/311] fixed parameter by reference error --- test/Storage/Plugin/ClearByFactorTest.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/Storage/Plugin/ClearByFactorTest.php b/test/Storage/Plugin/ClearByFactorTest.php index db655fca8..6a95eff25 100644 --- a/test/Storage/Plugin/ClearByFactorTest.php +++ b/test/Storage/Plugin/ClearByFactorTest.php @@ -81,7 +81,8 @@ public function testClearByFactorUsingNamespace() $event = new PostEvent('setItem.post', $adapter, array( 'options' => array(), )); - $event->setResult(true); + $result = true; + $event->setResult($result); $this->_plugin->clearByFactor($event); $this->assertTrue($event->getResult()); @@ -103,7 +104,8 @@ public function testClearByFactorAllNamespaces() $event = new PostEvent('setItem.post', $adapter, array( 'options' => array(), )); - $event->setResult(true); + $result = true; + $event->setResult($result); $this->_plugin->clearByFactor($event); $this->assertTrue($event->getResult()); From 874ddfb6bd9904433e2144b04383d8fa9e687150 Mon Sep 17 00:00:00 2001 From: marc-mabe Date: Thu, 1 Dec 2011 22:13:02 +0100 Subject: [PATCH 107/311] - reordered arguments of key and value - key can no longer be ignored - removed lastKey feature - removed profiler for beta 2 - fixed most unit tests --- src/Pattern/CallbackCache.php | 2 +- src/Pattern/CaptureCache.php | 2 +- src/Pattern/OutputCache.php | 2 +- src/Storage/Adapter.php | 37 ++-- src/Storage/Adapter/AbstractAdapter.php | 67 ++----- src/Storage/Adapter/Memory.php | 21 +- test/Pattern/CallbackCacheTest.php | 4 + test/Pattern/ClassCacheTest.php | 2 + test/Pattern/ObjectCacheTest.php | 2 + test/Profiler/ProfileTest.php | 99 --------- test/Profiler/ProfilerTest.php | 200 ------------------- test/Storage/Adapter/AbstractAdapterTest.php | 19 +- test/Storage/Adapter/CommonAdapterTest.php | 134 ++++++------- test/Storage/Plugin/OptimizeByFactorTest.php | 3 +- test/StorageFactoryTest.php | 14 +- 15 files changed, 131 insertions(+), 477 deletions(-) delete mode 100644 test/Profiler/ProfileTest.php delete mode 100644 test/Profiler/ProfilerTest.php diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index cba2a6c62..c63a55ee3 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -141,7 +141,7 @@ public function call($callback, array $args = array(), array $options = array()) $data = array($ret); } - $this->getStorage()->setItem($data, $key, $options); + $this->getStorage()->setItem($key, $data, $options); return $ret; } diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index d21499c77..15fb41138 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -348,7 +348,7 @@ protected function _save($output) } if ($tagIndex !== null) { - $this->getTagStorage()->setItem($tagIndex, $tagKey); + $this->getTagStorage()->setItem($tagKey, $tagIndex); } } } diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index 8c17c889d..4042a9a0b 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -145,7 +145,7 @@ public function end(array $options = array()) throw new RuntimeException('Output buffering not active'); } - return $this->getStorage()->setItem($data, $key, $options); + return $this->getStorage()->setItem($key, $data, $options); } } diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index 20a0c9d1c..412dfc724 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -95,7 +95,7 @@ public function getOptions(); * @return mixed Data on success and false on failure * @throws Zend\Cache\Exception */ - public function getItem($key = null, array $options = array()); + public function getItem($key, array $options = array()); /** * Get multiple items. @@ -115,7 +115,7 @@ public function getItems(array $keys, array $options = array()); * @return boolean * @throws Zend\Cache\Exception */ - public function hasItem($key = null, array $options = array()); + public function hasItem($key, array $options = array()); /** * Test multiple items. @@ -135,7 +135,7 @@ public function hasItems(array $keys, array $options = array()); * @return array|boolean Metadata or false on failure * @throws Zend\Cache\Exception */ - public function getMetadata($key = null, array $options = array()); + public function getMetadata($key, array $options = array()); /** * Get multiple metadata @@ -152,13 +152,13 @@ public function getMetadatas(array $keys, array $options = array()); /** * Store an item. * - * @param mixed $value * @param string $key + * @param mixed $value * @param array $options * @return boolean * @throws Zend\Cache\Exception */ - public function setItem($value, $key = null, array $options = array()); + public function setItem($key, $value, array $options = array()); /** * Store multiple items. @@ -173,13 +173,13 @@ public function setItems(array $keyValuePairs, array $options = array()); /** * Add an item. * - * @param mixed $value * @param string $key + * @param mixed $value * @param array $options * @return boolean * @throws Zend\Cache\Exception */ - public function addItem($value, $key = null, array $options = array()); + public function addItem($key, $value, array $options = array()); /** * Add multiple items. @@ -194,13 +194,13 @@ public function addItems(array $keyValuePairs, array $options = array()); /** * Replace an item. * - * @param mixed $value * @param string $key + * @param mixed $value * @param array $options * @return boolean * @throws Zend\Cache\Exception */ - public function replaceItem($value, $key = null, array $options = array()); + public function replaceItem($key, $value, array $options = array()); /** * Replace multiple items. @@ -216,13 +216,13 @@ public function replaceItems(array $keyValuePairs, array $options = array()); * Set item only if token matches * * @param mixed $token - * @param mixed $value * @param string|null $key + * @param mixed $value * @param array $options * @return boolean * @throws Zend\Cache\Exception */ - public function checkAndSetItem($token, $newValue, $key = null, array $options = array()); + public function checkAndSetItem($token, $key, $value, array $options = array()); /** * Reset lifetime of an item @@ -232,7 +232,7 @@ public function checkAndSetItem($token, $newValue, $key = null, array $options = * @return boolean True on success or false on failure * @throws Zend\Cache\Exception */ - public function touchItem($key = null, array $options = array()); + public function touchItem($key, array $options = array()); /** * Reset lifetime of multiple items. @@ -252,7 +252,7 @@ public function touchItems(array $keys, array $options = array()); * @return boolean True on success or false on failure * @throws Zend\Cache\Exception */ - public function removeItem($key = null, array $options = array()); + public function removeItem($key, array $options = array()); /** * Remove multiple items. @@ -273,7 +273,7 @@ public function removeItems(array $keys, array $options = array()); * @return boolean True on success or false on failure * @throws Zend\Cache\Exception */ - public function incrementItem($value, $key = null, array $options = array()); + public function incrementItem($key, $value, array $options = array()); /** * Increment multiple items. @@ -294,7 +294,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()); * @return boolean True on success or false on failure * @throws Zend\Cache\Exception */ - public function decrementItem($value, $key = null, array $options = array()); + public function decrementItem($key, $value, array $options = array()); /** * Decrement multiple items. @@ -393,11 +393,4 @@ public function getCapabilities(); */ public function getCapacity(array $options = array()); - /** - * Get the last used key - * - * @return string|null - */ - public function getLastKey(); - } diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index f6d251b79..05408d1fc 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -95,13 +95,6 @@ abstract class AbstractAdapter implements Adapter */ protected $_ignoreMissingItems = true; - /** - * The last used key - * - * @var string|null - */ - protected $_lastKey = null; - /** * Statement */ @@ -355,10 +348,6 @@ public function setKeyPattern($pattern) if (@preg_match($pattern, '') === false) { $err = error_get_last(); throw new InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - - // validate lastKey - } elseif (($lk = $this->getLastKey()) !== null && !preg_match($pattern, $lk)) { - $this->_lastKey = null; // remove the last used key } $this->_keyPattern = $pattern; @@ -540,7 +529,7 @@ public function getItems(array $keys, array $options = array()) return $ret; } - public function hasItem($key = null, array $options = array()) + public function hasItem($key, array $options = array()) { if (!$this->getReadable()) { return false; @@ -602,19 +591,18 @@ public function setItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->setItem($value, $key, $options) && $ret; + $ret = $this->setItem($key, $value, $options) && $ret; } return $ret; } - public function addItem($value, $key = null, array $options = array()) + public function addItem($key, $value, array $options = array()) { if ($this->hasItem($key, $options)) { - $key = $this->_key($key); throw new RuntimeException("Key '{$key}' already exists"); } - return $this->setItem($value, $key, $options); + return $this->setItem($key, $value, $options); } public function addItems(array $keyValuePairs, array $options = array()) @@ -625,19 +613,18 @@ public function addItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->addItem($value, $key, $options) && $ret; + $ret = $this->addItem($key, $value, $options) && $ret; } return $ret; } - public function replaceItem($value, $key = null, array $options = array()) + public function replaceItem($key, $value, array $options = array()) { if (!$this->hasItem($key, $options)) { - $key = $this->_key($key); throw new ItemNotFoundException("Key '{$key}' doen't exists"); } - return $this->setItem($value, $key, $options); + return $this->setItem($key, $value, $options); } public function replaceItems(array $keyValuePairs, array $options = array()) @@ -648,25 +635,23 @@ public function replaceItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->replaceItem($value, $key, $options) && $ret; + $ret = $this->replaceItem($key, $value, $options) && $ret; } return $ret; } - public function checkAndSetItem($token, $value, $key = null, array $options = array()) + public function checkAndSetItem($token, $key, $value, array $options = array()) { - $key = $this->_key($key); - $oldValue = $this->getItem($key, $options); if ($oldValue != $token) { return false; } - return $this->setItem($value, $key, $options); + return $this->setItem($key, $value, $options); } - public function touchItem($key = null, array $options = array()) + public function touchItem($key, array $options = array()) { if (!$this->getWritable() || !$this->getReadable()) { return false; @@ -678,7 +663,7 @@ public function touchItem($key = null, array $options = array()) $value = $this->getItem($key, $optsNoValidate); if ($value === false) { // add an empty item - return $this->addItem('', $key, $options); + return $this->addItem($key, '', $options); } else { // rewrite item to update mtime/ttl if (!isset($options['tags'])) { @@ -689,7 +674,7 @@ public function touchItem($key = null, array $options = array()) } // rewrite item - return $this->replaceItem($value, $key, $options); + return $this->replaceItem($key, $value, $options); } } @@ -729,7 +714,7 @@ public function incrementItem($value, $key = null, array $options = array()) $value = (int)$value; $get = (int)$this->getItem($key, $options); - $this->setItem($get + $value, $key, $options); + $this->setItem($key, $get + $value, $options); return $get + $value; } @@ -742,7 +727,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->incrementItems($value, $key, $options) && $ret; + $ret = $this->incrementItems($key, $value, $options) && $ret; } return $ret; } @@ -755,7 +740,7 @@ public function decrementItem($value, $key = null, array $options = array()) $value = (int)$value; $get = (int)$this->getItem($key, $options); - $this->setItem($get - $value, $key, $options); + $this->setItem($key, $get - $value, $options); return $get - $value; } @@ -768,7 +753,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->decrementMulti($value, $key, $options) && $ret; + $ret = $this->decrementMulti($key, $value, $options) && $ret; } return $ret; } @@ -922,11 +907,6 @@ public function getCapabilities() return $this->_capabilities; } - public function getLastKey() - { - return $this->_lastKey; - } - /* internal */ /** @@ -1068,25 +1048,18 @@ protected function _normalizeMatchingMode(&$mode, $default, array &$normalizedOp /** * Get, validate and normalize key. - * (If key is empty get the last used key) * - * @param string|null $key + * @param string $key * @return string * @throws Zend\Cache\InvalidArgumentException */ protected function _key($key) { - if ( ($key = (string)$key) === '') { - if ($this->_lastKey === null) { - throw new MissingKeyException('Missing key'); - } - } elseif (($p = $this->getKeyPattern()) && !preg_match($p, $key)) { + if (($p = $this->getKeyPattern()) && !preg_match($p, $key)) { throw new InvalidArgumentException("The key '{$key}' doesn't match agains pattern '{$p}'"); - } else { - $this->_lastKey = $key; } - return $this->_lastKey; + return (string)$key; } } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 6c0520f3e..5218aa78a 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -31,7 +31,7 @@ class Memory extends AbstractAdapter /* reading */ - public function getItem($key = null, array $options = array()) + public function getItem($key, array $options = array()) { if (!$this->getReadable()) { return false; @@ -62,7 +62,6 @@ public function getItem($key = null, array $options = array()) throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); } $result = false; - $args['_RESULT_'] = false; } else { $result = $this->_data[$ns][$key][0]; if (array_key_exists('token', $options)) { @@ -113,7 +112,7 @@ public function getItems(array $keys, array $options = array()) return $postEvent->getResult(); } - public function hasItem($key = null, array $options = array()) + public function hasItem($key, array $options = array()) { if (!$this->getReadable()) { return false; @@ -137,7 +136,7 @@ public function hasItem($key = null, array $options = array()) return $postEvent->getResult(); } - public function getMetadata($key = null, array $options = array()) + public function getMetadata($key, array $options = array()) { if (!$this->getReadable()) { return false; @@ -176,7 +175,7 @@ public function getMetadata($key = null, array $options = array()) /* writing */ - public function setItem($value, $key = null, array $options = array()) + public function setItem($key, $value, array $options = array()) { if (!$this->getWritable()) { return false; @@ -235,7 +234,7 @@ public function setItems(array $keyValuePairs, array $options = array()) return $postEvent->getResult(); } - public function addItem($value, $key = null, array $options = array()) + public function addItem($key, $value, array $options = array()) { if (!$this->getWritable()) { return false; @@ -300,7 +299,7 @@ public function addItems(array $keyValuePairs, array $options = array()) return $postEvent->getResult(); } - public function replaceItem($value, $key = null, array $options = array()) + public function replaceItem($key, $value, array $options = array()) { if (!$this->getWritable()) { return false; @@ -367,7 +366,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return $postEvent->getResult(); } - public function touchItem($key = null, array $options = array()) + public function touchItem($key, array $options = array()) { if (!$this->getWritable()) { return false; @@ -405,7 +404,7 @@ public function touchItem($key = null, array $options = array()) return $postEvent->getResult(); } - public function removeItem($key = null, array $options = array()) + public function removeItem($key, array $options = array()) { if (!$this->getWritable()) { return false; @@ -499,7 +498,7 @@ public function removeItems(array $keys, array $options = array()) return $postEvent->getResult(); } - public function incrementItem($value, $key = null, array $options = array()) + public function incrementItem($key, $value, array $options = array()) { if (!$this->getWritable()) { return false; @@ -541,7 +540,7 @@ public function incrementItem($value, $key = null, array $options = array()) return $postEvent->getResult(); } - public function decrementItem($value, $key = null, array $options = array()) + public function decrementItem($key, $value, array $options = array()) { if (!$this->getWritable()) { return false; diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index ca09caea0..42a5af947 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -113,6 +113,8 @@ public function testMagicFunctionCall() public function testCallWithPredefinedCallbackAndArgumentKey() { + $this->markTestIncomplete(); + $callback = __NAMESPACE__ . '\TestCallbackCache::emptyMethod'; $args = array('arg1', 2, 3.33, null); $options = array( @@ -131,6 +133,8 @@ public function testCallWithPredefinedCallbackAndArgumentKey() public function testGenerateKey() { + $this->markTestIncomplete(); + $callback = __NAMESPACE__ . '\TestCallbackCache::emptyMethod'; $args = array('arg1', 2, 3.33, null); diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 203f78134..16f1d4e3b 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -97,6 +97,8 @@ public function testCallDisabledCacheOutput() public function testGenerateKey() { + $this->markTestIncomplete(); + $args = array('arg1', 2, 3.33, null); $this->_pattern->call('emptyMethod', $args); $this->assertEquals( diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index 67f8790c5..7f4894a13 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -111,6 +111,8 @@ public function testCallInvoke() public function testGenerateKey() { + $this->markTestIncomplete(); + $args = array('arg1', 2, 3.33, null); $this->_pattern->call('emptyMethod', $args); $this->assertEquals( diff --git a/test/Profiler/ProfileTest.php b/test/Profiler/ProfileTest.php deleted file mode 100644 index 15ea8639c..000000000 --- a/test/Profiler/ProfileTest.php +++ /dev/null @@ -1,99 +0,0 @@ -assertFalse($profile->hasStarted()); - $this->assertNull($profile->getStartTime()); - - $this->assertFalse($profile->hasStopped()); - $this->assertNull($profile->getStopTime()); - $this->assertSame(0, $profile->getElapsedTime()); - } - - public function testStart() - { - $profile = new Profiler\Profile(); - - $startTime = microtime(true); - $args = array('p1', 'p2'); - - $profile->start('command', $args); - - $this->assertTrue($profile->hasStarted()); - $this->assertFalse($profile->hasStopped()); - - $this->assertEquals('command', $profile->getCommand()); - $this->assertEquals($args, $profile->getArguments()); - - $this->assertGreaterThanOrEqual($startTime, $profile->getStartTime()); - $this->assertLessThan($startTime + 1, $profile->getStartTime()); - - $this->assertNull($profile->getStopTime()); - $this->assertGreaterThan(0, $profile->getElapsedTime()); - } - - public function testStartAlreadyStartedThrowsLogicException() - { - $profile = new Profiler\Profile(); - $profile->start('cmd'); - - $this->setExpectedException('Zend\Cache\Exception\LogicException'); - $profile->start('cmd'); - } - - public function testStop() - { - $profile = new Profiler\Profile(); - - $profile->start('command'); - usleep(100); - $profile->stop(); - - $this->assertTrue($profile->hasStarted()); - $this->assertTrue($profile->hasStopped()); - - $this->assertGreaterThan(0, $profile->getStopTime()); - $this->assertGreaterThan(0, $profile->getElapsedTime()); - } - - public function testStopNotStartedThrowsLogicException() - { - $profile = new Profiler\Profile(); - - $this->setExpectedException('Zend\Cache\Exception\LogicException'); - $profile->stop(); - } - -} diff --git a/test/Profiler/ProfilerTest.php b/test/Profiler/ProfilerTest.php deleted file mode 100644 index e8b1eb541..000000000 --- a/test/Profiler/ProfilerTest.php +++ /dev/null @@ -1,200 +0,0 @@ -_profiler = new Profiler\Profiler(); - $this->_profiler->setEnabled(true); - } - - public function testAddAndHasProfile() - { - $profile = new Profiler\Profile(); - - // test missing profile - $this->assertFalse($this->_profiler->hasProfile($profile)); - $this->assertFalse($this->_profiler->hasProfile($profile->getProfileId())); - - // add profile - $this->assertSame($this->_profiler, $this->_profiler->addProfile($profile)); - - // test existing profile - $this->assertTrue($this->_profiler->hasProfile($profile)); - $this->assertTrue($this->_profiler->hasProfile($profile->getProfileId())); - } - - public function testGetProfile() - { - $profile = new Profiler\Profile(); - $this->_profiler->addProfile($profile); - - $this->assertSame($profile, $this->_profiler->getProfile($profile)); - $this->assertSame($profile, $this->_profiler->getProfile($profile->getProfileId())); - } - - public function testGetProfiles() - { - $profile1 = new Profiler\Profile(); - $profile2 = new Profiler\Profile(); - $this->_profiler->addProfile($profile1); - $this->_profiler->addProfile($profile2); - - $this->assertEquals(array( - $profile1->getProfileId() => $profile1, - $profile2->getProfileId() => $profile2, - ), $this->_profiler->getProfiles()); - } - - public function testGetLastProfile() - { - $profile1 = new Profiler\Profile(); - $profile2 = new Profiler\Profile(); - $this->_profiler->addProfile($profile1); - $this->_profiler->addProfile($profile2); - - $this->assertSame($profile2, $this->_profiler->getLastProfile()); - } - - public function testGetMissingProfileThrowsRuntimeException() - { - $profile = new Profiler\Profile(); - - $this->setExpectedException('Zend\Cache\Exception\RuntimeException'); - $this->_profiler->getProfile($profile); - } - - public function testRemoveProfile() - { - $profile = new Profiler\Profile(); - - // test remove profile by instance - $this->_profiler->addProfile($profile); - $this->assertSame($this->_profiler, $this->_profiler->removeProfile($profile)); - $this->assertFalse($this->_profiler->hasProfile($profile)); - - // test remove profile by id - $this->_profiler->addProfile($profile); - $this->assertSame($this->_profiler, $this->_profiler->removeProfile($profile->getProfileId())); - $this->assertFalse($this->_profiler->hasProfile($profile)); - } - - public function testClearProfiles() - { - // add three profiles - $profile1 = new Profiler\Profile(); - $profile2 = new Profiler\Profile(); - $profile3 = new Profiler\Profile(); - $this->_profiler->addProfile($profile1); - $this->_profiler->addProfile($profile2); - $this->_profiler->addProfile($profile3); - - $this->assertSame($this->_profiler, $this->_profiler->clearProfiles()); - - $this->assertFalse($this->_profiler->hasProfile($profile1)); - $this->assertFalse($this->_profiler->hasProfile($profile2)); - $this->assertFalse($this->_profiler->hasProfile($profile3)); - } - - public function testCount() - { - // test empty set - $this->assertEquals(0, $this->_profiler->count()); - - // add three profiles - $profile1 = new Profiler\Profile(); - $profile2 = new Profiler\Profile(); - $profile3 = new Profiler\Profile(); - $this->_profiler->addProfile($profile1); - $this->_profiler->addProfile($profile2); - $this->_profiler->addProfile($profile3); - $this->assertEquals(3, $this->_profiler->count()); - - // remove an profile - $this->_profiler->removeProfile($profile2); - $this->assertEquals(2, $this->_profiler->count()); - - // clear all profiles - $this->_profiler->clearProfiles(); - $this->assertEquals(0, $this->_profiler->count()); - } - - public function testStart() - { - $cmd = 'cmd'; - $args = array('args'); - - $profile = $this->_profiler->start($cmd, $args); - $this->assertInstanceOf('Zend\Cache\Profiler\Profile', $profile); - $this->assertTrue($profile->hasStarted()); - $this->assertFalse($profile->hasStopped()); - $this->assertEquals($cmd, $profile->getCommand()); - $this->assertEquals($args, $profile->getArguments()); - } - - public function testStartIfDisabled() - { - $this->_profiler->setEnabled(false); - $this->assertFalse($this->_profiler->start('cmd')); - } - - public function testStop() - { - $profile = $this->_profiler->start('cmd'); - $this->_profiler->stop($profile->getProfileId()); - $this->assertTrue($profile->hasStopped()); - } - - public function testTotalElapsedTime() - { - // add three profiles - $profile1 = $this->_profiler->start('cmd1'); - $profile2 = $this->_profiler->start('cmd2'); - $profile3 = $this->_profiler->start('cmd3'); - $profile1->stop(); - $profile2->stop(); - $profile3->stop(); - - $expectedElapsedTime = 0; - foreach ($this->_profiler->getProfiles() as $profile) { - $expectedElapsedTime+= $profile->getElapsedTime(); - } - $this->assertEquals($expectedElapsedTime, $this->_profiler->getTotalElapsedTime()); - } - -} diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 96f2b11e6..17e009dff 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -164,13 +164,6 @@ public function testSetKeyPatternThrowsExceptionOnInvalidPattern() $this->_storage->setKeyPattern('#'); } - public function testSetKeyPatternRemoveInvalidLastKey() - { - $this->_storage->hasItem('test'); - $this->_storage->setKeyPattern('/[abc]/'); - $this->assertNull($this->_storage->getLastKey()); - } - public function testSetIgnoreMissingItems() { $this->_storage->setIgnoreMissingItems(true); @@ -364,7 +357,7 @@ public function testSetItems() $this->_storage->expects($this->exactly(count($items))) ->method('setItem') - ->with($this->stringContains('value'), $this->stringContains('key'), $this->equalTo($options)) + ->with($this->stringContains('key'), $this->stringContains('value'), $this->equalTo($options)) ->will($this->returnValue(true)); $this->assertTrue($this->_storage->setItems($items, $options)); @@ -381,7 +374,7 @@ public function testSetItemsFail() $this->_storage->expects($this->exactly(count($items))) ->method('setItem') - ->with($this->stringContains('value'), $this->stringContains('key'), $this->equalTo($options)) + ->with($this->stringContains('key'), $this->stringContains('value'), $this->equalTo($options)) ->will($this->returnValue(false)); $this->assertFalse($this->_storage->setItems($items, $options)); @@ -402,7 +395,7 @@ public function testAddItems() ->will($this->returnValue(false)); $this->_storage->expects($this->exactly(count($items))) ->method('setItem') - ->with($this->stringContains('value'), $this->stringContains('key'), $this->equalTo($options)) + ->with($this->stringContains('key'), $this->stringContains('value'), $this->equalTo($options)) ->will($this->returnValue(true)); $this->assertTrue($this->_storage->addItems($items, $options)); @@ -424,7 +417,7 @@ public function testAddItemsFail() ->will($this->returnValue(false)); $this->_storage->expects($this->exactly(count($items))) ->method('setItem') - ->with($this->stringContains('value'), $this->stringContains('key'), $this->equalTo($options)) + ->with($this->stringContains('key'), $this->stringContains('value'), $this->equalTo($options)) ->will($this->returnValue(false)); $this->assertFalse($this->_storage->addItems($items, $options)); @@ -445,7 +438,7 @@ public function testReplaceItems() ->will($this->returnValue(true)); $this->_storage->expects($this->exactly(count($items))) ->method('setItem') - ->with($this->stringContains('value'), $this->stringContains('key'), $this->equalTo($options)) + ->with($this->stringContains('key'), $this->stringContains('value'), $this->equalTo($options)) ->will($this->returnValue(true)); $this->assertTrue($this->_storage->replaceItems($items, $options)); @@ -467,7 +460,7 @@ public function testReplaceItemsFail() ->will($this->returnValue(true)); $this->_storage->expects($this->exactly(count($items))) ->method('setItem') - ->with($this->stringContains('value'), $this->stringContains('key'), $this->equalTo($options)) + ->with($this->stringContains('key'), $this->stringContains('value'), $this->equalTo($options)) ->will($this->returnValue(false)); $this->assertFalse($this->_storage->replaceItems($items, $options)); diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 75414423d..379ca22bd 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -90,7 +90,7 @@ public function testGetItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabl $ttl = $capabilities->getTtlPrecision(); $this->_storage->setTtl($ttl); - $this->_storage->setItem('value', 'key'); + $this->_storage->setItem('key', 'value'); // wait until expired $wait = $ttl + $capabilities->getTtlPrecision(); @@ -104,13 +104,13 @@ public function testGetItemReturnsFalseIfNonReadable() { $this->_storage->setReadable(false); - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertFalse($this->_storage->getItem('key')); } public function testGetMetadata() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertInternalType('array', $this->_storage->getMetadata('key')); } @@ -132,7 +132,7 @@ public function testGetMetadataReturnsFalseIfNonReadable() { $this->_storage->setReadable(false); - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertFalse($this->_storage->getMetadata('key')); } @@ -157,7 +157,7 @@ public function testGetMetadatasReturnsEmptyArrayIfNonReadable() { $this->_storage->setReadable(false); - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertEquals(array(), $this->_storage->getItems(array('key'))); } @@ -165,7 +165,7 @@ public function testGetMetadataAgainstMetadataCapabilities() { $capabilities = $this->_storage->getCapabilities(); - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $metadata = $this->_storage->getMetadata('key'); $this->assertInternalType('array', $metadata); @@ -176,7 +176,7 @@ public function testGetMetadataAgainstMetadataCapabilities() public function testSetGetHasAndRemoveItem() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertEquals('value', $this->_storage->getItem('key')); $this->assertTrue($this->_storage->hasItem('key')); $this->assertTrue($this->_storage->removeItem('key')); @@ -231,11 +231,11 @@ public function testSetGetHasAndRemoveItemWithNamespace() { // write "key" to default namespace $this->_storage->setNamespace('defaultns1'); - $this->assertTrue( $this->_storage->setItem('defaultns1', 'key') ); + $this->assertTrue( $this->_storage->setItem('key', 'defaultns1') ); // write "key" to an other default namespace $this->_storage->setNamespace('defaultns2'); - $this->assertTrue( $this->_storage->setItem('defaultns2', 'key') ); + $this->assertTrue( $this->_storage->setItem('key', 'defaultns2') ); // test value of defaultns2 $this->assertTrue($this->_storage->hasItem('key')); @@ -310,13 +310,13 @@ public function testSetGetHasAndRemoveItemWithSpecificNamespace() $this->_storage->setNamespace('defaultns'); // write "key" without a namespace - $this->assertTrue( $this->_storage->setItem('nons', 'key')); + $this->assertTrue( $this->_storage->setItem('key', 'nons')); // write "key" with a default namespace - $this->assertTrue( $this->_storage->setItem('ns1', 'key', array('namespace' => 'ns1'))); + $this->assertTrue( $this->_storage->setItem('key', 'ns1', array('namespace' => 'ns1'))); // write "key" with an other default namespace - $this->assertTrue( $this->_storage->setItem('ns2', 'key', array('namespace' => 'ns2'))); + $this->assertTrue( $this->_storage->setItem('key', 'ns2', array('namespace' => 'ns2'))); // test value of ns2 $this->assertEquals('ns2', $this->_storage->getItem('key', array('namespace' => 'ns2'))); @@ -394,7 +394,7 @@ public function testSetAndGetExpiredItem() $ttl = $capabilities->getTtlPrecision(); $this->_storage->setTtl($ttl); - $this->_storage->setItem('value', 'key'); + $this->_storage->setItem('key', 'value'); // wait until expired $wait = $ttl + $capabilities->getTtlPrecision(); @@ -468,7 +468,7 @@ public function testSetAndGetItemOfDifferentTypes() } $value = $types[$sourceType]; - $this->assertTrue($this->_storage->setItem($value, 'key'), "Failed to set type '{$sourceType}'"); + $this->assertTrue($this->_storage->setItem('key', $value), "Failed to set type '{$sourceType}'"); if ($targetType === true) { $this->assertSame($value, $this->_storage->getItem('key')); @@ -483,51 +483,51 @@ public function testSetItemReturnsFalseIfNonWritable() { $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->setItem('value', 'key')); + $this->assertFalse($this->_storage->setItem('key', 'value')); $this->assertFalse($this->_storage->hasItem('key')); } public function testAddNewItem() { - $this->assertTrue($this->_storage->addItem('value', 'key')); + $this->assertTrue($this->_storage->addItem('key', 'value')); $this->assertTrue($this->_storage->hasItem('key')); } public function testAddItemThrowsExceptionIfItemAlreadyExists() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->setExpectedException('Zend\Cache\Exception'); - $this->_storage->addItem('newValue', 'key'); + $this->_storage->addItem('key', 'newValue'); } public function testAddItemReturnsFalseIfNonWritable() { $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->addItem('value', 'key')); + $this->assertFalse($this->_storage->addItem('key', 'value')); $this->assertFalse($this->_storage->hasItem('key')); } public function testReplaceExistingItem() { - $this->assertTrue($this->_storage->setItem('value', 'key')); - $this->assertTrue($this->_storage->replaceItem('anOtherValue', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); + $this->assertTrue($this->_storage->replaceItem('key', 'anOtherValue')); $this->assertEquals('anOtherValue', $this->_storage->getItem('key')); } public function testReplaceItemThrowsItemNotFoundException() { $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); - $this->_storage->replaceItem('value', 'missingKey'); + $this->_storage->replaceItem('missingKey', 'value'); } public function testReplaceItemReturnsFalseIfNonWritable() { - $this->_storage->setItem('value', 'key'); + $this->_storage->setItem('key', 'value'); $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->replaceItem('newvalue', 'key')); + $this->assertFalse($this->_storage->replaceItem('key', 'newvalue')); $this->assertEquals('value', $this->_storage->getItem('key')); } @@ -549,7 +549,7 @@ public function testRemoveMissingItemThrowsExceptionIfIgnoreMissingItemsDisabled public function testRemoveMissingItemsReturnsTrueIfIgnoreMissingItemsEnabled() { $this->_storage->setIgnoreMissingItems(true); - $this->_storage->setItem('value', 'key'); + $this->_storage->setItem('key', 'value'); $this->assertTrue($this->_storage->removeItems(array('key', 'missing'))); } @@ -557,7 +557,7 @@ public function testRemoveMissingItemsReturnsTrueIfIgnoreMissingItemsEnabled() public function testRemoveMissingItemsThrowsExceptionIfIgnoreMissingItemsDisabled() { $this->_storage->setIgnoreMissingItems(false); - $this->_storage->setItem('value', 'key'); + $this->_storage->setItem('key', 'value'); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->removeItems(array('key', 'missing')); @@ -565,14 +565,14 @@ public function testRemoveMissingItemsThrowsExceptionIfIgnoreMissingItemsDisable public function testCheckAndSetItem() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $token = null; $this->assertEquals('value', $this->_storage->getItem('key', array('token' => &$token))); $this->assertNotNull($token); - $this->assertTrue($this->_storage->checkAndSetItem($token, 'newValue', 'key')); - $this->assertFalse($this->_storage->checkAndSetItem($token, 'failedValue', 'key')); + $this->assertTrue($this->_storage->checkAndSetItem($token, 'key', 'newValue')); + $this->assertFalse($this->_storage->checkAndSetItem($token, 'key', 'failedValue')); $this->assertEquals('newValue', $this->_storage->getItem('key')); } @@ -728,7 +728,7 @@ public function testGetDelayedWithCallbackAndSelectInfo() public function testGetDelayedThrowExceptionOnActiveStatement() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertTrue($this->_storage->getDelayed(array('key'))); $this->setExpectedException('Zend\Cache\Exception'); @@ -737,8 +737,8 @@ public function testGetDelayedThrowExceptionOnActiveStatement() public function testIncrementItem() { - $this->assertTrue($this->_storage->setItem(10, 'counter')); - $this->assertEquals(15, $this->_storage->incrementItem(5, 'counter')); + $this->assertTrue($this->_storage->setItem('counter', 10)); + $this->assertEquals(15, $this->_storage->incrementItem('counter', 5)); $this->assertEquals(15, $this->_storage->getItem('counter')); } @@ -746,7 +746,7 @@ public function testIncrementInitialValue() { $this->_storage->setIgnoreMissingItems(true); - $this->assertEquals(5, $this->_storage->incrementItem(5, 'counter')); + $this->assertEquals(5, $this->_storage->incrementItem('counter', 5)); $this->assertEquals(5, $this->_storage->getItem('counter')); } @@ -760,33 +760,33 @@ public function testIncrementItemThrowsItemNotFoundException() public function testIncrementItemReturnsFalseIfNonWritable() { - $this->_storage->setItem(10, 'key'); + $this->_storage->setItem('key', 10); $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->incrementItem(5, 'key')); + $this->assertFalse($this->_storage->incrementItem('key', 5)); $this->assertEquals(10, $this->_storage->getItem('key')); } public function testIncrementItemsReturnsFalseIfNonWritable() { - $this->_storage->setItem(10, 'key'); + $this->_storage->setItem('key', 10); $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->incrementItem(array('key' => 5))); + $this->assertFalse($this->_storage->incrementItems(array('key' => 5))); $this->assertEquals(10, $this->_storage->getItem('key')); } public function testDecrementItem() { - $this->assertTrue($this->_storage->setItem(30, 'counter')); - $this->assertEquals(25, $this->_storage->decrementItem(5, 'counter')); + $this->assertTrue($this->_storage->setItem('counter', 30)); + $this->assertEquals(25, $this->_storage->decrementItem('counter', 5)); $this->assertEquals(25, $this->_storage->getItem('counter')); } public function testDecrmentInitialValue() { $this->_storage->setIgnoreMissingItems(true); - $this->assertEquals(-5, $this->_storage->decrementItem(5, 'counter')); + $this->assertEquals(-5, $this->_storage->decrementItem('counter', 5)); $this->assertEquals(-5, $this->_storage->getItem('counter')); } @@ -799,16 +799,16 @@ public function testDecrementItemThrowsItemNotFoundException() public function testDecrementItemReturnsFalseIfNonWritable() { - $this->_storage->setItem(10, 'key'); + $this->_storage->setItem('key', 10); $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->decrementItem(5, 'key')); + $this->assertFalse($this->_storage->decrementItem('key', 5)); $this->assertEquals(10, $this->_storage->getItem('key')); } public function testDecrementItemsReturnsFalseIfNonWritable() { - $this->_storage->setItem(10, 'key'); + $this->_storage->setItem('key', 10); $this->_storage->setWritable(false); $this->assertFalse($this->_storage->decrementItems(array('key' => 5))); @@ -820,7 +820,7 @@ public function testTouchItem() $capabilities = $this->_storage->getCapabilities(); $this->_storage->setTtl(2 * $capabilities->getTtlPrecision()); - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); // sleep 1 times before expire to touch the item usleep($capabilities->getTtlPrecision() * 1000000); @@ -877,13 +877,13 @@ public function testClearExpiredByNamespace() $ttl = $capabilities->getTtlPrecision(); $this->_storage->setTtl($ttl); - $this->assertTrue($this->_storage->setItem('value1', 'key1')); + $this->assertTrue($this->_storage->setItem('key1', 'value1')); // wait until the first item expired $wait = $ttl + $capabilities->getTtlPrecision(); usleep($wait * 1000000); - $this->assertTrue($this->_storage->setItem('value2', 'key2')); + $this->assertTrue($this->_storage->setItem('key2', 'value2')); $this->assertTrue($this->_storage->clearByNamespace(Adapter::MATCH_EXPIRED)); @@ -908,13 +908,13 @@ public function testClearActiveByNamespace() $ttl = $capabilities->getTtlPrecision(); $this->_storage->setTtl($ttl); - $this->assertTrue($this->_storage->setItem('value1', 'key1')); + $this->assertTrue($this->_storage->setItem('key1', 'value1')); // wait until the first item expired $wait = $ttl + $capabilities->getTtlPrecision(); usleep($wait * 1000000); - $this->assertTrue($this->_storage->setItem('value2', 'key2')); + $this->assertTrue($this->_storage->setItem('key2', 'value2')); $this->assertTrue($this->_storage->clearByNamespace(Adapter::MATCH_ACTIVE)); @@ -943,7 +943,7 @@ public function testClearAllByNamespace() foreach ($namespaces as $ns) { $this->_storage->setNamespace($ns); foreach ($items as $k => $v) { - $this->assertTrue($this->_storage->setItem($ns.$v, $ns.$k)); + $this->assertTrue($this->_storage->setItem($ns.$k, $ns.$v)); } } @@ -985,7 +985,7 @@ public function testClearAll() foreach ($namespaces as $ns) { $this->_storage->setNamespace($ns); foreach ($items as $k => $v) { - $this->assertTrue($this->_storage->setItem($ns.$v, $ns.$k)); + $this->assertTrue($this->_storage->setItem($ns.$k, $ns.$v)); } } @@ -1011,14 +1011,14 @@ public function testFindActive() $this->_storage->setTtl($capabilities->getTtlPrecision()); - $this->assertTrue($this->_storage->setItem('value1', 'key1')); - $this->assertTrue($this->_storage->setItem('value2', 'key2')); + $this->assertTrue($this->_storage->setItem('key1', 'value1')); + $this->assertTrue($this->_storage->setItem('key2', 'value2')); // wait until first 2 items expired usleep(($capabilities->getTtlPrecision() * 1000000) + 1000000); - $this->assertTrue($this->_storage->setItem('value3', 'key3')); - $this->assertTrue($this->_storage->setItem('value4', 'key4')); + $this->assertTrue($this->_storage->setItem('key3', 'value3')); + $this->assertTrue($this->_storage->setItem('key4', 'value4')); $this->assertTrue($this->_storage->find(Adapter::MATCH_ACTIVE)); @@ -1058,14 +1058,14 @@ public function testFindExpired() $this->_storage->setTtl($capabilities->getTtlPrecision()); - $this->assertTrue($this->_storage->setItem('value1', 'key1')); - $this->assertTrue($this->_storage->setItem('value2', 'key2')); + $this->assertTrue($this->_storage->setItem('key1', 'value1')); + $this->assertTrue($this->_storage->setItem('key2', 'value2')); // wait until first 2 items expired usleep($capabilities->getTtlPrecision() * 1000000); - $this->assertTrue($this->_storage->setItem('value3', 'key3')); - $this->assertTrue($this->_storage->setItem('value4', 'key4')); + $this->assertTrue($this->_storage->setItem('key3', 'value3')); + $this->assertTrue($this->_storage->setItem('key4', 'value4')); $this->assertTrue($this->_storage->find(Adapter::MATCH_EXPIRED)); @@ -1094,7 +1094,7 @@ public function testFindExpired() public function testHasItemWithNonReadable() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->_storage->setReadable(false); $this->assertFalse($this->_storage->hasItem('key')); @@ -1102,7 +1102,7 @@ public function testHasItemWithNonReadable() public function testHasItemsWithNonReadable() { - $this->assertTrue($this->_storage->setItem('value', 'key')); + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->_storage->setReadable(false); $this->assertEquals(array(), $this->_storage->hasItems(array('key'))); @@ -1130,18 +1130,4 @@ public function testOptimizeSimpleCall() $this->assertTrue($rs); } - public function testGetLastKey() - { - $this->_storage->hasItem('key'); // set the last key - $this->assertEquals('key', $this->_storage->getLastKey()); - - $this->assertTrue($this->_storage->setItem('value')); - $this->assertTrue($this->_storage->hasItem()); - $this->assertEquals('value', $this->_storage->getItem()); - $this->assertInternalType('array', $this->_storage->getMetadata()); - - $this->assertTrue($this->_storage->removeItem()); - $this->assertFalse($this->_storage->hasItem()); - } - } diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index ee54c08e9..58ee92e77 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -78,7 +78,8 @@ public function testOptimizeByFactor() $event = new PostEvent('removeItem.post', $adapter, array( 'options' => array() )); - $event->setResult(true); + $result = true; + $event->setResult($result); $this->_plugin->optimizeByFactor($event); $this->assertTrue($event->getResult()); diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index a1f76f442..629fbbba8 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -79,10 +79,10 @@ public function testChangePluginBroker() public function testPluginFactory() { - $cache = Cache\StorageFactory::pluginFactory('IgnoreUserAbort', array( + $cache = Cache\StorageFactory::pluginFactory('Serializer', array( 'adapter' => Cache\StorageFactory::adapterFactory('Memory'), )); - $this->assertInstanceOf('Zend\Cache\Storage\Plugin\IgnoreUserAbort', $cache); + $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $cache); } public function testFactoryAdapterAsString() @@ -106,7 +106,7 @@ public function testFactoryAdapterAsArray() public function testFactoryWithPlugins() { $adapter = 'Memory'; - $plugins = array('Serialize', 'IgnoreUserAbort'); + $plugins = array('Serialize', 'ClearByFactor'); $cache = Cache\StorageFactory::factory(array( 'adapter' => $adapter, @@ -142,8 +142,8 @@ public function testFactoryWithPluginsAndOptionsArray() ), 'plugins' => array( 'Serialize' => array(), - 'IgnoreUserAbort' => array( - 'exit_on_abort' => true, + 'ClearByFactor' => array( + 'clearing_factor' => 1, ), ), 'options' => array( @@ -159,8 +159,8 @@ public function testFactoryWithPluginsAndOptionsArray() // test plugin options switch (get_class($storage)) { - case 'Zend\Cache\Storage\Plugin\IgnoreUserAbort': - $this->assertSame($factory['plugins']['IgnoreUserAbort']['exit_on_abort'], $storage->getExitOnAbort()); + case 'Zend\Cache\Storage\Plugin\ClearByFactor': + $this->assertSame($factory['plugins']['ClearByFactor']['clearing_factor'], $storage->getClearingFactor()); break; } From ee1aa87d2e86f522c83f5993bbd728197616f2f5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 4 Dec 2011 13:37:56 +0100 Subject: [PATCH 108/311] fixed storage factory --- src/Storage/PluginLoader.php | 38 ++++++++++++------------- src/StorageFactory.php | 14 +++++----- test/StorageFactoryTest.php | 54 +++++++++++++++--------------------- 3 files changed, 48 insertions(+), 58 deletions(-) diff --git a/src/Storage/PluginLoader.php b/src/Storage/PluginLoader.php index e97fb4b43..fa5448310 100644 --- a/src/Storage/PluginLoader.php +++ b/src/Storage/PluginLoader.php @@ -33,30 +33,30 @@ class PluginLoader extends PluginClassLoader { /** - * @var array Pre-aliased adapters + * @var array Pre-aliased adapters */ protected $plugins = array( 'clear_by_factor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', 'clearbyfactor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', - 'exception_handler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', - 'exceptionhandler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', - 'filter' => 'Zend\Cache\Storage\Plugin\Filter', - 'ignore_user_abort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', - 'ignoreuserabort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', - 'key_filter' => 'Zend\Cache\Storage\Plugin\KeyFilter', - 'keyfilter' => 'Zend\Cache\Storage\Plugin\KeyFilter', - 'levels' => 'Zend\Cache\Storage\Plugin\Levels', - 'locking' => 'Zend\Cache\Storage\Plugin\Locking', - 'master_file' => 'Zend\Cache\Storage\Plugin\MasterFile', - 'masterfile' => 'Zend\Cache\Storage\Plugin\MasterFile', + //'exception_handler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', + //'exceptionhandler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', + //'filter' => 'Zend\Cache\Storage\Plugin\Filter', + //'ignore_user_abort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', + //'ignoreuserabort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', + //'key_filter' => 'Zend\Cache\Storage\Plugin\KeyFilter', + //'keyfilter' => 'Zend\Cache\Storage\Plugin\KeyFilter', + //'levels' => 'Zend\Cache\Storage\Plugin\Levels', + //'locking' => 'Zend\Cache\Storage\Plugin\Locking', + //'master_file' => 'Zend\Cache\Storage\Plugin\MasterFile', + //'masterfile' => 'Zend\Cache\Storage\Plugin\MasterFile', 'optimize_by_factor' => 'Zend\Cache\Storage\Plugin\OptimizeByFactor', 'optimizebyfactor' => 'Zend\Cache\Storage\Plugin\OptimizeByFactor', - 'reluctant' => 'Zend\Cache\Storage\Plugin\Reluctant', - 'serialize' => 'Zend\Cache\Storage\Plugin\Serialize', - 'store_times' => 'Zend\Cache\Storage\Plugin\StoreTimes', - 'storetimes' => 'Zend\Cache\Storage\Plugin\StoreTimes', - 'tagging' => 'Zend\Cache\Storage\Plugin\Tagging', - 'write_control' => 'Zend\Cache\Storage\Plugin\WriteControl', - 'writecontrol' => 'Zend\Cache\Storage\Plugin\WriteControl', + //'reluctant' => 'Zend\Cache\Storage\Plugin\Reluctant', + 'serializer' => 'Zend\Cache\Storage\Plugin\Serializer', + //'store_times' => 'Zend\Cache\Storage\Plugin\StoreTimes', + //'storetimes' => 'Zend\Cache\Storage\Plugin\StoreTimes', + //'tagging' => 'Zend\Cache\Storage\Plugin\Tagging', + //'write_control' => 'Zend\Cache\Storage\Plugin\WriteControl', + //'writecontrol' => 'Zend\Cache\Storage\Plugin\WriteControl', ); } diff --git a/src/StorageFactory.php b/src/StorageFactory.php index ad727c95d..2d96ffca1 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -27,6 +27,8 @@ class StorageFactory * This can instantiate storage adapters and plugins. * * @param array|\Zend\Config $cfg + * @return Zend\Cache\Storage\Adapter + * @throws Zend\Cache\RuntimeException */ public static function factory($cfg) { @@ -67,8 +69,7 @@ public static function factory($cfg) ); } - $plugins = array_reverse($cfg['plugins']); - foreach ($plugins as $k => $v) { + foreach ($cfg['plugins'] as $k => $v) { if (is_string($k)) { $name = $k; if (!is_array($v)) { @@ -77,7 +78,6 @@ public static function factory($cfg) ); } $options = $v; - $options['storage'] = $adapter; } elseif (is_array($v)) { if (!isset($v['name'])) { throw new InvalidArgumentException("Invalid plugins[{$k}] or missing plugins[{$k}].name"); @@ -85,16 +85,16 @@ public static function factory($cfg) $name = (string)$v['name']; if (isset($v['options'])) { $options = $v['options']; - $options['storage'] = $adapter; } else { - $options = array('storage' => $adapter); + $options = array(); } } else { $name = $v; - $options = array('storage' => $adapter); + $options = array(); } - $adapter = self::pluginFactory($name, $options); + $plugin = self::pluginFactory($name, $options); + $adapter->addPlugin($plugin); } } diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index 629fbbba8..dd1ef581a 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -79,10 +79,8 @@ public function testChangePluginBroker() public function testPluginFactory() { - $cache = Cache\StorageFactory::pluginFactory('Serializer', array( - 'adapter' => Cache\StorageFactory::adapterFactory('Memory'), - )); - $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $cache); + $plugin = Cache\StorageFactory::pluginFactory('Serializer'); + $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $plugin); } public function testFactoryAdapterAsString() @@ -106,28 +104,20 @@ public function testFactoryAdapterAsArray() public function testFactoryWithPlugins() { $adapter = 'Memory'; - $plugins = array('Serialize', 'ClearByFactor'); + $plugins = array('Serializer', 'ClearByFactor'); $cache = Cache\StorageFactory::factory(array( 'adapter' => $adapter, 'plugins' => $plugins, )); - // test returned class - $this->assertInstanceOf('Zend\Cache\Storage\Adapter', $cache); + // test adapter + $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $cache); // test plugin structure - $i = 0; - $plugin = $cache; - do { + foreach ($cache->getPlugins() as $i => $plugin) { $this->assertInstanceOf('Zend\Cache\Storage\Plugin\\' . $plugins[$i], $plugin); - - $plugin = $plugin->getStorage(); - $i++; - } while ($plugin instanceof Cache\Storage\Plugin); - - // test adapter - $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $plugin); + } } public function testFactoryWithPluginsAndOptionsArray() @@ -141,7 +131,7 @@ public function testFactoryWithPluginsAndOptionsArray() ), ), 'plugins' => array( - 'Serialize' => array(), + 'Serializer', 'ClearByFactor' => array( 'clearing_factor' => 1, ), @@ -152,28 +142,28 @@ public function testFactoryWithPluginsAndOptionsArray() ); $storage = Cache\StorageFactory::factory($factory); + // test adapter + $this->assertInstanceOf('Zend\Cache\Storage\Adapter\\' . $factory['adapter']['name'], $storage); + $this->assertEquals(123, $storage->getTtl()); + $this->assertEquals('test', $storage->getNamespace()); + // test plugin structure - $i = 0; - do { - $this->assertInstanceOf('Zend\\Cache\Storage\Plugin', $storage); + foreach ($storage->getPlugins() as $i => $plugin) { // test plugin options - switch (get_class($storage)) { + $pluginClass = get_class($plugin); + switch ($pluginClass) { case 'Zend\Cache\Storage\Plugin\ClearByFactor': - $this->assertSame($factory['plugins']['ClearByFactor']['clearing_factor'], $storage->getClearingFactor()); + $this->assertSame($factory['plugins']['ClearByFactor']['clearing_factor'], $plugin->getClearingFactor()); break; + case 'Zend\Cache\Storage\Plugin\Serializer': + break; + default: + $this->fail("Unexpected plguin class '{$pluginClass}'"); } - $storage = $storage->getStorage(); - $i++; - } while ($storage instanceof Cache\Storage\Plugin); - - // test adapter - $this->assertInstanceOf('Zend\Cache\Storage\Adapter\\' . $factory['adapter']['name'], $storage); + } - // test adapter options - $this->assertEquals(123, $storage->getTtl()); - $this->assertEquals('test', $storage->getNamespace()); } } From 776b4ca5e7b75786dd0def1b8f12487e29614e2f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 4 Dec 2011 14:36:16 +0100 Subject: [PATCH 109/311] - more strict type hints on events - simplified usage of post events (triggerPost directly returns the result) - added exception events (ExceptionEvent, triggerException) - set identifiers to event manager --- src/Storage/Adapter/AbstractAdapter.php | 46 +- src/Storage/Adapter/Memory.php | 815 ++++++++++--------- src/Storage/Event.php | 19 +- src/Storage/ExceptionEvent.php | 115 +++ src/Storage/PostEvent.php | 18 + test/Storage/Adapter/AbstractAdapterTest.php | 28 +- test/Storage/Plugin/ClearByFactorTest.php | 19 +- test/Storage/Plugin/OptimizeByFactorTest.php | 11 +- test/Storage/Plugin/SerializerTest.php | 10 +- 9 files changed, 665 insertions(+), 416 deletions(-) create mode 100644 src/Storage/ExceptionEvent.php diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 05408d1fc..9d6f241c8 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -1,11 +1,11 @@ _events === null) { - $this->_events = new EventManager(); + $this->_events = new EventManager(array(__CLASS__, get_class($this))); } return $this->_events; } /** - * Trigger an pre event + * Trigger an pre event and return the event response collection * * @param string $eventName * @param ArrayObject $args @@ -427,23 +427,49 @@ protected function triggerPre($eventName, \ArrayObject $args) } /** - * Trigger an post event + * Triggers the PostEvent and return the result value. * * @param string $eventName * @param ArrayObject $args * @param mixed $result - * @return Zend\Cache\Storage\PostEvent All handler return values + * @return mixed */ protected function triggerPost($eventName, \ArrayObject $args, &$result) { - $postEvent = new PostEvent($eventName . '.post', $this, $args); - $postEvent->setResult($result); + $postEvent = new PostEvent($eventName . '.post', $this, $args, $result); $eventRs = $this->events()->trigger($postEvent); if ($eventRs->stopped()) { - $result = $eventRs->last(); - $postEvent->setResult($result); + return $eventRs->last(); } - return $postEvent; + + return $postEvent->getResult(); + } + + /** + * Trigger an exception event + * + * If the ExceptionEvent has the flag "throwException" enabled throw the + * exception after trigger else return the result. + * + * @param string $eventName + * @param ArrayObject $args + * @param Exception $exception + * @return mixed + */ + protected function triggerException($eventName, \ArrayObject $args, $exception) + { + $exceptionEvent = new ExceptionEvent($eventName . '.exception', $this, $args, $exception); + $eventRs = $this->events()->trigger($exceptionEvent); + + if ($exceptionEvent->getThrowException()) { + throw $exceptionEvent->getException(); + } + + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + return $exceptionEvent->getResult(); } /** diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 5218aa78a..1bad31ead 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -44,33 +44,36 @@ public function getItem($key, array $options = array()) 'options' => & $options )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - $exist = isset($this->_data[$ns][$key]); - if ($exist) { - if ($options['ttl'] && microtime(true) >= ($this->_data[$ns][$key][1] + $options['ttl']) ) { - $exist = false; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - } - if (!$exist) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); + $ns = $options['namespace']; + $exist = isset($this->_data[$ns][$key]); + if ($exist) { + if ($options['ttl'] && microtime(true) >= ($this->_data[$ns][$key][1] + $options['ttl']) ) { + $exist = false; + } } - $result = false; - } else { - $result = $this->_data[$ns][$key][0]; - if (array_key_exists('token', $options)) { - $options['token'] = $this->_data[$ns][$key][0]; + + if (!$exist) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); + } + $result = false; + } else { + $result = $this->_data[$ns][$key][0]; + if (array_key_exists('token', $options)) { + $options['token'] = $this->_data[$ns][$key][0]; + } } - } - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function getItems(array $keys, array $options = array()) @@ -85,31 +88,34 @@ public function getItems(array $keys, array $options = array()) 'options' => & $options )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { - $result = array(); - } else { - $data = &$this->_data[$ns]; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $keyValuePairs = array(); - foreach ($keys as $key) { - if (isset($data[$key])) { - if (!$options['ttl'] || microtime(true) < ($this->_data[$ns][$key][1] + $options['ttl']) ) { - $keyValuePairs[$key] = $data[$key][0]; + $ns = $options['namespace']; + if (!isset($this->_data[$ns])) { + $result = array(); + } else { + $data = &$this->_data[$ns]; + + $keyValuePairs = array(); + foreach ($keys as $key) { + if (isset($data[$key])) { + if (!$options['ttl'] || microtime(true) < ($this->_data[$ns][$key][1] + $options['ttl']) ) { + $keyValuePairs[$key] = $data[$key][0]; + } } } + + $result = $keyValuePairs; } - $result = $keyValuePairs; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); } public function hasItem($key, array $options = array()) @@ -125,15 +131,18 @@ public function hasItem($key, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $result = $this->_exists($key, $options); + $result = $this->_exists($key, $options); - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function getMetadata($key, array $options = array()) @@ -149,28 +158,31 @@ public function getMetadata($key, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - if (!$this->_exists($key, $options)) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( - "Key '{$key}' not found on namespace '{$options['namespace']}'" + if (!$this->_exists($key, $options)) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException( + "Key '{$key}' not found on namespace '{$options['namespace']}'" + ); + } + $result = false; + } else { + $ns = $options['namespace']; + $result = array( + 'mtime' => $this->_data[$ns][$key][1], + 'tags' => $this->_data[$ns][$key][2], ); } - $result = false; - } else { - $ns = $options['namespace']; - $result = array( - 'mtime' => $this->_data[$ns][$key][1], - 'tags' => $this->_data[$ns][$key][2], - ); - } - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* writing */ @@ -189,17 +201,20 @@ public function setItem($key, $value, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); + $ns = $options['namespace']; + $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function setItems(array $keyValuePairs, array $options = array()) @@ -214,24 +229,27 @@ public function setItems(array $keyValuePairs, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { - $this->_data[$ns] = array(); - } + $ns = $options['namespace']; + if (!isset($this->_data[$ns])) { + $this->_data[$ns] = array(); + } - $data = & $this->_data[$ns]; - foreach ($keyValuePairs as $key => $value) { - $data[$key] = array($value, microtime(true), $options['tags']); - } + $data = & $this->_data[$ns]; + foreach ($keyValuePairs as $key => $value) { + $data[$key] = array($value, microtime(true), $options['tags']); + } - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function addItem($key, $value, array $options = array()) @@ -248,20 +266,23 @@ public function addItem($key, $value, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (isset($this->_data[$ns][$key])) { - throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); - } - $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); + $ns = $options['namespace']; + if (isset($this->_data[$ns][$key])) { + throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); + } + $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function addItems(array $keyValuePairs, array $options = array()) @@ -276,27 +297,30 @@ public function addItems(array $keyValuePairs, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { - $this->_data[$ns] = array(); - } + $ns = $options['namespace']; + if (!isset($this->_data[$ns])) { + $this->_data[$ns] = array(); + } - $data = & $this->_data[$ns]; - foreach ($keyValuePairs as $key => $value) { - if (isset($data[$key])) { - throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); + $data = & $this->_data[$ns]; + foreach ($keyValuePairs as $key => $value) { + if (isset($data[$key])) { + throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); + } + $data[$key] = array($value, microtime(true), $options['tags']); } - $data[$key] = array($value, microtime(true), $options['tags']); - } - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function replaceItem($key, $value, array $options = array()) @@ -313,20 +337,23 @@ public function replaceItem($key, $value, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (!isset($this->_data[$ns][$key])) { - throw new ItemNotFoundException("Key '{$key}' doen't exists within namespace '$ns'"); - } - $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); + $ns = $options['namespace']; + if (!isset($this->_data[$ns][$key])) { + throw new ItemNotFoundException("Key '{$key}' doen't exists within namespace '$ns'"); + } + $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function replaceItems(array $keyValuePairs, array $options = array()) @@ -341,29 +368,32 @@ public function replaceItems(array $keyValuePairs, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { - throw new ItemNotFoundException("Namespace '$ns' doesn't exist"); - } + $ns = $options['namespace']; + if (!isset($this->_data[$ns])) { + throw new ItemNotFoundException("Namespace '$ns' doesn't exist"); + } - $data = & $this->_data[$ns]; - foreach ($keyValuePairs as $key => $value) { - if (!isset($data[$key])) { - throw new ItemNotFoundException( - "Key '{$key}' doen't exists within namespace '$ns'" - ); + $data = & $this->_data[$ns]; + foreach ($keyValuePairs as $key => $value) { + if (!isset($data[$key])) { + throw new ItemNotFoundException( + "Key '{$key}' doen't exists within namespace '$ns'" + ); + } + $data[$key] = array($value, microtime(true), $options['tags']); } - $data[$key] = array($value, microtime(true), $options['tags']); - } - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function touchItem($key, array $options = array()) @@ -379,29 +409,32 @@ public function touchItem($key, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (isset($this->_data[$ns][$key])) { - // update mtime - $this->_data[$ns][$key][1] = microtime(true); - } else { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( - "Key '{$key}' not found within namespace '{$ns}'" - ); + $ns = $options['namespace']; + if (isset($this->_data[$ns][$key])) { + // update mtime + $this->_data[$ns][$key][1] = microtime(true); + } else { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException( + "Key '{$key}' not found within namespace '{$ns}'" + ); + } + + // add an empty item + $this->_data[$ns][$key] = array('', microtime(true), null); } - // add an empty item - $this->_data[$ns][$key] = array('', microtime(true), null); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); } public function removeItem($key, array $options = array()) @@ -417,29 +450,32 @@ public function removeItem($key, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - if (isset($this->_data[$ns][$key])) { - unset($this->_data[$ns][$key]); + $ns = $options['namespace']; + if (isset($this->_data[$ns][$key])) { + unset($this->_data[$ns][$key]); - // remove empty namespace - if (!$this->_data[$ns]) { - unset($this->_data[$ns]); - } + // remove empty namespace + if (!$this->_data[$ns]) { + unset($this->_data[$ns]); + } - } else { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); + } else { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); + } } - } - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function removeItems(array $keys, array $options = array()) @@ -454,48 +490,51 @@ public function removeItems(array $keys, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if ($options['ignore_missing_items'] === false) { - if (!isset($this->_data[$ns])) { - throw new ItemNotFoundException("Namespace '{$ns}' is empty"); + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - $data = &$this->_data[$ns]; + $ns = $options['namespace']; + if ($options['ignore_missing_items'] === false) { + if (!isset($this->_data[$ns])) { + throw new ItemNotFoundException("Namespace '{$ns}' is empty"); + } - $missingItems = null; - foreach ($keys as $key) { - if (isset($data[$key])) { + $data = &$this->_data[$ns]; + + $missingItems = null; + foreach ($keys as $key) { + if (isset($data[$key])) { + unset($data[$key]); + } else { + $missingItems[] = $key; + } + } + + if ($missingItems) { + throw new ItemNotFoundException( + "Keys '" . implode("','", $missingItems) . "' not found on namespace '{$ns}'" + ); + } + } elseif (isset($this->_data[$ns])) { + $data = & $this->_data[$ns]; + foreach ($keys as $key) { unset($data[$key]); - } else { - $missingItems[] = $key; } - } - if ($missingItems) { - throw new ItemNotFoundException( - "Keys '" . implode("','", $missingItems) . "' not found on namespace '{$ns}'" - ); - } - } elseif (isset($this->_data[$ns])) { - $data = & $this->_data[$ns]; - foreach ($keys as $key) { - unset($data[$key]); + // remove empty namespace + if (!$data) { + unset($this->_data[$ns]); + } } - // remove empty namespace - if (!$data) { - unset($this->_data[$ns]); - } + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); } public function incrementItem($key, $value, array $options = array()) @@ -513,31 +552,34 @@ public function incrementItem($key, $value, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - $data = & $this->_data[$ns]; - if (isset($data[$key])) { - $data[$key][0]+= $value; - $data[$key][1] = microtime(true); - $result = $data[$key][0]; - } else { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( - "Key '{$key}' not found within namespace '{$ns}'" - ); + $ns = $options['namespace']; + $data = & $this->_data[$ns]; + if (isset($data[$key])) { + $data[$key][0]+= $value; + $data[$key][1] = microtime(true); + $result = $data[$key][0]; + } else { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException( + "Key '{$key}' not found within namespace '{$ns}'" + ); + } + + // add a new item + $data[$key] = array($value, microtime(true), null); + $result = $value; } - // add a new item - $data[$key] = array($value, microtime(true), null); - $result = $value; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); } public function decrementItem($key, $value, array $options = array()) @@ -555,31 +597,34 @@ public function decrementItem($key, $value, array $options = array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ns = $options['namespace']; - $data = & $this->_data[$ns]; - if (isset($data[$key])) { - $data[$key][0]-= $value; - $data[$key][1] = microtime(true); - $result = $data[$key][0]; - } else { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( - "Key '{$key}' not found within namespace '{$ns}'" - ); + $ns = $options['namespace']; + $data = & $this->_data[$ns]; + if (isset($data[$key])) { + $data[$key][0]-= $value; + $data[$key][1] = microtime(true); + $result = $data[$key][0]; + } else { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException( + "Key '{$key}' not found within namespace '{$ns}'" + ); + } + + // add a new item + $data[$key] = array(-$value, microtime(true), null); + $result = -$value; } - // add a new item - $data[$key] = array(-$value, microtime(true), null); - $result = -$value; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); } /* non-blocking */ @@ -601,65 +646,68 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $tags = & $options['tags']; - $emptyTags = $keys = array(); - foreach ($this->_data[ $options['namespace'] ] as $key => &$item) { + $tags = & $options['tags']; + $emptyTags = $keys = array(); + foreach ($this->_data[ $options['namespace'] ] as $key => &$item) { - // compare expired / active - if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { + // compare expired / active + if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { - // if MATCH_EXPIRED -> filter active items - if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($this->_exists($key, $options)) { - continue; - } + // if MATCH_EXPIRED -> filter active items + if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { + if ($this->_exists($key, $options)) { + continue; + } - // if MATCH_ACTIVE -> filter expired items - } else { - if (!$this->_exists($key, $options)) { - continue; + // if MATCH_ACTIVE -> filter expired items + } else { + if (!$this->_exists($key, $options)) { + continue; + } } } - } - // compare tags - if ($tags !== null) { - $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; + // compare tags + if ($tags !== null) { + $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; - if ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); - } elseif ( ($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - $matched = (count(array_diff($tags, $tagsStored)) == 0); - } + if ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { + $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); + } elseif ( ($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { + $matched = (count(array_diff($tags, $tagsStored)) == 0); + } - // negate - if ( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - $matched = !$matched; - } + // negate + if ( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { + $matched = !$matched; + } - if (!$matched) { - continue; + if (!$matched) { + continue; + } } - } - $keys[] = $key; - } + $keys[] = $key; + } - // don't check expiry on fetch - $options['ttl'] = 0; + // don't check expiry on fetch + $options['ttl'] = 0; - $this->_stmtKeys = $keys; - $this->_stmtOptions = $options; - $this->_stmtActive = true; + $this->_stmtKeys = $keys; + $this->_stmtOptions = $options; + $this->_stmtActive = true; - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function fetch() @@ -668,57 +716,60 @@ public function fetch() return false; } - $args = new \ArrayObject(); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $args = new \ArrayObject(); + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $options = & $this->_stmtOptions; + $options = & $this->_stmtOptions; - // get the next valid item - do { - $key = array_shift($this->_stmtKeys); - if ($key === null) { + // get the next valid item + do { + $key = array_shift($this->_stmtKeys); + if ($key === null) { + break; + } + if (!$this->_exists($key, $options)) { + continue; + } + $ref = & $this->_data[ $options['namespace'] ][$key]; break; - } - if (!$this->_exists($key, $options)) { - continue; - } - $ref = & $this->_data[ $options['namespace'] ][$key]; - break; - } while (true); - - // get item data - if ($key) { - $item = array(); - foreach ($options['select'] as $select) { - if ($select == 'key') { - $item['key'] = $key; - } elseif ($select == 'value') { - $item['value'] = $ref[0]; - } elseif ($select == 'mtime') { - $item['mtime'] = $ref[1]; - } elseif ($select == 'tags') { - $item['tags'] = $ref[2]; - } else { - $item[$select] = null; + } while (true); + + // get item data + if ($key) { + $item = array(); + foreach ($options['select'] as $select) { + if ($select == 'key') { + $item['key'] = $key; + } elseif ($select == 'value') { + $item['value'] = $ref[0]; + } elseif ($select == 'mtime') { + $item['mtime'] = $ref[1]; + } elseif ($select == 'tags') { + $item['tags'] = $ref[2]; + } else { + $item[$select] = null; + } } - } - $result = $item; + $result = $item; + + } else { + // free statement after last item + $this->_stmtActive = false; + $this->_stmtKeys = null; + $this->_stmtOptions = null; - } else { - // free statement after last item - $this->_stmtActive = false; - $this->_stmtKeys = null; - $this->_stmtOptions = null; + $result = false; + } - $result = false; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); } /* cleaning */ @@ -731,28 +782,30 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $this->_normalizeOptions($options); $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { - $this->_data = array(); - } else { - foreach ($this->_data as &$data) { - $this->_clearNamespacedDataArray($data, $mode, $options); + if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { + $this->_data = array(); + } else { + foreach ($this->_data as &$data) { + $this->_clearNamespacedDataArray($data, $mode, $options); + } } - } - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) @@ -763,28 +816,30 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $this->_normalizeOptions($options); $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options, )); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - if (isset($this->_data[ $options['namespace'] ])) { - if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { - unset($this->_data[ $options['namespace'] ]); - } else { - $this->_clearNamespacedDataArray($this->_data[ $options['namespace'] ], $mode, $options); + if (isset($this->_data[ $options['namespace'] ])) { + if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { + unset($this->_data[ $options['namespace'] ]); + } else { + $this->_clearNamespacedDataArray($this->_data[ $options['namespace'] ], $mode, $options); + } } - } - $result = true; - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } protected function _clearNamespacedDataArray(array &$data, $mode, &$options) @@ -878,8 +933,7 @@ public function getCapabilities() ); } - $postEvent = $this->triggerPost(__FUNCTION__, $args, $this->_capabilities); - return $postEvent->getResult(); + return $this->triggerPost(__FUNCTION__, $args, $this->_capabilities); } public function getCapacity(array $options = array()) @@ -895,8 +949,7 @@ public function getCapacity(array $options = array()) $result = Utils::getPhpMemoryCapacity(); - $postEvent = $this->triggerPost(__FUNCTION__, $args, $result); - return $postEvent->getResult(); + return $this->triggerPost(__FUNCTION__, $args, $result); } /* internal */ diff --git a/src/Storage/Event.php b/src/Storage/Event.php index 6f3f08c93..1510cf04c 100644 --- a/src/Storage/Event.php +++ b/src/Storage/Event.php @@ -1,11 +1,28 @@ setException($exception); + } + + /** + * Set the exception to be throw + * + * @param Exception $exception + */ + public function setException(Exception $exception) + { + $this->exception = $exception; + return $this; + } + + /** + * Get the exception to be throw + * + * @return Exception + */ + public function getException() + { + return $this->exception; + } + + /** + * Throw the exception or use the result + * + * @param boolean $flag + */ + public function setThrowException($flag) + { + $this->throwException = (bool)$flag; + return $this; + } + + /** + * Throw the exception or use the result + * + * @return boolean + */ + public function getThrowException() + { + return $this->throwException; + } + + /** + * Set the result/return value + * + * @param mixed $value + * @return Zend\Cache\Storage\PostEvent + */ + public function setResult(&$value) + { + $this->result = & $value; + return $this; + } + + /** + * Get the result/return value + * + * @return mixed + */ + public function & getResult() + { + return $this->result; + } + +} + diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index e147b27e5..7a08b3896 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -1,6 +1,7 @@ setResult($result); + } + /** * Set the result/return value * diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 17e009dff..6e37c5060 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -22,7 +22,8 @@ namespace ZendTest\Cache\Storage\Adapter; use ZendTest\Cache\Storage\CommonStorageTest, - Zend\Cache; + Zend\Cache, + Zend\Cache\Exception\RuntimeException; /** * @category Zend @@ -244,14 +245,15 @@ public function testInternalTriggerPost() // call protected method $method = new \ReflectionMethod(get_class($this->_storage), 'triggerPost'); $method->setAccessible(true); - $returnedEvent = $method->invokeArgs($this->_storage, array('setItem', $params, &$result)); + $result = $method->invokeArgs($this->_storage, array('setItem', $params, &$result)); // test called event $calledEvents = $plugin->getCalledEvents(); $this->assertEquals(1, count($calledEvents)); - $event = current($calledEvents); - $this->assertSame($returnedEvent, $event); + + // return value of triggerPost and the called event should be the same + $this->assertSame($result, $event->getResult()); $this->assertInstanceOf('Zend\Cache\Storage\PostEvent', $event); $this->assertEquals('setItem.post', $event->getName()); @@ -260,6 +262,24 @@ public function testInternalTriggerPost() $this->assertSame($result, $event->getResult()); } + public function testInternalTriggerExceptionThrowRuntimeException() + { + $plugin = new \ZendTest\Cache\Storage\TestAsset\MockPlugin(); + $this->_storage->addPlugin($plugin); + + $params = new \ArrayObject(array( + 'key' => 'key1', + 'value' => 'value1' + )); + + // call protected method + $method = new \ReflectionMethod(get_class($this->_storage), 'triggerException'); + $method->setAccessible(true); + + $this->setExpectedException('Zend\Cache\Exception\RuntimeException', 'test'); + $method->invokeArgs($this->_storage, array('setItem', $params, new RuntimeException('test'))); + } + public function testGetItems() { $options = array('ttl' => 123); diff --git a/test/Storage/Plugin/ClearByFactorTest.php b/test/Storage/Plugin/ClearByFactorTest.php index 6a95eff25..7945d7966 100644 --- a/test/Storage/Plugin/ClearByFactorTest.php +++ b/test/Storage/Plugin/ClearByFactorTest.php @@ -3,7 +3,8 @@ namespace ZendTest\Cache\Storage\Plugin; use Zend\Cache, Zend\Cache\Storage\PostEvent, - ZendTest\Cache\Storage\TestAsset\MockAdapter; + ZendTest\Cache\Storage\TestAsset\MockAdapter, + ArrayObject; class ClearByFactorTest extends \PHPUnit_Framework_TestCase { @@ -78,11 +79,11 @@ public function testClearByFactorUsingNamespace() ->will($this->returnValue(true)); // call event callback - $event = new PostEvent('setItem.post', $adapter, array( - 'options' => array(), - )); $result = true; - $event->setResult($result); + $event = new PostEvent('setItem.post', $adapter, new ArrayObject(array( + 'options' => array(), + )), $result); + $this->_plugin->clearByFactor($event); $this->assertTrue($event->getResult()); @@ -101,11 +102,11 @@ public function testClearByFactorAllNamespaces() ->will($this->returnValue(true)); // call event callback - $event = new PostEvent('setItem.post', $adapter, array( - 'options' => array(), - )); $result = true; - $event->setResult($result); + $event = new PostEvent('setItem.post', $adapter, new ArrayObject(array( + 'options' => array(), + )), $result); + $this->_plugin->clearByFactor($event); $this->assertTrue($event->getResult()); diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index 58ee92e77..c70a55505 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -3,7 +3,8 @@ namespace ZendTest\Cache\Storage\Plugin; use Zend\Cache, Zend\Cache\Storage\PostEvent, - ZendTest\Cache\Storage\TestAsset\MockAdapter; + ZendTest\Cache\Storage\TestAsset\MockAdapter, + ArrayObject; class OptimizeByFactorTest extends \PHPUnit_Framework_TestCase { @@ -75,11 +76,11 @@ public function testOptimizeByFactor() ->method('optimize'); // call event callback - $event = new PostEvent('removeItem.post', $adapter, array( - 'options' => array() - )); $result = true; - $event->setResult($result); + $event = new PostEvent('removeItem.post', $adapter, new ArrayObject(array( + 'options' => array() + )), $result); + $this->_plugin->optimizeByFactor($event); $this->assertTrue($event->getResult()); diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index ece691429..561dc805e 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -21,11 +21,11 @@ */ namespace ZendTest\Cache\Storage\Plugin; - use Zend\Cache, Zend\Cache\Storage\Event, Zend\Cache\Storage\PostEvent, - Zend\Serializer; + Zend\Serializer, + ArrayObject; /** * @category Zend @@ -112,8 +112,7 @@ public function testRemovePlugin() public function testUnserializeOnReadItem() { $value = serialize(123); - $event = new PostEvent('getItem.post', $this->_adapter, array()); - $event->setResult($value); + $event = new PostEvent('getItem.post', $this->_adapter, new ArrayObject(), $value); $this->_plugin->onReadItemPost($event); $this->assertFalse($event->propagationIsStopped()); @@ -123,8 +122,7 @@ public function testUnserializeOnReadItem() public function testUnserializeOnReadItems() { $values = array('key1' => serialize(123), 'key2' => serialize(456)); - $event = new PostEvent('getItems.post', $this->_adapter, array()); - $event->setResult($values); + $event = new PostEvent('getItems.post', $this->_adapter, new ArrayObject(), $values); $this->_plugin->onReadItemsPost($event); From 7d567e09b3cbd543220e8ab1302b5fefbb3da95f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 4 Dec 2011 15:35:01 +0100 Subject: [PATCH 110/311] fixed argument order of AbstractAdapter::[increment/decrement]Item --- src/Storage/Adapter/AbstractAdapter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 9d6f241c8..9b3ecc6c6 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -732,7 +732,7 @@ public function removeItems(array $keys, array $options = array()) return $ret; } - public function incrementItem($value, $key = null, array $options = array()) + public function incrementItem($key, $value, array $options = array()) { if (!$this->getWritable() || !$this->getReadable()) { return false; @@ -758,7 +758,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()) return $ret; } - public function decrementItem($value, $key = null, array $options = array()) + public function decrementItem($key, $value, array $options = array()) { if (!$this->getWritable() || !$this->getReadable()) { return false; From e2ddefb3c665237aefc943efd2b5d597048e2b21 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 5 Dec 2011 09:00:44 +0100 Subject: [PATCH 111/311] added filesystem adapter --- src/Storage/Adapter/Filesystem.php | 1825 +++++++++++++++++++++++ test/Storage/Adapter/FilesystemTest.php | 287 ++++ 2 files changed, 2112 insertions(+) create mode 100644 src/Storage/Adapter/Filesystem.php create mode 100644 test/Storage/Adapter/FilesystemTest.php diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php new file mode 100644 index 000000000..36efb79bb --- /dev/null +++ b/src/Storage/Adapter/Filesystem.php @@ -0,0 +1,1825 @@ +getNamespaceSeparator(); + $options['cache_dir'] = $this->getCacheDir(); + $options['file_perm'] = $this->getFilePerm(); + $options['file_umask'] = $this->getFileUmask(); + $options['file_locking'] = $this->getFileLocking(); + $options['file_blocking'] = $this->getFileBlocking(); + $options['dir_perm'] = $this->getDirPerm(); + $options['dir_umask'] = $this->getDirUmask(); + $options['dir_level'] = $this->getDirLevel(); + $options['no_atime'] = $this->getNoAtime(); + $options['no_ctime'] = $this->getNoCtime(); + $options['read_control'] = $this->getReadControl(); + $options['read_control_algo'] = $this->getReadControlAlgo(); + $options['clear_stat_cache'] = $this->getClearStatCache(); + return $options; + } + + public function setNamespaceSeparator($separator) + { + $this->_namespaceSeparator = (string)$separator; + $this->_updateCapabilities(); + return $this; + } + + public function getNamespaceSeparator() + { + return $this->_namespaceSeparator; + } + + public function setCacheDir($dir) + { + if ($dir !== null) { + if (!is_dir($dir)) { + throw new InvalidArgumentException( + "Cache directory '{$dir}' not found or not a directoy" + ); + } elseif (!is_writable($dir)) { + throw new InvalidArgumentException( + "Cache directory '{$dir}' not writable" + ); + } elseif (!is_readable($dir)) { + throw new InvalidArgumentException( + "Cache directory '{$dir}' not readable" + ); + } + + $dir = rtrim(realpath($dir), \DIRECTORY_SEPARATOR); + } + + $this->_cacheDir = $dir; + return $this; + } + + public function getCacheDir() + { + if ($this->_cacheDir === null) { + $this->setCacheDir(sys_get_temp_dir()); + } + + return $this->_cacheDir; + } + + public function setFilePerm($perm) + { + if (is_string($perm)) { + $perm = octdec($perm); + } else { + $perm = (int)$perm; + } + + // use umask + return $this->setFileUmask(~$perm); + } + + public function getFilePerm() + { + return ~$this->getFileUmask(); + } + + public function setFileUmask($umask) + { + if (is_string($umask)) { + $umask = octdec($umask); + } else { + $umask = (int)$umask; + } + if ((~$umask & 0600) != 0600 ) { + throw new InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'need permissions to read and write files by owner' + ); + } elseif ((~$umask & 0111) > 0) { + throw new InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'executable cache files are not allowed' + ); + } + + $this->_fileUmask = $umask; + return $this; + } + + public function getFileUmask() + { + return $this->_fileUmask; + } + + public function setFileLocking($flag) + { + $this->_fileLocking = (bool)$flag; + return $this; + } + + public function getFileLocking() + { + return $this->_fileLocking; + } + + public function setFileBlocking($flag) + { + $this->_fileBlocking = (bool)$flag; + return $this; + } + + public function getFileBlocking() + { + return $this->_fileBlocking; + } + + public function setNoAtime($flag) + { + $this->_noAtime = (bool)$flag; + $this->_updateCapabilities(); + return $this; + } + + public function getNoAtime() + { + return $this->_noAtime; + } + + public function setNoCtime($flag) + { + $this->_noCtime = (bool)$flag; + $this->_updateCapabilities(); + return $this; + } + + public function getNoCtime() + { + return $this->_noCtime; + } + + public function setDirPerm($perm) + { + if (is_string($perm)) { + $perm = octdec($perm); + } else { + $perm = (int)$perm; + } + + // use umask + return $this->setDirUmask(~$perm); + } + + public function getDirPerm() + { + return ~$this->getDirUmask(); + } + + public function setDirUmask($umask) + { + if (is_string($umask)) { + $umask = octdec($umask); + } else { + $umask = (int)$umask; + } + + if ((~$umask & 0700) != 0700 ) { + throw new InvalidArgumentException( + 'Invalid directory umask or directory permissions: ' + . 'need permissions to execute, read and write directories by owner' + ); + } + + $this->_dirUmask = $umask; + return $this; + } + + public function getDirUmask() + { + return $this->_dirUmask; + } + + public function setDirLevel($level) + { + $level = (int)$level; + if ($level < 0 || $level > 16) { + throw new InvalidArgumentException( + "Directory level '{$level}' have to be between 0 and 16" + ); + } + $this->_dirLevel = $level; + return $this; + } + + public function getDirLevel() + { + return $this->_dirLevel; + } + + public function setReadControl($flag) + { + $this->_readControl = (bool)$flag; + return $this; + } + + public function getReadControl() + { + return $this->_readControl; + } + + public function setReadControlAlgo($algo) + { + $algo = strtolower($algo); + + if (!in_array($algo, Utils::getHashAlgos())) { + throw new InvalidArgumentException("Unsupported hash algorithm '{$algo}"); + } + + $this->_readControlAlgo = $algo; + return $this; + } + + public function getReadControlAlgo() + { + return $this->_readControlAlgo; + } + + public function setClearStatCache($flag) + { + $this->_clearStatCache = (bool)$flag; + return $this; + } + + public function getClearStatCache() + { + return $this->_clearStatCache; + } + + /* reading */ + + public function getItem($key, array $options = array()) + { + if (!$this->getReadable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = $this->_get($key, $options); + if (array_key_exists('token', $options)) { + // use filemtime + filesize as CAS token + $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + $options['token'] = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function getItems(array $keys, array $options = array()) + { + if (!$this->getReadable()) { + return array(); + } + + $this->_normalizeOptions($options); + // don't throw ItemNotFoundException on getItems + $options['ignore_missing_items'] = true; + + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = array(); + foreach ($keys as $key) { + if ( ($rs = $this->_get($key, $options)) !== false) { + $result[$key] = $rs; + } + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function hasItem($key, array $options = array()) + { + if (!$this->getReadable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = $this->_exists($key, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function hasItems(array $keys, array $options = array()) + { + if (!$this->getReadable()) { + return array(); + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = array(); + foreach ($keys as $key) { + if ( $this->_exists($key, $options) === true ) { + $result[] = $key; + } + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function getMetadata($key, array $options = array()) + { + if (!$this->getReadable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $lastInfoId = $options['namespace'] . $this->getNamespaceSeparator() . $key; + if ($this->_lastInfoId == $lastInfoId && $this->_lastInfoAll) { + return $this->_lastInfoAll; + } + + $this->_lastInfoAll = $result = $this->_info($key, $options); + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function getMetadatas(array $keys, array $options = array()) + { + if (!$this->getReadable()) { + return array(); + } + + $this->_normalizeOptions($options); + // don't throw ItemNotFoundException on getMetadatas + $options['ignore_missing_items'] = true; + + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = array(); + foreach ($keys as $key) { + if ( ($info = $this->_info($key, $options)) !== false ) { + $result[$key] = $info; + } + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /* writing */ + + public function setItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = $this->_set($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function setItems(array $keyValuePairs, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = true; + foreach ($keyValuePairs as $key => $value) { + $result = $this->_set($key, $value, $options) && $result; + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function replaceItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + if ( !$this->_exists($key, $options) ) { + throw new ItemNotFoundException("Key '{$key}' doesn't exist"); + } + + $result = $this->_set($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function replaceItems(array $keyValuePairs, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = true; + foreach ($keyValuePairs as $key => $value) { + if ( !$this->_exists($key, $options) ) { + throw new ItemNotFoundException("Key '{$key}' doesn't exist"); + } + $result = $this->_set($key, $value, $options) && $result; + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function addItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + if ( $this->_exists($key, $options) ) { + throw new RuntimeException("Key '{$key}' already exist"); + } + + $result = $this->_set($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function addItems(array $keyValuePairs, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $result = true; + foreach ($keyValuePairs as $key => $value) { + if ( $this->_exists($key, $options) ) { + throw new RuntimeException("Key '{$key}' already exist"); + } + + $result = $this->_set($key, $value, $options) && $result; + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function checkAndSetItem($token, $key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'token' => & $token, + 'key' => & $key, + 'value' => & $value, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + if ( !($keyInfo = $this->_getKeyInfo($key, $options['namespace'])) ) { + if ($options['ignore_missing_items']) { + $result = false; + } else { + throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + } + } else { + // use filemtime + filesize as CAS token + $check = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); + if ($token != $check) { + $result = false; + } else { + $result = $this->_set($key, $value, $options); + } + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function touchItem($key, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $this->_touch($key, $options); + $this->_lastInfoId = null; + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function touchItems(array $keys, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + foreach ($keys as $key) { + $this->_touch($key, $options); + } + $this->_lastInfoId = null; + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function removeItem($key, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $key = $this->_key($key); + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + // unlink is not affected by clearstatcache + $this->_remove($key, $options); + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function removeItems(array $keys, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + // unlink is not affected by clearstatcache + foreach ($keys as $key) { + $this->_remove($key, $options); + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /* non-blocking */ + + public function find($mode = Adapter::MATCH_ACTIVE, array $options = array()) + { + if ($this->_stmtActive) { + throw new RuntimeException('Statement already in use'); + } + + if (!$this->getReadable()) { + return false; + } + + $this->_normalizeOptions($options); + $this->_normalizeMatchingMode($mode, Adapter::MATCH_ACTIVE, $options); + $options = array_merge($this->getOptions(), $options); + $args = new \ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $find = $options['cache_dir'] + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = glob($find, \GLOB_NOSORT | \GLOB_NOESCAPE); + if (!$glob) { + // On some systems glob returns false even on empty result + return true; + } + + $this->_stmtActive = true; + $this->_stmtGlob = $glob; + $this->_stmtMatch = $mode; + $this->_stmtOptions = $options; + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function fetch() + { + if (!$this->_stmtActive) { + return false; + } + + $args = new \ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->_stmtGlob !== null) { + $result = $this->_fetchByGlob(); + + if ($result === false) { + // clear statement + $this->_stmtActive = false; + $this->_stmtGlob = null; + $this->_stmtMatch = null; + $this->_stmtOptions = null; + } + } else { + $result = parent::fetch(); + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /* cleaning */ + + public function clear($mode = Adapter::MATCH_EXPIRED, array $options = array()) + { + $this->_normalizeOptions($options); + $this->_normalizeMatchingMode($mode, Adapter::MATCH_EXPIRED, $options); + $args = new \ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->_clearByPrefix('', $mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function clearByNamespace($mode = Adapter::MATCH_EXPIRED, array $options = array()) + { + $this->_normalizeOptions($options); + $this->_normalizeMatchingMode($mode, Adapter::MATCH_EXPIRED, $options); + $args = new \ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $result = $this->_clearByPrefix($prefix, $mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function optimize(array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->_normalizeOptions($options); + $args = new \ArrayObject(array( + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ( ($dirLevel = $this->getDirLevel()) ) { + // removes only empty directories + $this->_rmDir($this->getCacheDir(), $options['namespace'] . $this->getNamespaceSeparator()); + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /* status */ + + public function getCapabilities() + { + $args = new \ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->_capabilities === null) { + $this->_capabilityMarker = new \stdClass(); + $this->_capabilities = new Capabilities( + $this->_capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => 'string', + 'boolean' => 'string', + 'integer' => 'string', + 'double' => 'string', + 'string' => true, + 'array' => false, + 'object' => false, + 'resource' => false, + ), + 'supportedMetadata' => array('mtime', 'filespec'), + 'maxTtl' => 0, + 'staticTtl' => false, + 'ttlPrecision' => 1, + 'expiredRead' => true, + 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getNamespaceSeparator(), + 'iterable' => true, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); + + // set dynamic capibilities + $this->_updateCapabilities(); + } + + $result = $this->_capabilities; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + public function getCapacity(array $options = array()) + { + $args = new \ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = Utils::getDiskCapacity($this->getCacheDir()); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /* internal */ + + protected function _set($key, $value, array &$options) + { + $oldUmask = null; + + $lastInfoId = $options['namespace'] . $this->getNamespaceSeparator() . $key; + if ($this->_lastInfoId == $lastInfoId) { + $filespec = $this->_lastInfo['filespec']; + // if lastKeyInfo is available I'm sure that the cache directory exist + } else { + $filespec = $this->_getKeyFileSpec($key, $options['namespace']); + if ($this->getDirLevel() > 0) { + $path = dirname($filespec); + if (!file_exists($path)) { + $oldUmask = umask($this->getDirUmask()); + if ( !@mkdir($path, 0777, true) ) { + // reset umask on exception + umask($oldUmask); + + // throw exception with last error message + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + } + } + } + + $info = null; + if ($this->getReadControl()) { + $info['hash'] = Utils::generateHash($this->getReadControlAlgo(), $data, true); + $info['algo'] = $this->getReadControlAlgo(); + } + + if (isset($options['tags']) && $options['tags']) { + $info['tags'] = array_values(array_unique($options['tags'])); + } + + try { + if ($oldUmask !== null) { // $oldUmask could be defined on set directory_umask + umask($this->getFileUmask()); + } else { + $oldUmask = umask($this->getFileUmask()); + } + + $ret = $this->_putFileContent($filespec . '.dat', $value); + if ($ret && $info) { + // Don't throw exception if writing of info file failed + // -> only return false + try { + $ret = $this->_putFileContent($filespec . '.ifo', serialize($info)); + } catch (\Exception $e) { + $ret = false; + } + } + + $this->_lastInfoId = null; + + // reset file_umask + umask($oldUmask); + + return $ret; + + } catch (\Exception $e) { + // reset umask on exception + umask($oldUmask); + throw $e; + } + } + + protected function _remove($key, array &$options) + { + $filespec = $this->_getKeyFileSpec($key, $options['namespace']); + + if (!$options['ignore_missing_items'] && !file_exists($filespec . '.dat')) { + throw new ItemNotFoundException("Key '{$key}' with file '{$filespec}.dat' not found"); + } + + $this->_unlink($filespec . '.dat'); + $this->_unlink($filespec . '.ifo'); + $this->_lastInfoId = null; + } + + protected function _get($key, array &$options) + { + if ( !$this->_exists($key, $options) + || !($keyInfo=$this->_getKeyInfo($key, $options['namespace'])) ) { + if ($options['ignore_missing_items']) { + return false; + } else { + throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + } + } + + try { + $data = $this->_getFileContent($keyInfo['filespec'] . '.dat'); + + if ($this->getReadControl()) { + if ( ($info = $this->_readInfoFile($keyInfo['filespec'] . '.ifo')) + && isset($info['hash'], $info['algo']) ) { + $hashData = Utils::generateHash($info['algo'], $data, true); + if ($hashData != $info['hash']) { + throw new UnexpectedValueException( + 'readControl: Stored hash and computed hash don\'t match' + ); + } + } + } + + return $data; + + } catch (\Exception $e) { + try { + // remove cache file on exception + $this->_remove($key, $options); + } catch (\Exception $tmp) {} // do not throw remove exception on this point + + throw $e; + } + } + + protected function _exists($key, array &$options) + { + $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + if (!$keyInfo) { + return false; // missing or corrupted cache data + } + + if ( !$options['ttl'] // infinite lifetime + || time() < ($keyInfo['mtime'] + $options['ttl']) // not expired + ) { + return true; + } + + return false; + } + + protected function _info($key, array &$options) { + $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + if (!$keyInfo) { + if ($options['ignore_missing_items']) { + return false; + } else { + throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + } + } + + if ( ($info = $this->_readInfoFile($keyInfo['filespec'] . '.ifo')) ) { + return $keyInfo + $info; + } + + return $keyInfo; + } + + protected function _touch($key, array &$options) + { + $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + if (!$keyInfo) { + if ($options['ignore_missing_items']) { + return false; + } else { + throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + } + } + + if ( !@touch($keyInfo['filespec'] . '.dat') ) { + $err = error_get_last(); + throw new RuntimeException($err['message']); + } + } + + protected function _fetchByGlob() + { + $options = $this->_stmtOptions; + $match = $this->_stmtMatch; + + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefixL = strlen($prefix); + + do { + $item = array(); + $info = null; + + $file = array_shift($this->_stmtGlob); + if ($file === null) { + return false; + } + + $basename = basename($file); + + if ($prefix !== '') { + if (substr($basename, 0, $prefixL) != $prefix) { + continue; + } + + // remove prefix and suffix (.dat) + $key = substr($basename, $prefixL, -4); + } else { + // remove suffix (.dat) + $key = substr($basename, 0, -4); + } + + // if MATCH_ALL mode do not check expired + if (($match & Adapter::MATCH_ALL) != Adapter::MATCH_ALL) { + + $mtime = @filemtime($file); + if ($mtime === false) { + // file already removed + continue; + } + + // if MATCH_EXPIRED -> filter not expired items + if (($match & Adapter::MATCH_EXPIRED) == Adapter::MATCH_EXPIRED) { + if ( time() < ($mtime + $options['ttl']) ) { + continue; + } + + // if MATCH_ACTIVE -> filter expired items + } else { + if ( time() >= ($mtime + $options['ttl']) ) { + continue; + } + } + } + + // check tags only if one of the tag matching mode is selected + if (($match & 070) > 0) { + + $info = $this->_info($key, $options); + + // if MATCHING_TAGS mode -> check if all given tags available in current cache + if (($match & Adapter::MATCHING_TAGS) == Adapter::MATCHING_TAGS ) { + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { + continue; + } + + // if MATCHING_NO_TAGS mode -> check if no given tag available in current cache + } elseif( ($match & Adapter::MATCHING_NO_TAGS) == Adapter::MATCHING_NO_TAGS ) { + if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { + continue; + } + + // if MATCHING_ANY_TAGS mode -> check if any given tag available in current cache + } elseif ( ($match & Adapter::MATCHING_ANY_TAGS) == Adapter::MATCHING_ANY_TAGS ) { + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { + continue; + } + + } + } + + foreach ($options['select'] as $select) { + if ($select == 'key') { + $item['key'] = $key; + } else if ($select == 'value') { + $item['value'] = $this->_getFileContent($file); + } else if ($select != 'key') { + if ($info === null) { + $info = $this->_info($key, $options); + } + $item[$select] = isset($info[$select]) ? $info[$select] : null; + } + } + + return $item; + } while (true); + } + + protected function _clearByPrefix($prefix, $mode, array &$opts) + { + if (!$this->getWritable()) { + return false; + } + + $ttl = $opts['ttl']; + + if ($this->getClearStatCache()) { + clearstatcache(); + } + + $find = $this->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $this->getDirLevel()) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = glob($find, \GLOB_NOSORT | \GLOB_NOESCAPE); + if (!$glob) { + // On some systems glob returns false even on empty result + return true; + } + + $time = time(); + + foreach ($glob as $file) { + + // if MATCH_ALL mode do not check expired + if (($mode & Adapter::MATCH_ALL) != Adapter::MATCH_ALL) { + + $mtime = @filemtime($file); + if ($mtime === false) { + // file already removed + continue; + } + + if (($mode & Adapter::MATCH_EXPIRED) == Adapter::MATCH_EXPIRED) { + if ( $time <= ($mtime + $ttl) ) { + continue; + } + + // if Zend_Cache::MATCHING_ACTIVE mode selected do not remove expired data + } else { + if ( $time >= ($mtime + $ttl) ) { + continue; + } + } + } + + // remove file suffix (*.dat) + $filespec = substr($file, 0, -4); + + //////////////////////////////////////// + // on this time all expire tests match + //////////////////////////////////////// + + // check tags only if one of the tag matching mode is selected + if (($mode & 070) > 0) { + + $info = $this->_readInfoFile($filespec . '.ifo'); + + // if MATCHING_TAGS mode -> check if all given tags available in current cache + if (($mode & Adapter::MATCHING_TAGS) == Adapter::MATCHING_TAGS ) { + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { + continue; + } + + // if MATCHING_NO_TAGS mode -> check if no given tag available in current cache + } elseif( ($mode & Adapter::MATCHING_NO_TAGS) == Adapter::MATCHING_NO_TAGS ) { + if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { + continue; + } + + // if MATCHING_ANY_TAGS mode -> check if any given tag available in current cache + } elseif ( ($mode & Adapter::MATCHING_ANY_TAGS) == Adapter::MATCHING_ANY_TAGS ) { + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { + continue; + } + + } + } + + //////////////////////////////////////// + // on this time all tests match + //////////////////////////////////////// + + $this->_unlink($file); // delete data file + $this->_unlink($filespec . '.ifo'); // delete info file + } + + return true; + } + + /** + * Removes directories recursive by namespace + * + * @param string $dir Directory to delete + * @param string $prefix Namespace + Separator + */ + protected function _rmDir($dir, $prefix) + { + $glob = glob( + $dir . \DIRECTORY_SEPARATOR . $prefix . '*', + \GLOB_ONLYDIR | \GLOB_NOESCAPE | \GLOB_NOSORT + ); + if (!$glob) { + // On some systems glob returns false even on empty result + return true; + } + + $ret = true; + foreach ($glob as $subdir) { + // ignore not empty directories + // skip removing current directory if removing of sub-directory failed + $ret = $this->_rmDir($subdir, $prefix) && @rmdir($subdir); + } + return $ret; + } + + /** + * Get an array of information about the cache key. + * NOTE: returns false if cache doesn't hit. + * + * @param string $key + * @param string $ns + * @return array|boolean + */ + protected function _getKeyInfo($key, $ns) + { + $lastInfoId = $ns . $this->getNamespaceSeparator() . $key; + if ($this->_lastInfoId == $lastInfoId) { + return $this->_lastInfo; + } + + $filespec = $this->_getKeyFileSpec($key, $ns); + + if ( ($filemtime = @filemtime($filespec . '.dat')) === false ) { + return false; + } + + $this->_lastInfoId = $lastInfoId; + $this->_lastInfoAll = null; + $this->_lastInfo = array( + 'filespec' => $filespec, + 'mtime' => $filemtime + ); + + if (!$this->getNoCtime()) { + $this->_lastInfo['ctime'] = filectime($filespec . '.dat'); + } + + if (!$this->getNoAtime()) { + $this->_lastInfo['atime'] = fileatime($filespec . '.dat'); + } + + return $this->_lastInfo; + } + + /** + * Get cache file spec + * + * @param string $key + * @param string $ns + * @return string + */ + protected function _getKeyFileSpec($key, $ns) + { + $prefix = $ns . $this->getNamespaceSeparator(); + $lastInfoId = $prefix . $key; + if ($this->_lastInfoId == $lastInfoId) { + return $this->_lastInfo['filespec']; + } + + $path = $this->getCacheDir(); + $level = $this->getDirLevel(); + if ( $level > 0 ) { + // create up to 256 directories per directory level + $hash = md5($key); + for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { + $path.= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; + } + } + + return $path . \DIRECTORY_SEPARATOR . $prefix . $key; + } + + /** + * Read info file + * + * @param string $file + * @return array|boolean The info array or false if file wasn't found + * @throws RuntimeException + */ + protected function _readInfoFile($file) { + if ( file_exists($file) ) { + $info = @unserialize($this->_getFileContent($file)); + if (!is_array($info)) { + $err = error_get_last(); + throw new RuntimeException("Corrupted info file '{$file}': {$err['message']}"); + } + return $info; + } + + return false; + } + + /** + * Read a complete file + * + * @param string $file File complete path + * @throws RuntimeException + */ + protected function _getFileContent($file) + { + // if file locking enabled -> file_get_contents can't be used + if ($this->getFileLocking()) { + $fp = @fopen($file, 'rb'); + if ($fp === false) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + + if (!flock($fp, \LOCK_SH)) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + + $result = @stream_get_contents($fp); + if ($result === false) { + $lastErr = error_get_last(); + @flock($fp, \LOCK_UN); + @fclose($fp); + throw new RuntimeException($lastErr['message']); + } + + flock($fp, \LOCK_UN); + fclose($fp); + + // if file locking disabled -> file_get_contents can be used + } else { + $result = @file_get_contents($file, false); + if ($result === false) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + } + + return $result; + } + + /** + * Write content to a file + * + * @param string $file File complete path + * @param string $data Data to write + * @throws RuntimeException + */ + protected function _putFileContent($file, $data) + { + $locking = $this->getFileLocking(); + $blocking = $locking ? $this->getFileBlocking() : false; + + if ($locking && !$blocking) { + $fp = @fopen($file, 'cb'); + if (!$fp) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + + if(!flock($fp, \LOCK_EX | \LOCK_NB)) { + // file is locked by another process -> aborting writing + fclose($fp); + return false; + } + + if (!ftruncate($fp, 0)) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + + if (!fwrite($fp, $data)) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + + flock($fp, \LOCK_UN); + fclose($fp); + } else { + $flags = 0; + if ($locking) { + $flags = $flags | \LOCK_EX; + } + + if ( @file_put_contents($file, $data, $flags) === false ) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + } + + return true; + } + + /** + * Unlink a file + * + * @param string $file + * @throw RuntimeException + */ + protected function _unlink($file) { + if (!@unlink($file)) { + // only throw exception if file still exists after deleting + if (file_exists($file)) { + $lastErr = error_get_last(); + throw new RuntimeException($lastErr['message']); + } + } + } + + /** + * Update dynamic capabilities only if already created + */ + protected function _updateCapabilities() + { + if ($this->_capabilities) { + + // update namespace separator + $this->_capabilities->setNamespaceSeparator( + $this->_capabilityMarker, + $this->getNamespaceSeparator() + ); + + // update metadata capabilities + $metadata = array('mtime', 'filespec'); + + if (!$this->getNoCtime()) { + $metadata[] = 'ctime'; + } + + if (!$this->getNoAtime()) { + $metadata[] = 'atime'; + } + + $this->_capabilities->setSupportedMetadata( + $this->_capabilityMarker, + $metadata + ); + } + } + +} diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php new file mode 100644 index 000000000..2158ba580 --- /dev/null +++ b/test/Storage/Adapter/FilesystemTest.php @@ -0,0 +1,287 @@ +_tmpCacheDir = @tempnam(sys_get_temp_dir(), 'zend_cache_test_'); + if (!$this->_tmpCacheDir) { + $err = error_get_last(); + $this->fail("Can't create temporary cache directory-file: {$err['message']}"); + } elseif (!@unlink($this->_tmpCacheDir)) { + $err = error_get_last(); + $this->fail("Can't remove temporary cache directory-file: {$err['message']}"); + } elseif (!@mkdir($this->_tmpCacheDir, 0777)) { + $err = error_get_last(); + $this->fail("Can't create temporaty cache directory: {$err['message']}"); + } + + $this->_storage = new Cache\Storage\Adapter\Filesystem(array( + 'cache_dir' => $this->_tmpCacheDir + )); + + parent::setUp(); + } + + public function tearDown() + { + $this->_removeRecursive($this->_tmpCacheDir); + + parent::tearDown(); + } + + protected function _removeRecursive($dir) + { + if (file_exists($dir)) { + $dirIt = new \DirectoryIterator($dir); + foreach ($dirIt as $entry) { + $fname = $entry->getFilename(); + if ($fname == '.' || $fname == '..') { + continue; + } + + if ($entry->isFile()) { + unlink($entry->getPathname()); + } else { + $this->_removeRecursive($entry->getPathname()); + } + } + + rmdir($dir); + } + } + + public function testNormalizeCacheDir() + { + $cacheDir = $cacheDirExpected = sys_get_temp_dir(); + + if (DIRECTORY_SEPARATOR != '/') { + $cacheDir = str_replace(DIRECTORY_SEPARATOR, '/', $cacheDir); + } + + $firstSlash = strpos($cacheDir, '/'); + $cacheDir = substr($cacheDir, 0, $firstSlash + 1) + . '..//../' + . substr($cacheDir, $firstSlash) + . '///'; + + $this->_storage->setCacheDir($cacheDir); + $cacheDir = $this->_storage->getCacheDir(); + + $this->assertEquals($cacheDirExpected, $cacheDir); + } + + public function testSetCacheDirToSystemsTempDirWithNull() + { + $this->_storage->setCacheDir(null); + $this->assertEquals(sys_get_temp_dir(), $this->_storage->getCacheDir()); + } + + public function testSetCacheDirNoDirectoryException() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setCacheDir(__FILE__); + } + + public function testSetCacheDirNotWritableException() + { + if (substr(PHP_OS, 0, 3) == 'WIN') { + $this->markTestSkipped("Not testable on windows"); + } else { + @exec('whoami 2>&1', $out, $ret); + if ($ret) { + $err = error_get_last(); + $this->markTestSkipped("Not testable: {$err['message']}"); + } elseif (isset($out[0]) && $out[0] == 'root') { + $this->markTestSkipped("Not testable as root"); + } + } + + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + + // create a not writable temporaty directory + $testDir = tempnam(sys_get_temp_dir(), 'ZendTest'); + unlink($testDir); mkdir($testDir); chmod($testDir, 0557); + + try { + $this->_storage->setCacheDir($testDir); + } catch (\Exception $e) { + rmdir($testDir); + throw $e; + } + } + + public function testSetCacheDirNotReadableException() + { + if (substr(PHP_OS, 0, 3) == 'WIN') { + $this->markTestSkipped("Not testable on windows"); + } else { + @exec('whoami 2>&1', $out, $ret); + if ($ret) { + $this->markTestSkipped("Not testable: " . implode("\n", $out)); + } elseif (isset($out[0]) && $out[0] == 'root') { + $this->markTestSkipped("Not testable as root"); + } + } + + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + + // create a not readable temporaty directory + $testDir = tempnam(sys_get_temp_dir(), 'ZendTest'); + unlink($testDir); mkdir($testDir); chmod($testDir, 0337); + + try { + $this->_storage->setCacheDir($testDir); + } catch (\Exception $e) { + rmdir($testDir); + throw $e; + } + } + + public function testSetFilePermUpdatesUmask() + { + $this->_storage->setFilePerm(0606); + $this->assertEquals(~0606, $this->_storage->getFileUmask()); + } + + public function testSetFilePermThrowsExceptionIfNotWritable() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setFilePerm(0466); + } + + public function testSetFilePermThrowsExceptionIfNotReadable() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setFilePerm(0266); + } + + public function testSetFilePermThrowsExceptionIfExecutable() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setFilePerm(0661); + } + + public function testSetNoAtimeChangesAtimeOfMetadataCapability() + { + $capabilities = $this->_storage->getCapabilities(); + + $this->_storage->setNoAtime(false); + $this->assertContains('atime', $capabilities->getSupportedMetadata()); + + $this->_storage->setNoAtime(true); + $this->assertNotContains('atime', $capabilities->getSupportedMetadata()); + } + + public function testSetNoCtimeChangesCtimeOfMetadataCapability() + { + $capabilities = $this->_storage->getCapabilities(); + + $this->_storage->setNoCtime(false); + $this->assertContains('ctime', $capabilities->getSupportedMetadata()); + + $this->_storage->setNoCtime(true); + $this->assertNotContains('ctime', $capabilities->getSupportedMetadata()); + } + + public function testSetDirPermUpdatesUmask() + { + $this->_storage->setDirPerm(0706); + $this->assertEquals(~0706, $this->_storage->getDirUmask()); + } + + public function testSetDirPermThrowsExceptionIfNotWritable() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setDirPerm(0577); + } + + public function testSetDirPermThrowsExceptionIfNotReadable() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setDirPerm(0377); + } + + public function testSetDirPermThrowsExceptionIfNotExecutable() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setDirPerm(0677); + } + + public function testSetDirLevelInvalidException() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setDirLevel(17); // must between 0-16 + } + + public function testSetReadControlAlgoAllowStrlen() + { + $this->_storage->setReadControlAlgo('strlen'); + $this->assertEquals('strlen', $this->_storage->getReadControlAlgo()); + } + + public function testSetReadControlAlgoInvalidException() + { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + $this->_storage->setReadControlAlgo('unknown'); + } + + public function testDisabledFileBlocking() + { + $this->_storage->setFileLocking(true); + $this->_storage->setFileBlocking(false); + + // create cache item and get data file + $this->assertTrue($this->_storage->setItem('key', 'value')); + $info = $this->_storage->getMetadata('key'); + $this->assertInternalType('array', $info); + $this->assertArrayHasKey('filespec', $info); + $file = $info['filespec'] . '.dat'; + + // open file and create a write lock + $fp = @fopen($file, 'w+'); + $this->assertInternalType('resource', $fp); + flock($fp, LOCK_EX); + + // rewriting file should fail in part of open lock + $this->assertFalse($this->_storage->setItem('key', 'lock')); + + flock($fp, LOCK_UN); + fclose($fp); + } + +} From f5c8c5738c8a82d2e6fdc626cae8322bdb62493c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 5 Dec 2011 09:17:22 +0100 Subject: [PATCH 112/311] merged branch into filesystem adapter to use GlobIterator instead of glob to save memory usage --- src/Storage/Adapter/Filesystem.php | 109 ++++++++++++++--------------- 1 file changed, 54 insertions(+), 55 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 36efb79bb..d09949d84 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -7,7 +7,8 @@ Zend\Cache\Utils, Zend\Cache\Exception\RuntimeException, Zend\Cache\Exception\InvalidArgumentException, - Zend\Cache\Exception\ItemNotFoundException; + Zend\Cache\Exception\ItemNotFoundException, + GlobIterator; class Filesystem extends AbstractAdapter { @@ -1005,20 +1006,20 @@ public function find($mode = Adapter::MATCH_ACTIVE, array $options = array()) clearstatcache(); } - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); - $find = $options['cache_dir'] - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) - . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = glob($find, \GLOB_NOSORT | \GLOB_NOESCAPE); - if (!$glob) { - // On some systems glob returns false even on empty result - return true; - } + try { + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $find = $options['cache_dir'] + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = new \GlobIterator($find); - $this->_stmtActive = true; - $this->_stmtGlob = $glob; - $this->_stmtMatch = $mode; - $this->_stmtOptions = $options; + $this->_stmtActive = true; + $this->_stmtGlob = $glob; + $this->_stmtMatch = $mode; + $this->_stmtOptions = $options; + } catch (\Exception $e) { + throw new RuntimeException('Instantiating glob iterator failed', 0, $e); + } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -1055,7 +1056,6 @@ public function fetch() $result = parent::fetch(); } - $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1381,45 +1381,49 @@ protected function _touch($key, array &$options) protected function _fetchByGlob() { $options = $this->_stmtOptions; - $match = $this->_stmtMatch; + $mode = $this->_stmtMatch; $prefix = $options['namespace'] . $this->getNamespaceSeparator(); $prefixL = strlen($prefix); do { - $item = array(); - $info = null; - - $file = array_shift($this->_stmtGlob); - if ($file === null) { + try { + $valid = $this->_stmtGlob->valid(); + } catch (\LogicException $e) { + // @link https://bugs.php.net/bug.php?id=55701 + // GlobIterator throws LogicException with message + // 'The parent constructor was not called: the object is in an invalid state' + $valid = false; + } + if (!$valid) { return false; } - $basename = basename($file); + $item = array(); + $info = null; + + $current = $this->_stmtGlob->current(); + $this->_stmtGlob->next(); + $filename = $current->getFilename(); if ($prefix !== '') { - if (substr($basename, 0, $prefixL) != $prefix) { + if (substr($filename, 0, $prefixL) != $prefix) { continue; } // remove prefix and suffix (.dat) - $key = substr($basename, $prefixL, -4); + $key = substr($filename, $prefixL, -4); } else { // remove suffix (.dat) - $key = substr($basename, 0, -4); + $key = substr($filename, 0, -4); } // if MATCH_ALL mode do not check expired - if (($match & Adapter::MATCH_ALL) != Adapter::MATCH_ALL) { - - $mtime = @filemtime($file); - if ($mtime === false) { - // file already removed - continue; - } + if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { + $mtime = $current->getMTime(); // if MATCH_EXPIRED -> filter not expired items - if (($match & Adapter::MATCH_EXPIRED) == Adapter::MATCH_EXPIRED) { + if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { if ( time() < ($mtime + $options['ttl']) ) { continue; } @@ -1433,24 +1437,24 @@ protected function _fetchByGlob() } // check tags only if one of the tag matching mode is selected - if (($match & 070) > 0) { + if (($mode & 070) > 0) { $info = $this->_info($key, $options); // if MATCHING_TAGS mode -> check if all given tags available in current cache - if (($match & Adapter::MATCHING_TAGS) == Adapter::MATCHING_TAGS ) { + if (($mode & self::MATCHING_TAGS) == self::MATCHING_TAGS ) { if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { continue; } // if MATCHING_NO_TAGS mode -> check if no given tag available in current cache - } elseif( ($match & Adapter::MATCHING_NO_TAGS) == Adapter::MATCHING_NO_TAGS ) { + } elseif( ($mode & self::MATCHING_NO_TAGS) == self::MATCHING_NO_TAGS ) { if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { continue; } // if MATCHING_ANY_TAGS mode -> check if any given tag available in current cache - } elseif ( ($match & Adapter::MATCHING_ANY_TAGS) == Adapter::MATCHING_ANY_TAGS ) { + } elseif ( ($mode & self::MATCHING_ANY_TAGS) == self::MATCHING_ANY_TAGS ) { if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { continue; } @@ -1462,7 +1466,7 @@ protected function _fetchByGlob() if ($select == 'key') { $item['key'] = $key; } else if ($select == 'value') { - $item['value'] = $this->_getFileContent($file); + $item['value'] = $this->_getFileContent($current->getPathname()); } else if ($select != 'key') { if ($info === null) { $info = $this->_info($key, $options); @@ -1487,28 +1491,23 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) clearstatcache(); } - $find = $this->getCacheDir() - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $this->getDirLevel()) - . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = glob($find, \GLOB_NOSORT | \GLOB_NOESCAPE); - if (!$glob) { - // On some systems glob returns false even on empty result - return true; + try { + $find = $this->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $this->getDirLevel()) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = new \GlobIterator($find); + } catch (\Exception $e) { + throw new RuntimeException('Instantiating GlobIterator failed', 0, $e); } $time = time(); - foreach ($glob as $file) { + foreach ($glob as $entry) { // if MATCH_ALL mode do not check expired if (($mode & Adapter::MATCH_ALL) != Adapter::MATCH_ALL) { - $mtime = @filemtime($file); - if ($mtime === false) { - // file already removed - continue; - } - + $mtime = $entry->getMTime(); if (($mode & Adapter::MATCH_EXPIRED) == Adapter::MATCH_EXPIRED) { if ( $time <= ($mtime + $ttl) ) { continue; @@ -1523,7 +1522,7 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) } // remove file suffix (*.dat) - $filespec = substr($file, 0, -4); + $pathnameSpec = substr($entry->getPathname(), 0, -4); //////////////////////////////////////// // on this time all expire tests match @@ -1559,8 +1558,8 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) // on this time all tests match //////////////////////////////////////// - $this->_unlink($file); // delete data file - $this->_unlink($filespec . '.ifo'); // delete info file + $this->_unlink($pathnameSpec . '.dat'); // delete data file + $this->_unlink($pathnameSpec . '.ifo'); // delete info file } return true; From e18b75b83f0d675a5220b4b88aeacd40520d4d99 Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Wed, 7 Dec 2011 20:37:24 +0100 Subject: [PATCH 113/311] small fix in MissingDependencyException, PhpDoc for Zend\Cache\Pattern --- src/Exception/MissingDependencyException.php | 2 +- src/Pattern.php | 4 +- src/Pattern/AbstractPattern.php | 17 ++++ src/Pattern/CallbackCache.php | 22 +++++ src/Pattern/CaptureCache.php | 93 +++++++++++++++++++- src/Pattern/ClassCache.php | 34 +++++++ src/Pattern/ObjectCache.php | 46 ++++++++++ src/Pattern/OutputCache.php | 16 ++++ 8 files changed, 228 insertions(+), 6 deletions(-) diff --git a/src/Exception/MissingDependencyException.php b/src/Exception/MissingDependencyException.php index cf57f115b..be8bf69d9 100644 --- a/src/Exception/MissingDependencyException.php +++ b/src/Exception/MissingDependencyException.php @@ -2,5 +2,5 @@ namespace Zend\Cache\Exception; -class MissingDependencyException extends RuntimeException implements \Zend\Cache\Exception +class MissingDependencyException extends RuntimeException {} diff --git a/src/Pattern.php b/src/Pattern.php index d76e8e27d..eb043364d 100644 --- a/src/Pattern.php +++ b/src/Pattern.php @@ -16,14 +16,14 @@ public function __construct($options = array()); * Set pattern options * * @param array|Traversable $options - * @return Zend\Cache\Pattern + * @return Pattern */ public function setOptions($options); /** * Get all pattern options * - * return array + * @return array */ public function getOptions(); diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index db6cdd918..586fbaf21 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -7,11 +7,23 @@ abstract class AbstractPattern implements Cache\Pattern { + /** + * Constructor + * + * @param array|Traversable $options + */ public function __construct($options = array()) { $this->setOptions($options); } + /** + * Set pattern options + * + * @param array|Traversable $options + * @return AbstractPattern + * @throws InvalidArgumentException + */ public function setOptions($options) { if (!($options instanceof Traversable) && !is_array($options)) { @@ -29,6 +41,11 @@ public function setOptions($options) return $this; } + /** + * Get all pattern options + * + * @return array + */ public function getOptions() { return array(); diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index c63a55ee3..f0241e33c 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -22,6 +22,12 @@ class CallbackCache extends AbstractPattern */ protected $_cacheOutput = true; + /** + * Constructor + * + * @param array|Traversable $options + * @throws InvalidArgumentException + */ public function __construct($options = array()) { parent::__construct($options); @@ -31,6 +37,11 @@ public function __construct($options = array()) } } + /** + * Get all pattern options + * + * @return array + */ public function getOptions() { $options = parent::getOptions(); @@ -180,6 +191,17 @@ public function generateKey($callback, array $args = array(), array $options = a return $this->_generateKey($callback, $args, $options); } + /** + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part merged using md5($callbackKey.$argumentsKey). + * + * @param callback $callback A valid callback + * @param array $args Callback arguments + * @param array $options Options + * @return string + * @throws \Zend\Cache\Exception\InvalidArgumentException + * @throws \Zend\Cache\Exception\RuntimeException + */ protected function _generateKey($callback, array $args, array $options) { $callbackKey = ''; diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 15fb41138..f43521c3b 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -54,11 +54,21 @@ class CaptureCache extends AbstractPattern */ protected $_tags = array(); + /** + * Constructor + * + * @param array|Traversable $options + */ public function __construct($options = array()) { parent::__construct($options); } + /** + * Get all pattern options + * + * @return array + */ public function getOptions() { return array( @@ -69,34 +79,67 @@ public function getOptions() ); } + /** + * Set public directory + * + * @param null|string $dir + * @return CaptureCache + */ public function setPublicDir($dir) { $this->_publicDir = $dir; return $this; } + /** + * Get public directory + * + * @return null|string + */ public function getPublicDir() { return $this->_publicDir; } + /** + * Set index filename + * + * @param string $filename + * @return CaptureCache + */ public function setIndexFilename($filename) { $this->_indexFilename = (string)$filename; return $this; } + /** + * Get index filename + * + * @return string + */ public function getIndexFilename() { return $this->_indexFilename; } + /** + * Set file locking + * + * @param bool $flag + * @return CaptureCache + */ public function setFileLocking($flag) { $this->_fileLocking = (boolean)$flag; return $this; } + /** + * Get file locking + * + * @return bool + */ public function getFileLocking() { return $this->_fileLocking; @@ -106,7 +149,7 @@ public function getFileLocking() * Set a storage for tagging * * @param \Zend\Cache\Storage\Adapter $storage - * @return \Zend\Cache\Pattern\CaptureCache + * @return CaptureCache */ public function setTagStorage(Adapter $storage) { @@ -128,7 +171,7 @@ public function getTagStorage() * Set cache item key to store tags * * @param $tagKey string - * @return Zend\Cache\Pattern\CaptureCache + * @return CaptureCache */ public function setTagKey($tagKey) { @@ -154,7 +197,7 @@ public function getTagKey() * Set tags to store * * @param array $tags - * @return Zend\Cache\Pattern\CaptureCache + * @return CaptureCache */ public function setTags(array $tags) { @@ -205,6 +248,14 @@ public function start($pageId = null, array $options = array()) return false; } + /** + * Get from cache + * + * @param null|string $pageId + * @param array $options + * @return bool|string + * @throws RuntimeException + */ public function get($pageId = null, array $options = array()) { if (($pageId = (string)$pageId) === '') { @@ -226,6 +277,13 @@ public function get($pageId = null, array $options = array()) return false; } + /** + * Checks if a cache with given id exists + * + * @param null|string $pageId + * @param array $options + * @return bool + */ public function exists($pageId = null, array $options = array()) { if (($pageId = (string)$pageId) === '') { @@ -239,6 +297,14 @@ public function exists($pageId = null, array $options = array()) return file_exists($file); } + /** + * Remove from cache + * + * @param null|string $pageId + * @param array $options + * @throws RuntimeException + * @return void + */ public function remove($pageId = null, array $options = array()) { if (($pageId = (string)$pageId) === '') { @@ -257,6 +323,9 @@ public function remove($pageId = null, array $options = array()) } } + /** + * Clear cache + */ public function clear(/*TODO*/) { // TODO @@ -272,6 +341,12 @@ protected function _detectPageId() return $_SERVER['REQUEST_URI']; } + /** + * Get filename for page id + * + * @param string $pageId + * @return string + */ protected function _pageId2Filename($pageId) { $filename = basename($pageId); @@ -283,6 +358,12 @@ protected function _pageId2Filename($pageId) return $filename; } + /** + * Get path for page id + * + * @param string $pageId + * @return string + */ protected function _pageId2Path($pageId) { $path = rtrim(dirname($pageId), '/'); @@ -310,6 +391,12 @@ protected function _flush($output) return false; } + /** + * Save the cache + * + * @param $output + * @throws RuntimeException + */ protected function _save($output) { $path = $this->_pageId2Path($this->_pageId); diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index 4a307377d..1c92ec16a 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -15,11 +15,40 @@ class ClassCache extends CallbackCache */ protected $_storage; + /** + * The entity + * + * @var null|string + */ protected $_entity = null; + + /** + * Cache by default + * + * @var bool + */ protected $_cacheByDefault = true; + + /** + * Cache methods + * + * @var array + */ protected $_cacheMethods = array(); + + /** + * Non-cache methods + * + * @var array + */ protected $_nonCacheMethods = array(); + /** + * Constructor + * + * @param array|Traversable $options + * @throws InvalidArgumentException + */ public function __construct($options = array()) { parent::__construct($options); @@ -31,6 +60,11 @@ public function __construct($options = array()) } } + /** + * Get all pattern options + * + * @return array + */ public function getOptions() { $options = parent::getOptions(); diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index 80fce7153..84e2851f1 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -15,13 +15,54 @@ class ObjectCache extends CallbackCache */ protected $_storage; + /** + * The entity + * + * @var null|object + */ protected $_entity = null; + + /** + * The entity key + * + * @var null|string + */ protected $_entityKey = null; + + /** + * Cache by default + * + * @var bool + */ protected $_cacheByDefault = true; + + /** + * Cache methods + * + * @var array + */ protected $_cacheMethods = array(); + + /** + * Non-cache methods + * + * @var array + */ protected $_nonCacheMethods = array('__tostring'); + + /** + * Cache magic properties + * + * @var bool + */ protected $_cacheMagicProperties = false; + /** + * Constructor + * + * @param array|Traversable $options + * @throws InvalidArgumentException + */ public function __construct($options = array()) { parent::__construct($options); @@ -33,6 +74,11 @@ public function __construct($options = array()) } } + /** + * Get all pattern options + * + * @return array + */ public function getOptions() { $options = parent::getOptions(); diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index 4042a9a0b..c358333c3 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -17,8 +17,19 @@ class OutputCache extends AbstractPattern */ protected $_storage; + /** + * The key stack + * + * @var array + */ protected $_keyStack = array(); + /** + * Constructor + * + * @param array|Traversable $options + * @throws InvalidArgumentException + */ public function __construct($options = array()) { parent::__construct($options); @@ -28,6 +39,11 @@ public function __construct($options = array()) } } + /** + * Get all pattern options + * + * @return array + */ public function getOptions() { $options = parent::getOptions(); From e3de24a09f3aca852a752f80fee8deff451e032d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 20:46:31 +0100 Subject: [PATCH 114/311] fixed matching mode constants of filesystem adapter --- src/Storage/Adapter/Filesystem.php | 42 +++++++++++++++--------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index d09949d84..178adcce9 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -978,7 +978,7 @@ public function removeItems(array $keys, array $options = array()) /* non-blocking */ - public function find($mode = Adapter::MATCH_ACTIVE, array $options = array()) + public function find($mode = self::MATCH_ACTIVE, array $options = array()) { if ($this->_stmtActive) { throw new RuntimeException('Statement already in use'); @@ -989,7 +989,7 @@ public function find($mode = Adapter::MATCH_ACTIVE, array $options = array()) } $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, Adapter::MATCH_ACTIVE, $options); + $this->_normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); $options = array_merge($this->getOptions(), $options); $args = new \ArrayObject(array( 'mode' => & $mode, @@ -1064,10 +1064,10 @@ public function fetch() /* cleaning */ - public function clear($mode = Adapter::MATCH_EXPIRED, array $options = array()) + public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, Adapter::MATCH_EXPIRED, $options); + $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options @@ -1086,10 +1086,10 @@ public function clear($mode = Adapter::MATCH_EXPIRED, array $options = array()) } } - public function clearByNamespace($mode = Adapter::MATCH_EXPIRED, array $options = array()) + public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, Adapter::MATCH_EXPIRED, $options); + $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options @@ -1441,20 +1441,20 @@ protected function _fetchByGlob() $info = $this->_info($key, $options); - // if MATCHING_TAGS mode -> check if all given tags available in current cache - if (($mode & self::MATCHING_TAGS) == self::MATCHING_TAGS ) { + // if MATCH_TAGS mode -> check if all given tags available in current cache + if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { continue; } - // if MATCHING_NO_TAGS mode -> check if no given tag available in current cache - } elseif( ($mode & self::MATCHING_NO_TAGS) == self::MATCHING_NO_TAGS ) { + // if MATCH_NO_TAGS mode -> check if no given tag available in current cache + } elseif( ($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS ) { if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { continue; } - // if MATCHING_ANY_TAGS mode -> check if any given tag available in current cache - } elseif ( ($mode & self::MATCHING_ANY_TAGS) == self::MATCHING_ANY_TAGS ) { + // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache + } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { continue; } @@ -1505,15 +1505,15 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) foreach ($glob as $entry) { // if MATCH_ALL mode do not check expired - if (($mode & Adapter::MATCH_ALL) != Adapter::MATCH_ALL) { + if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { $mtime = $entry->getMTime(); - if (($mode & Adapter::MATCH_EXPIRED) == Adapter::MATCH_EXPIRED) { + if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { if ( $time <= ($mtime + $ttl) ) { continue; } - // if Zend_Cache::MATCHING_ACTIVE mode selected do not remove expired data + // if Zend_Cache::MATCH_ACTIVE mode selected do not remove expired data } else { if ( $time >= ($mtime + $ttl) ) { continue; @@ -1533,20 +1533,20 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) $info = $this->_readInfoFile($filespec . '.ifo'); - // if MATCHING_TAGS mode -> check if all given tags available in current cache - if (($mode & Adapter::MATCHING_TAGS) == Adapter::MATCHING_TAGS ) { + // if MATCH_TAGS mode -> check if all given tags available in current cache + if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { continue; } - // if MATCHING_NO_TAGS mode -> check if no given tag available in current cache - } elseif( ($mode & Adapter::MATCHING_NO_TAGS) == Adapter::MATCHING_NO_TAGS ) { + // if MATCH_NO_TAGS mode -> check if no given tag available in current cache + } elseif( ($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS ) { if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { continue; } - // if MATCHING_ANY_TAGS mode -> check if any given tag available in current cache - } elseif ( ($mode & Adapter::MATCHING_ANY_TAGS) == Adapter::MATCHING_ANY_TAGS ) { + // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache + } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { continue; } From 086bf14e7bf590f7d463a9213a0295e1daacea1c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 21:02:54 +0100 Subject: [PATCH 115/311] fixed missing on CaptureCache --- src/Pattern/CaptureCache.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index f43521c3b..e5bb80b5d 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -267,8 +267,8 @@ public function get($pageId = null, array $options = array()) . DIRECTORY_SEPARATOR . $this->_pageId2Filename($pageId); if (file_exists($file)) { - $content = @file_get_contents($file); - if ($content === false) { + if (($content = @file_get_contents($file)) === false) { + $lastErr = error_get_last(); throw new RuntimeException("Failed to read cached pageId '{$pageId}': {$lastErr['message']}"); } return $content; From 37d299f1036dc97d693d317aa587c7eaebaac70f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 21:09:31 +0100 Subject: [PATCH 116/311] common pattern test tested options of a wrong and sometimes missing object --- test/Pattern/CommonPatternTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Pattern/CommonPatternTest.php b/test/Pattern/CommonPatternTest.php index e353386cb..4aa1c115a 100644 --- a/test/Pattern/CommonPatternTest.php +++ b/test/Pattern/CommonPatternTest.php @@ -68,9 +68,9 @@ public function testOptionNamesValid() public function testOptionsGetAndSetDefault() { - $options = $this->_storage->getOptions(); - $this->_storage->setOptions($options); - $this->assertEquals($options, $this->_storage->getOptions()); + $options = $this->_pattern->getOptions(); + $this->_pattern->setOptions($options); + $this->assertEquals($options, $this->_pattern->getOptions()); } public function testOptionsFluentInterface() @@ -87,8 +87,8 @@ public function testOptionsFluentInterface() } $this->assertSame( - $this->_storage, - $this->_storage->setOptions(array()), + $this->_pattern, + $this->_pattern->setOptions(array()), "Method 'setOptions' doesn't implement the fluent interface" ); } From 06f45643e28b949386e10973f1b36944ff57498b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 21:31:37 +0100 Subject: [PATCH 117/311] added initial tests of capture cache and fixed some small issues --- src/Pattern/CaptureCache.php | 19 +++++------ test/Pattern/CaptureCacheTest.php | 52 +++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 9 deletions(-) create mode 100644 test/Pattern/CaptureCacheTest.php diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index e5bb80b5d..8ed5f54e0 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -1,6 +1,7 @@ $this->getPublicDir(), - 'fileExtension' => $this->getFileException(), - 'fileLocking' => $this->getFileLocking(), - 'tagStorage' => $this->getTagStorage(), + 'public_dir' => $this->getPublicDir(), + 'file_locking' => $this->getFileLocking(), + 'tag_storage' => $this->getTagStorage(), + 'tag_key' => $this->getTagKey(), ); } @@ -146,12 +147,12 @@ public function getFileLocking() } /** - * Set a storage for tagging + * Set a storage for tagging or remove the storage * - * @param \Zend\Cache\Storage\Adapter $storage + * @param null|StorageAdapter $storage * @return CaptureCache */ - public function setTagStorage(Adapter $storage) + public function setTagStorage(StorageAdapter $storage = null) { $this->_tagStorage = $storage; return $this; @@ -160,7 +161,7 @@ public function setTagStorage(Adapter $storage) /** * Get the storage for tagging * - * @return null|\Zend\Cache\Storage\Adapter + * @return null|StorageAdapter */ public function getTagStorage() { diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php new file mode 100644 index 000000000..9c583c822 --- /dev/null +++ b/test/Pattern/CaptureCacheTest.php @@ -0,0 +1,52 @@ +_pattern = new Cache\Pattern\CaptureCache(array( + // TODO + )); + + parent::setUp(); + } + + public function tearDown() + { + // TODO + parent::tearDown(); + } + +} From 764208f808f05b2eff180751db3153a691c16de8 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 22:08:04 +0100 Subject: [PATCH 118/311] - don't use the full integer range on set the default umask - implemented umask on capture cache --- src/Pattern/CaptureCache.php | 166 +++++++++++++++++++++++++++-- src/Storage/Adapter/Filesystem.php | 4 +- 2 files changed, 159 insertions(+), 11 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 8ed5f54e0..e20fcfd31 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -13,6 +13,20 @@ class CaptureCache extends AbstractPattern */ protected $_publicDir = null; + /** + * Used umask on creating a cache directory + * + * @var int + */ + protected $_dirUmask = 0007; + + /** + * Used umask on creating a cache file + * + * @var int + */ + protected $_fileUmask = 0117; + /** * Lock files on writing * @@ -74,6 +88,10 @@ public function getOptions() { return array( 'public_dir' => $this->getPublicDir(), + 'dir_perm' => $this->getDirPerm(), + 'dir_umask' => $this->getDirUmask(), + 'file_perm' => $this->getFilePerm(), + 'file_umask' => $this->getFileUmask(), 'file_locking' => $this->getFileLocking(), 'tag_storage' => $this->getTagStorage(), 'tag_key' => $this->getTagKey(), @@ -103,25 +121,133 @@ public function getPublicDir() } /** - * Set index filename + * Set directory permissions * - * @param string $filename + * @param int|string $perm Permissions as octal number * @return CaptureCache */ - public function setIndexFilename($filename) + public function setDirPerm($perm) { - $this->_indexFilename = (string)$filename; + if (is_string($perm)) { + $perm = octdec($perm); + } else { + $perm = (int)$perm; + } + + // use umask + return $this->setDirUmask(~$perm); + } + + /** + * Get directory permissions + * + * @return int + */ + public function getDirPerm() + { + return ~$this->getDirUmask(); + } + + /** + * Set directory umask + * + * @param int|string $umask Umask as octal number + * @return CaptureCache + */ + public function setDirUmask($umask) + { + if (is_string($umask)) { + $umask = octdec($umask); + } else { + $umask = (int)$umask; + } + + if ((~$umask & 0700) != 0700 ) { + throw new InvalidArgumentException( + 'Invalid directory umask or directory permissions: ' + . 'need permissions to execute, read and write directories by owner' + ); + } + + $this->_dirUmask = $umask; return $this; } /** - * Get index filename + * Get directory umask * - * @return string + * @return int */ - public function getIndexFilename() + public function getDirUmask() { - return $this->_indexFilename; + return $this->_dirUmask; + } + + /** + * Set file permissions + * + * @param int|string $perm Permissions as octal number + * @return CaptureCache + */ + public function setFilePerm($perm) + { + if (is_string($perm)) { + $perm = octdec($perm); + } else { + $perm = (int)$perm; + } + + // use umask + return $this->setFileUmask(~$perm); + } + + /** + * Get file permissions + * + * @return int + */ + public function getFilePerm() + { + return ~$this->getFileUmask(); + } + + /** + * Set file umask + * + * @param int|string $umask Umask as octal number + * @return CaptureCache + */ + public function setFileUmask($umask) + { + if (is_string($umask)) { + $umask = octdec($umask); + } else { + $umask = (int)$umask; + } + if ((~$umask & 0600) != 0600 ) { + throw new InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'need permissions to read and write files by owner' + ); + } elseif ((~$umask & 0111) > 0) { + throw new InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'executable cache files are not allowed' + ); + } + + $this->_fileUmask = $umask; + return $this; + } + + /** + * Get file umask + * + * @return int + */ + public function getFileUmask() + { + return $this->_fileUmask; } /** @@ -146,6 +272,28 @@ public function getFileLocking() return $this->_fileLocking; } + /** + * Set index filename + * + * @param string $filename + * @return CaptureCache + */ + public function setIndexFilename($filename) + { + $this->_indexFilename = (string)$filename; + return $this; + } + + /** + * Get index filename + * + * @return string + */ + public function getIndexFilename() + { + return $this->_indexFilename; + } + /** * Set a storage for tagging or remove the storage * @@ -403,7 +551,7 @@ protected function _save($output) $path = $this->_pageId2Path($this->_pageId); $fullPath = $this->getPublicDir() . DIRECTORY_SEPARATOR . $path; if (!file_exists($fullPath)) { - $oldUmask = umask($this->getDirectoryUmask()); + $oldUmask = umask($this->getDirUmask()); if (!@mkdir($fullPath, 0777, true)) { $lastErr = error_get_last(); throw new RuntimeException( diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 178adcce9..978cef06d 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -45,7 +45,7 @@ class Filesystem extends AbstractAdapter * * @var int */ - protected $_fileUmask = -433; // ~0660 + protected $_fileUmask = 0117; /** * Lock files on writing @@ -69,7 +69,7 @@ class Filesystem extends AbstractAdapter * * @var int */ - protected $_dirUmask = -505; // ~0770 + protected $_dirUmask = 0007; /** * How much sub-directaries should be created? From 953fce89097997598ec2d9513102e6fd612e10f9 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 23:10:49 +0100 Subject: [PATCH 119/311] set default result value to false on ExceptionEvent --- src/Storage/ExceptionEvent.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index e2a59443a..c5cccbfda 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -25,10 +25,9 @@ class ExceptionEvent extends Event * The result/return value * if the exception shouldn't throw * - * * @var mixed */ - protected $result; + protected $result = false; /** * Constructor From eb271d96769600791e5acbd2887121d2390f622e Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 23:11:42 +0100 Subject: [PATCH 120/311] added exception handler storage plugin --- src/Storage/Plugin/ExceptionHandler.php | 150 +++++++++++++++++++ test/Storage/Plugin/ExceptionHandlerTest.php | 143 ++++++++++++++++++ 2 files changed, 293 insertions(+) create mode 100644 src/Storage/Plugin/ExceptionHandler.php create mode 100644 test/Storage/Plugin/ExceptionHandlerTest.php diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php new file mode 100644 index 000000000..b5adcff06 --- /dev/null +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -0,0 +1,150 @@ +setOptions($options); + } + + public function setOptions($options) + { + foreach ($options as $name => $value) { + $m = 'set' . str_replace('_', '', $name); + $this->$m($value); + } + } + + public function getOptions() + { + $options = parent::getOptions(); + $options['callback'] = $this->getExceptionHandler(); + $options['throw_exceptions'] = $this->getThrowExceptions(); + return $options; + } + + public function setCallback($callback) + { + if (!is_callable($callback, true)) { + throw new InvalidArgumentException('Not a valid callback'); + } + $this->_callback = $callback; + } + + public function getCallback() + { + return $this->_callback; + } + + public function setThrowExceptions($flag) + { + $this->_throwExceptions = (bool)$flag; + } + + public function getThrowExceptions() + { + return $this->_throwExceptions; + } + + public function attach(EventCollection $eventCollection) + { + $index = \spl_object_hash($eventCollection); + if (isset($this->handles[$index])) { + throw new LogicException('Plugin already attached'); + } + + $callback = array($this, 'onException'); + $handles = array(); + $this->handles[$index] = & $handles; + + // read + $handles[] = $eventCollection->attach('getItem.exception', $callback); + $handles[] = $eventCollection->attach('getItems.exception', $callback); + + $handles[] = $eventCollection->attach('hasItem.exception', $callback); + $handles[] = $eventCollection->attach('hasItems.exception', $callback); + + $handles[] = $eventCollection->attach('getMetadata.exception', $callback); + $handles[] = $eventCollection->attach('getMetadatas.exception', $callback); + + // non-blocking + $handles[] = $eventCollection->attach('getDelayed.exception', $callback); + $handles[] = $eventCollection->attach('find.exception', $callback); + + $handles[] = $eventCollection->attach('fetch.exception', $callback); + $handles[] = $eventCollection->attach('fetchAll.exception', $callback); + + // write + $handles[] = $eventCollection->attach('setItem.exception', $callback); + $handles[] = $eventCollection->attach('setItems.exception', $callback); + + $handles[] = $eventCollection->attach('addItem.exception', $callback); + $handles[] = $eventCollection->attach('addItems.exception', $callback); + + $handles[] = $eventCollection->attach('replaceItem.exception', $callback); + $handles[] = $eventCollection->attach('replaceItems.exception', $callback); + + $handles[] = $eventCollection->attach('touchItem.exception', $callback); + $handles[] = $eventCollection->attach('touchItems.exception', $callback); + + $handles[] = $eventCollection->attach('removeItem.exception', $callback); + $handles[] = $eventCollection->attach('removeItems.exception', $callback); + + $handles[] = $eventCollection->attach('checkAndSetItem.exception', $callback); + + // increment / decrement item(s) + $handles[] = $eventCollection->attach('incrementItem.exception', $callback); + $handles[] = $eventCollection->attach('incrementItems.exception', $callback); + + $handles[] = $eventCollection->attach('decrementItem.exception', $callback); + $handles[] = $eventCollection->attach('decrementItems.exception', $callback); + + // clear + $handles[] = $eventCollection->attach('clear.exception', $callback); + $handles[] = $eventCollection->attach('clearByNamespace.exception', $callback); + + // additional + $handles[] = $eventCollection->attach('optimize.exception', $callback); + $handles[] = $eventCollection->attach('getCapacity.exception', $callback); + + return $this; + } + + public function detach(EventCollection $eventCollection) + { + $index = \spl_object_hash($eventCollection); + if (!isset($this->handles[$index])) { + throw new LogicException('Plugin not attached'); + } + + // detach all handles of this index + foreach ($this->handles[$index] as $handle) { + $eventCollection->detach($handle); + } + + // remove all detached handles + unset($this->handles[$index]); + + return $this; + } + + public function onException(ExceptionEvent $event) + { + if ( ($callback = $this->getCallback()) ) { + $callback($event->getException()); + } + + $event->setThrowException( $this->getThrowExceptions() ); + } + +} diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php new file mode 100644 index 000000000..6263db0a5 --- /dev/null +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -0,0 +1,143 @@ +_adapter = new MockAdapter(); + $this->_plugin = new Cache\Storage\Plugin\ExceptionHandler(); + } + + public function testAddPlugin() + { + $this->_adapter->addPlugin($this->_plugin); + + // check attached callbacks + $expectedListeners = array( + 'getItem.exception' => 'onException', + 'getItems.exception' => 'onException', + + 'hasItem.exception' => 'onException', + 'hasItems.exception' => 'onException', + + 'getMetadata.exception' => 'onException', + 'getMetadatas.exception' => 'onException', + + 'getDelayed.exception' => 'onException', + 'find.exception' => 'onException', + + 'fetch.exception' => 'onException', + 'fetchAll.exception' => 'onException', + + 'setItem.exception' => 'onException', + 'setItems.exception' => 'onException', + + 'addItem.exception' => 'onException', + 'addItems.exception' => 'onException', + + 'replaceItem.exception' => 'onException', + 'replaceItems.exception' => 'onException', + + 'touchItem.exception' => 'onException', + 'touchItems.exception' => 'onException', + + 'removeItem.exception' => 'onException', + 'removeItems.exception' => 'onException', + + 'checkAndSetItem.exception' => 'onException', + + 'incrementItem.exception' => 'onException', + 'incrementItems.exception' => 'onException', + + 'decrementItem.exception' => 'onException', + 'decrementItems.exception' => 'onException', + + 'clear.exception' => 'onException', + 'clearByNamespace.exception' => 'onException', + + 'optimize.exception' => 'onException', + 'getCapacity.exception' => 'onException', + ); + foreach ($expectedListeners as $eventName => $expectedCallbackMethod) { + $listeners = $this->_adapter->events()->getListeners($eventName); + + // event should attached only once + $this->assertSame(1, $listeners->count()); + + // check expected callback method + $cb = $listeners->top()->getCallback(); + $this->assertArrayHasKey(0, $cb); + $this->assertSame($this->_plugin, $cb[0]); + $this->assertArrayHasKey(1, $cb); + $this->assertSame($expectedCallbackMethod, $cb[1]); + } + } + + public function testRemovePlugin() + { + $this->_adapter->addPlugin($this->_plugin); + $this->_adapter->removePlugin($this->_plugin); + + // no events should be attached + $this->assertEquals(0, count($this->_adapter->events()->getEvents())); + } + + public function testOnExceptionCallCallback() + { + $expectedException = new \Exception(); + $callbackCalled = false; + + $this->_plugin->setCallback(function ($exception) use ($expectedException, &$callbackCalled) { + $callbackCalled = ($exception === $expectedException); + }); + + // run onException + $event = new ExceptionEvent('getItem.exception', $this->_adapter, new ArrayObject(array( + 'key' => 'key', + 'options' => array() + )), $expectedException); + $this->_plugin->onException($event); + + $this->assertTrue( + $callbackCalled, + "Expected callback wasn't called or the expected exception wasn't the first argument" + ); + } + + public function testDontThrowException() + { + $this->_plugin->setThrowExceptions(false); + + // run onException + $event = new ExceptionEvent('getItem.exception', $this->_adapter, new ArrayObject(array( + 'key' => 'key', + 'options' => array() + )), new \Exception()); + $this->_plugin->onException($event); + + $this->assertFalse($event->getThrowException()); + $this->assertFalse($event->getResult()); + } + +} From 35b598e79bf58d9a2cb2adc58d2a975fe303e7bc Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 7 Dec 2011 23:25:00 +0100 Subject: [PATCH 121/311] added missing plugin methods [get|set]Options --- src/Storage/Plugin.php | 26 +++++++++++++++++++++++++- src/Storage/Plugin/Serializer.php | 7 +++++++ test/Storage/TestAsset/MockPlugin.php | 17 +++++++++++++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/Storage/Plugin.php b/src/Storage/Plugin.php index 3b5980b22..f1bd266a2 100644 --- a/src/Storage/Plugin.php +++ b/src/Storage/Plugin.php @@ -5,4 +5,28 @@ use Zend\EventManager\ListenerAggregate; interface Plugin extends ListenerAggregate -{} +{ + + /** + * Constructor + * + * @param array|Traversable $options + */ + public function __construct($options = array()); + + /** + * Set options + * + * @param array|Traversable $options + * @return Plugin + */ + public function setOptions($options); + + /** + * Get options + * + * @return array + */ + public function getOptions(); + +} diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index efb306231..b07a1579a 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -30,6 +30,13 @@ public function setOptions($options) } } + public function getOptions() + { + return array( + 'serializer' => $this->getSerializer(), + ); + } + public function setSerializer(SerializerAdapter $serializer) { $this->serializer = $serializer; diff --git a/test/Storage/TestAsset/MockPlugin.php b/test/Storage/TestAsset/MockPlugin.php index 64e750392..d6026f58c 100644 --- a/test/Storage/TestAsset/MockPlugin.php +++ b/test/Storage/TestAsset/MockPlugin.php @@ -9,6 +9,7 @@ class MockPlugin implements Plugin { + protected $options = array(); protected $handles = array(); protected $calledEvents = array(); protected $eventCallbacks = array( @@ -16,6 +17,22 @@ class MockPlugin implements Plugin 'setItem.post' => 'onSetItemPost' ); + public function __construct($options = array()) + { + $this->setOptions($options); + } + + public function setOptions($options) + { + $this->options = $options; + return $this; + } + + public function getOptions() + { + return $this->options; + } + public function attach(EventCollection $eventCollection) { $handles = array(); From 605ed71706d762ed9106e34ca8960e3b8275ebf7 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 8 Dec 2011 09:14:42 +0100 Subject: [PATCH 122/311] - phpdoc - type hint of exception argument on triggerException - optimized internal method to normalize select array --- src/Storage/Adapter.php | 51 +++++++++++------- src/Storage/Adapter/AbstractAdapter.php | 72 ++++++++++++++----------- 2 files changed, 73 insertions(+), 50 deletions(-) diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index 412dfc724..fd13927e1 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -122,7 +122,7 @@ public function hasItem($key, array $options = array()); * * @param array $keys * @param array $options - * @return array Assoziative array of existing keys + * @return array Array of existing keys * @throws Zend\Cache\Exception */ public function hasItems(array $keys, array $options = array()); @@ -215,12 +215,17 @@ public function replaceItems(array $keyValuePairs, array $options = array()); /** * Set item only if token matches * + * It uses the token from received from getItem to + * check if the item has changed befor overwrite it. + * * @param mixed $token * @param string|null $key * @param mixed $value * @param array $options * @return boolean * @throws Zend\Cache\Exception + * @see getItem() + * @see setItem() */ public function checkAndSetItem($token, $key, $value, array $options = array()); @@ -229,7 +234,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()); * * @param string $key * @param array $options - * @return boolean True on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function touchItem($key, array $options = array()); @@ -239,7 +244,7 @@ public function touchItem($key, array $options = array()); * * @param array $keys * @param array $options - * @return boolean True on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function touchItems(array $keys, array $options = array()); @@ -249,7 +254,7 @@ public function touchItems(array $keys, array $options = array()); * * @param string $key * @param array $options - * @return boolean True on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function removeItem($key, array $options = array()); @@ -259,7 +264,7 @@ public function removeItem($key, array $options = array()); * * @param array $keys * @param array $options - * @return boolean True on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function removeItems(array $keys, array $options = array()); @@ -270,7 +275,7 @@ public function removeItems(array $keys, array $options = array()); * @param string $key * @param int $value * @param array $options - * @return boolean True on success or false on failure + * @return int|boolean The new value of false on failure * @throws Zend\Cache\Exception */ public function incrementItem($key, $value, array $options = array()); @@ -280,7 +285,7 @@ public function incrementItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean True on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function incrementItems(array $keyValuePairs, array $options = array()); @@ -291,7 +296,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()); * @param string $key * @param int $value * @param array $options - * @return boolean True on success or false on failure + * @return int|boolean The new value or false or failure * @throws Zend\Cache\Exception */ public function decrementItem($key, $value, array $options = array()); @@ -301,7 +306,7 @@ public function decrementItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean True on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function decrementItems(array $keyValuePairs, array $options = array()); @@ -313,18 +318,22 @@ public function decrementItems(array $keyValuePairs, array $options = array()); * * @param array $keys * @param array $options - * @return boolean true on success or fale on failure + * @return boolean * @throws Zend\Cache\Exception + * @see fetch() + * @see fetchAll() */ public function getDelayed(array $keys, array $options = array()); /** * Find items. * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::*) * @param array $options - * @return boolean true on success or fale on failure - * @throw Zend\Cache\Exception + * @return boolean + * @throws Zend\Cache\Exception + * @see fetch() + * @see fetchAll() */ public function find($mode = self::MATCH_ACTIVE, array $options = array()); @@ -333,6 +342,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()); * * @return array|boolean The next item or false * @throws Zend\Cache\Exception + * @see fetchAll() */ public function fetch(); @@ -341,6 +351,7 @@ public function fetch(); * * @return array The result set as array containing all items * @throws Zend\Cache\Exception + * @see fetch() */ public function fetchAll(); @@ -351,8 +362,9 @@ public function fetchAll(); * * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) * @param array $options - * @return boolean True on success or false on failure - * @throw Zend\Cache\Exception + * @return boolean + * @throws Zend\Cache\Exception + * @see clearByNamespace() */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()); @@ -361,8 +373,9 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()); * * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) * @param array $options - * @return boolean True on success or false on failure - * @throw Zend\Cache\Exception + * @return boolean + * @throws Zend\Cache\Exception + * @see clear() */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()); @@ -370,7 +383,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a * Optimize adapter storage. * * @param array $options - * @return boolean true on success or false on failure + * @return boolean * @throws Zend\Cache\Exception */ public function optimize(array $options = array()); @@ -389,7 +402,7 @@ public function getCapabilities(); * * @param array $options * @return array|boolean Capacity as array or false on failure - * @throw Zend\Cache\Exception + * @throws Zend\Cache\Exception */ public function getCapacity(array $options = array()); diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 9b3ecc6c6..011f4e5ab 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -21,28 +21,28 @@ abstract class AbstractAdapter implements Adapter /** * The used EventManager if any * - * @var null|Zend\EventManager\EventManager + * @var null|EventManager */ protected $_events = null; /** * The plugin registry * - * @var Zend\Cache\Storage\Plugin[] + * @var array Array of registered plugins */ protected $_pluginRegistry = array(); /** * Capabilities of this adapter * - * @var null|Zend\Cache\Storage\Capabilities + * @var null|Capabilities */ protected $_capabilities = null; /** * Marker to change capabilities * - * @var null|stdClass + * @var null|object */ protected $_capabilityMarker; @@ -102,15 +102,25 @@ abstract class AbstractAdapter implements Adapter protected $_stmtKeys = null; protected $_stmtOptions = null; + /** + * Constructor + * + * @param array|Traversable $options + * @see setOptions() + */ public function __construct($options = array()) { $this->setOptions($options); } + /** + * Destructor + * + * detach all registered plugins to free + * event handles of event manager + */ public function __destruct() { - // detach all registered plugins to free - // event handles of internal event manager foreach ($this->getPlugins() as $plugin) { $this->removePlugin($plugin); } @@ -121,10 +131,9 @@ public function __destruct() /** * Set options. * - * @see __constructor - * @see getOptions - * @param array@Traversable $options - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @param array|Traversable $options + * @return AbstractAdapter + * @see getOptions() */ public function setOptions($options) { @@ -146,8 +155,8 @@ public function setOptions($options) /** * Get options. * - * @see setOptions * @return array + * @see setOptions() */ public function getOptions() { @@ -167,7 +176,7 @@ public function getOptions() * Enable/Disable writing data to cache. * * @param boolean $flag - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setWritable($flag) { @@ -189,7 +198,7 @@ public function getWritable() * Enable/Disable reading data from cache. * * @param boolean $flag - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setReadable($flag) { @@ -214,7 +223,7 @@ public function getReadable() * @see setWritable * @see setReadable * @param boolean $flag - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setCaching($flag) { @@ -241,7 +250,7 @@ public function getCaching() * Set time to life. * * @param int|float $ttl - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setTtl($ttl) { @@ -264,7 +273,7 @@ public function getTtl() * Set namespace. * * @param string $namespace - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setNamespace($namespace) { @@ -297,7 +306,7 @@ public function getNamespace() * Set namespace pattern * * @param null|string $pattern - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setNamespacePattern($pattern) { @@ -337,7 +346,7 @@ public function getNamespacePattern() * Set key pattern * * @param null|string $pattern - * @return Zend\Cache\Storage\Adapter\AbstractAdapter + * @return AbstractAdapter */ public function setKeyPattern($pattern) { @@ -373,14 +382,14 @@ public function getKeyPattern() * - getItem, getMetadata: return false * - removeItem[s]: return true * - incrementItem[s], decrementItem[s]: add a new item with 0 as base - * - touchItem[s]: add new new empty item + * - touchItem[s]: add new empty item * * - If disabled and a missing item was requested: * - getItem, getMetadata, incrementItem[s], decrementItem[s], touchItem[s] * throws ItemNotFoundException * * @param boolean $flag - * @return Zend\Cache\Storage\Adapter + * @return Adapter */ public function setIgnoreMissingItems($flag) { @@ -391,8 +400,8 @@ public function setIgnoreMissingItems($flag) /** * Ignore missing items * - * @see setIgnoreMissingItems to get more information * @return boolean + * @see setIgnoreMissingItems() to get more information */ public function getIgnoreMissingItems() { @@ -454,9 +463,10 @@ protected function triggerPost($eventName, \ArrayObject $args, &$result) * @param string $eventName * @param ArrayObject $args * @param Exception $exception + * @throws Exception * @return mixed */ - protected function triggerException($eventName, \ArrayObject $args, $exception) + protected function triggerException($eventName, \ArrayObject $args, \Exception $exception) { $exceptionEvent = new ExceptionEvent($eventName . '.exception', $this, $args, $exception); $eventRs = $this->events()->trigger($exceptionEvent); @@ -487,7 +497,7 @@ public function hasPlugin(Plugin $plugin) * Register a plugin * * @param Plugin $plugin - * @return Zend\Cache\Storage\Adapter Fluent interface + * @return Adapter Fluent interface * @throws LogicException */ public function addPlugin(Plugin $plugin) @@ -506,7 +516,7 @@ public function addPlugin(Plugin $plugin) * Unregister an already registered plugin * * @param Plugin $plugin - * @return Zend\Cache\Storage\Adapter Fluent interface + * @return Adapter Fluent interface * @throws LogicException */ public function removePlugin(Plugin $plugin) @@ -525,7 +535,7 @@ public function removePlugin(Plugin $plugin) /** * Get all registered plugins * - * @return Zend\Cache\Storage\Plugin[] + * @return array */ public function getPlugins() { @@ -922,7 +932,7 @@ public function optimize(array $options = array()) /** * Get capabilities of this adapter * - * @return Zend\Cache\Storage\Capabilities + * @return Capabilities */ public function getCapabilities() { @@ -982,7 +992,7 @@ protected function _normalizeOptions(array &$options) * Validates and normalize a TTL. * * @param int|float $ttl - * @throws Zend\Cache\InvalidArgumentException + * @throws InvalidArgumentException */ protected function _normalizeTtl(&$ttl) { @@ -1004,7 +1014,7 @@ protected function _normalizeTtl(&$ttl) * Validates and normalize a namespace. * * @param string $namespace - * @throws Zend\Cache\InvalidArgumentException + * @throws InvalidArgumentException */ protected function _normalizeNamespace(&$namespace) { @@ -1050,9 +1060,9 @@ protected function _normalizeSelect(&$select) { if (!is_array($select)) { $select = array((string)$select); + } else { + $select = array_unique($select); } - - $select = array_unique($select); } /** @@ -1077,7 +1087,7 @@ protected function _normalizeMatchingMode(&$mode, $default, array &$normalizedOp * * @param string $key * @return string - * @throws Zend\Cache\InvalidArgumentException + * @throws InvalidArgumentException */ protected function _key($key) { From e218ef693e62daedfb28af7d7eccf77ae0474ffe Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 8 Dec 2011 09:19:40 +0100 Subject: [PATCH 123/311] removed some underscores of private/protected members --- src/PatternFactory.php | 12 ++++++------ src/StorageFactory.php | 24 ++++++++++++------------ src/Utils.php | 12 ++++++------ 3 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/PatternFactory.php b/src/PatternFactory.php index 5dc856008..db9b6509b 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -12,7 +12,7 @@ class PatternFactory * * @var null|Zend\Loader\Broker */ - protected static $_broker = null; + protected static $broker = null; /** * Instantiate a cache pattern @@ -39,11 +39,11 @@ public static function factory($patternName, $options = array()) */ public static function getBroker() { - if (self::$_broker === null) { - self::$_broker = self::_getDefaultBroker(); + if (self::$broker === null) { + self::$broker = self::_getDefaultBroker(); } - return self::$_broker; + return self::$broker; } /** @@ -54,7 +54,7 @@ public static function getBroker() */ public static function setBroker(Broker $broker) { - self::$_broker = $broker; + self::$broker = $broker; } /** @@ -64,7 +64,7 @@ public static function setBroker(Broker $broker) */ public static function resetBroker() { - self::$_broker = null; + self::$broker = null; } /** diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 2d96ffca1..923ec9178 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -13,14 +13,14 @@ class StorageFactory * * @var null|Zend\Loader\Broker */ - protected static $_adapterBroker = null; + protected static $adapterBroker = null; /** * Broker for loading plugins * * @var null|Zend\Loader\Broker */ - protected static $_pluginBroker = null; + protected static $pluginBroker = null; /** * The storage factory @@ -138,10 +138,10 @@ public static function adapterFactory($adapterName, $options = array()) */ public static function getAdapterBroker() { - if (self::$_adapterBroker === null) { - self::$_adapterBroker = new Storage\AdapterBroker(); + if (self::$adapterBroker === null) { + self::$adapterBroker = new Storage\AdapterBroker(); } - return self::$_adapterBroker; + return self::$adapterBroker; } /** @@ -152,7 +152,7 @@ public static function getAdapterBroker() */ public static function setAdapterBroker(Broker $broker) { - self::$_adapterBroker = $broker; + self::$adapterBroker = $broker; } /** @@ -160,7 +160,7 @@ public static function setAdapterBroker(Broker $broker) */ public static function resetAdapterBroker() { - self::$_adapterBroker = new Storage\AdapterBroker(); + self::$adapterBroker = new Storage\AdapterBroker(); } /** @@ -189,10 +189,10 @@ public static function pluginFactory($pluginName, $options = array()) */ public static function getPluginBroker() { - if (self::$_pluginBroker === null) { - self::$_pluginBroker = new Storage\PluginBroker(); + if (self::$pluginBroker === null) { + self::$pluginBroker = new Storage\PluginBroker(); } - return self::$_pluginBroker; + return self::$pluginBroker; } /** @@ -203,7 +203,7 @@ public static function getPluginBroker() */ public static function setPluginBroker(Broker $broker) { - self::$_pluginBroker = $broker; + self::$pluginBroker = $broker; } /** @@ -211,7 +211,7 @@ public static function setPluginBroker(Broker $broker) */ public static function resetPluginBroker() { - self::$_pluginBroker = new Storage\PluginBroker(); + self::$pluginBroker = new Storage\PluginBroker(); } } diff --git a/src/Utils.php b/src/Utils.php index a4f50ef19..3499fa487 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -41,7 +41,7 @@ static public function getDiskCapacity($path) */ static public function getPhpMemoryCapacity() { - $memSize = (float)self::_bytesFromString(ini_get('memory_limit')); + $memSize = (float)self::bytesFromString(ini_get('memory_limit')); if ($memSize <= 0) { return self::getSystemMemoryCapacity(); } @@ -83,16 +83,16 @@ static public function getSystemMemoryCapacity() $memFree = 0; if (isset($meminfoIndex['MemTotal'])) { - $memTotal+= self::_bytesFromString( $meminfoValues[ $meminfoIndex['MemTotal'] ] ); + $memTotal+= self::bytesFromString( $meminfoValues[ $meminfoIndex['MemTotal'] ] ); } if (isset($meminfoIndex['MemFree'])) { - $memFree+= self::_bytesFromString( $meminfoValues[ $meminfoIndex['MemFree'] ] ); + $memFree+= self::bytesFromString( $meminfoValues[ $meminfoIndex['MemFree'] ] ); } if (isset($meminfoIndex['Buffers'])) { - $memFree+= self::_bytesFromString( $meminfoValues[ $meminfoIndex['Buffers'] ] ); + $memFree+= self::bytesFromString( $meminfoValues[ $meminfoIndex['Buffers'] ] ); } if (isset($meminfoIndex['Cached'])) { - $memFree+= self::_bytesFromString( $meminfoValues[ $meminfoIndex['Cached'] ] ); + $memFree+= self::bytesFromString( $meminfoValues[ $meminfoIndex['Cached'] ] ); } return array( @@ -201,7 +201,7 @@ static public function getHashAlgos() * @return float * @throws Zend\Cache\Exception\RuntimeException */ - static protected function _bytesFromString($memStr) + static protected function bytesFromString($memStr) { if (preg_match('/\s*([\-\+]?\d+)\s*(\w*)\s*/', $memStr, $matches)) { $value = (float)$matches[1]; From 30bfbde7bf7b0efadc818ebbe971972148516ec5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 8 Dec 2011 09:30:18 +0100 Subject: [PATCH 124/311] removed underscore of private/protected members of pattern namespace --- src/Pattern/CallbackCache.php | 12 ++-- src/Pattern/CaptureCache.php | 104 +++++++++++++++++----------------- src/Pattern/ClassCache.php | 66 ++++----------------- src/Pattern/ObjectCache.php | 80 +++++++------------------- src/Pattern/OutputCache.php | 12 ++-- 5 files changed, 95 insertions(+), 179 deletions(-) diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index f0241e33c..40474e35d 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -13,14 +13,14 @@ class CallbackCache extends AbstractPattern * * @var Zend\Cache\Storage\Adapter */ - protected $_storage; + protected $storage; /** * Caching output stream * * @var boolean */ - protected $_cacheOutput = true; + protected $cacheOutput = true; /** * Constructor @@ -57,7 +57,7 @@ public function getOptions() */ public function getStorage() { - return $this->_storage; + return $this->storage; } /** @@ -80,7 +80,7 @@ public function setStorage($storage) ); } - $this->_storage = $storage; + $this->storage = $storage; return $this; } @@ -91,7 +91,7 @@ public function setStorage($storage) */ public function setCacheOutput($flag) { - $this->_cacheOutput = (bool)$flag; + $this->cacheOutput = (bool)$flag; return $this; } @@ -102,7 +102,7 @@ public function setCacheOutput($flag) */ public function getCacheOutput() { - return $this->_cacheOutput; + return $this->cacheOutput; } /** diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index e20fcfd31..844773b65 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -11,63 +11,63 @@ class CaptureCache extends AbstractPattern * * @var string */ - protected $_publicDir = null; + protected $publicDir = null; /** * Used umask on creating a cache directory * * @var int */ - protected $_dirUmask = 0007; + protected $dirUmask = 0007; /** * Used umask on creating a cache file * * @var int */ - protected $_fileUmask = 0117; + protected $fileUmask = 0117; /** * Lock files on writing * * @var boolean */ - protected $_fileLocking = true; + protected $fileLocking = true; /** * The index filename * * @var string */ - protected $_indexFilename = 'index.html'; + protected $indexFilename = 'index.html'; /** * Page identifier * * @var null|string */ - protected $_pageId = null; + protected $pageId = null; /** * Storage for tagging * * @var null|StorageAdapter */ - protected $_tagStorage = null; + protected $tagStorage = null; /** * Cache item key to store tags * * @var string */ - protected $_tagKey = 'ZendCachePatternCaptureCache_Tags'; + protected $tagKey = 'ZendCachePatternCaptureCache_Tags'; /** * Tags * * @var array */ - protected $_tags = array(); + protected $tags = array(); /** * Constructor @@ -106,7 +106,7 @@ public function getOptions() */ public function setPublicDir($dir) { - $this->_publicDir = $dir; + $this->publicDir = $dir; return $this; } @@ -117,7 +117,7 @@ public function setPublicDir($dir) */ public function getPublicDir() { - return $this->_publicDir; + return $this->publicDir; } /** @@ -169,7 +169,7 @@ public function setDirUmask($umask) ); } - $this->_dirUmask = $umask; + $this->dirUmask = $umask; return $this; } @@ -180,7 +180,7 @@ public function setDirUmask($umask) */ public function getDirUmask() { - return $this->_dirUmask; + return $this->dirUmask; } /** @@ -236,7 +236,7 @@ public function setFileUmask($umask) ); } - $this->_fileUmask = $umask; + $this->fileUmask = $umask; return $this; } @@ -247,7 +247,7 @@ public function setFileUmask($umask) */ public function getFileUmask() { - return $this->_fileUmask; + return $this->fileUmask; } /** @@ -258,7 +258,7 @@ public function getFileUmask() */ public function setFileLocking($flag) { - $this->_fileLocking = (boolean)$flag; + $this->fileLocking = (boolean)$flag; return $this; } @@ -269,7 +269,7 @@ public function setFileLocking($flag) */ public function getFileLocking() { - return $this->_fileLocking; + return $this->fileLocking; } /** @@ -280,7 +280,7 @@ public function getFileLocking() */ public function setIndexFilename($filename) { - $this->_indexFilename = (string)$filename; + $this->indexFilename = (string)$filename; return $this; } @@ -291,7 +291,7 @@ public function setIndexFilename($filename) */ public function getIndexFilename() { - return $this->_indexFilename; + return $this->indexFilename; } /** @@ -302,7 +302,7 @@ public function getIndexFilename() */ public function setTagStorage(StorageAdapter $storage = null) { - $this->_tagStorage = $storage; + $this->tagStorage = $storage; return $this; } @@ -313,7 +313,7 @@ public function setTagStorage(StorageAdapter $storage = null) */ public function getTagStorage() { - return $this->_tagStorage; + return $this->tagStorage; } /** @@ -328,7 +328,7 @@ public function setTagKey($tagKey) throw new InvalidArgumentException("Missing tag key '{$tagKey}'"); } - $this->_tagKey = $tagKey; + $this->tagKey = $tagKey; return $this; } @@ -339,7 +339,7 @@ public function setTagKey($tagKey) */ public function getTagKey() { - return $this->_tagKey; + return $this->tagKey; } /** @@ -350,7 +350,7 @@ public function getTagKey() */ public function setTags(array $tags) { - $this->_tags = $tags; + $this->tags = $tags; return $this; } @@ -361,7 +361,7 @@ public function setTags(array $tags) */ public function getTags() { - return $this->_tags; + return $this->tags; } /** @@ -373,8 +373,8 @@ public function getTags() */ public function start($pageId = null, array $options = array()) { - if ($this->_pageId !== null) { - throw new RuntimeException("Capturing already stated with page id '{$this->_pageId}'"); + if ($this->pageId !== null) { + throw new RuntimeException("Capturing already stated with page id '{$this->pageId}'"); } if (isset($options['tags'])) { @@ -387,12 +387,12 @@ public function start($pageId = null, array $options = array()) } if (($pageId = (string)$pageId) === '') { - $pageId = $this->_detectPageId(); + $pageId = $this->detectPageId(); } - ob_start(array($this, '_flush')); - ob_implicit_flush(false); - $this->_pageId = $pageId; + ob_start(array($this, 'flush')); + ob_implicitflush(false); + $this->pageId = $pageId; return false; } @@ -408,12 +408,12 @@ public function start($pageId = null, array $options = array()) public function get($pageId = null, array $options = array()) { if (($pageId = (string)$pageId) === '') { - $pageId = $this->_detectPageId(); + $pageId = $this->detectPageId(); } $file = $this->getPublicDir() - . DIRECTORY_SEPARATOR . $this->_pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->_pageId2Filename($pageId); + . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { if (($content = @file_get_contents($file)) === false) { @@ -436,12 +436,12 @@ public function get($pageId = null, array $options = array()) public function exists($pageId = null, array $options = array()) { if (($pageId = (string)$pageId) === '') { - $pageId = $this->_detectPageId(); + $pageId = $this->detectPageId(); } $file = $this->getPublicDir() - . DIRECTORY_SEPARATOR . $this->_pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->_pageId2Filename($pageId); + . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); return file_exists($file); } @@ -457,12 +457,12 @@ public function exists($pageId = null, array $options = array()) public function remove($pageId = null, array $options = array()) { if (($pageId = (string)$pageId) === '') { - $pageId = $this->_detectPageId(); + $pageId = $this->detectPageId(); } $file = $this->getPublicDir() - . DIRECTORY_SEPARATOR . $this->_pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->_pageId2Filename($pageId); + . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { if (!@unlink($file)) { @@ -485,7 +485,7 @@ public function clear(/*TODO*/) * * @return string */ - protected function _detectPageId() + protected function detectPageId() { return $_SERVER['REQUEST_URI']; } @@ -496,7 +496,7 @@ protected function _detectPageId() * @param string $pageId * @return string */ - protected function _pageId2Filename($pageId) + protected function pageId2Filename($pageId) { $filename = basename($pageId); @@ -513,7 +513,7 @@ protected function _pageId2Filename($pageId) * @param string $pageId * @return string */ - protected function _pageId2Path($pageId) + protected function pageId2Path($pageId) { $path = rtrim(dirname($pageId), '/'); @@ -531,9 +531,9 @@ protected function _pageId2Path($pageId) * @param string $output Buffered output * @return boolean FALSE means original input is sent to the browser. */ - protected function _flush($output) + protected function flush($output) { - $this->_save($output); + $this->save($output); // http://php.net/manual/function.ob-start.php // -> If output_callback returns FALSE original input is sent to the browser. @@ -546,9 +546,9 @@ protected function _flush($output) * @param $output * @throws RuntimeException */ - protected function _save($output) + protected function save($output) { - $path = $this->_pageId2Path($this->_pageId); + $path = $this->pageId2Path($this->pageId); $fullPath = $this->getPublicDir() . DIRECTORY_SEPARATOR . $path; if (!file_exists($fullPath)) { $oldUmask = umask($this->getDirUmask()); @@ -565,9 +565,9 @@ protected function _save($output) } else { $oldUmask = umask($this->getFileUmask()); } - $file = $path . DIRECTORY_SEPARATOR . $this->_pageId2Filename($this->_pageId); + $file = $path . DIRECTORY_SEPARATOR . $this->pageId2Filename($this->pageId); $fullFile = $this->getPublicDir() . DIRECTORY_SEPARATOR . $file; - $this->_putFileContent($fullFile, $output); + $this->putFileContent($fullFile, $output); $tagStorage = $this->getTagStorage(); if ($tagStorage) { @@ -577,8 +577,8 @@ protected function _save($output) $tagIndex = null; } - if ($this->_tags) { - $tagIndex[$file] = &$this->_tags; + if ($this->tags) { + $tagIndex[$file] = &$this->tags; } elseif ($tagIndex) { unset($tagIndex[$file]); } @@ -596,7 +596,7 @@ protected function _save($output) * @param string $data Data to write * @throws RuntimeException */ - protected function _putFileContent($file, $data) + protected function putFileContent($file, $data) { $flags = FILE_BINARY; // since PHP 6 but defined as 0 in PHP 5.3 if ($this->getFileLocking()) { diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index 1c92ec16a..c22c68356 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -8,40 +8,33 @@ class ClassCache extends CallbackCache { - /** - * The storage adapter - * - * @var Zend\Cache\Storage\Adapter - */ - protected $_storage; - /** * The entity * * @var null|string */ - protected $_entity = null; + protected $entity = null; /** * Cache by default * * @var bool */ - protected $_cacheByDefault = true; + protected $cacheByDefault = true; /** * Cache methods * * @var array */ - protected $_cacheMethods = array(); + protected $cacheMethods = array(); /** * Non-cache methods * * @var array */ - protected $_nonCacheMethods = array(); + protected $nonCacheMethods = array(); /** * Constructor @@ -68,7 +61,6 @@ public function __construct($options = array()) public function getOptions() { $options = parent::getOptions(); - $options['storage'] = $this->getStorage(); $options['entity'] = $this->getEntity(); $options['cache_by_default'] = $this->getCacheByDefault(); $options['cache_methods'] = $this->getCacheMethods(); @@ -76,40 +68,6 @@ public function getOptions() return $options; } - /** - * Get cache storage - * - * return Zend\Cache\Storage\Adapter - */ - public function getStorage() - { - return $this->_storage; - } - - /** - * Set cache storage - * - * @param Zend\Cache\Storage\Adapter|array|string $storage - * @return Zend\Cache\Pattern\PatternInterface - */ - public function setStorage($storage) - { - if (is_array($storage)) { - $storage = Cache\StorageFactory::factory($storage); - } elseif (is_string($storage)) { - $storage = Cache\StorageFactory::adapterFactory($storage); - } elseif ( !($storage instanceof Cache\Storage\Adapter) ) { - throw new InvalidArgumentException( - 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' - . 'or an array passed to Zend\Cache\Storage::factory ' - . 'or simply the name of the storage adapter' - ); - } - - $this->_storage = $storage; - return $this; - } - /** * Set the entity to cache * @@ -121,7 +79,7 @@ public function setEntity($entity) if (!is_string($entity)) { throw new InvalidArgumentException('Invalid entity, must be a classname'); } - $this->_entity = $entity; + $this->entity = $entity; return $this; } @@ -132,7 +90,7 @@ public function setEntity($entity) */ public function getEntity() { - return $this->_entity; + return $this->entity; } /** @@ -143,7 +101,7 @@ public function getEntity() */ public function setCacheByDefault($flag) { - $this->_cacheByDefault = (bool)$flag; + $this->cacheByDefault = (bool)$flag; return $this; } @@ -154,7 +112,7 @@ public function setCacheByDefault($flag) */ public function getCacheByDefault() { - return $this->_cacheByDefault; + return $this->cacheByDefault; } /** @@ -165,7 +123,7 @@ public function getCacheByDefault() */ public function setCacheMethods(array $methods) { - $this->_cacheMethods = array_values(array_unique(array_map(function ($method) { + $this->cacheMethods = array_values(array_unique(array_map(function ($method) { return strtolower($method); }, $methods))); @@ -179,7 +137,7 @@ public function setCacheMethods(array $methods) */ public function getCacheMethods() { - return $this->_cacheMethods; + return $this->cacheMethods; } /** @@ -190,7 +148,7 @@ public function getCacheMethods() */ public function setNonCacheMethods(array $methods) { - $this->_nonCacheMethods = array_values(array_unique(array_map(function ($method) { + $this->nonCacheMethods = array_values(array_unique(array_map(function ($method) { return strtolower($method); }, $methods))); @@ -204,7 +162,7 @@ public function setNonCacheMethods(array $methods) */ public function getNonCacheMethods() { - return $this->_nonCacheMethods; + return $this->nonCacheMethods; } /** diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index 84e2851f1..cf2bfa871 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -8,54 +8,47 @@ class ObjectCache extends CallbackCache { - /** - * The storage adapter - * - * @var Zend\Cache\Storage\Adapter - */ - protected $_storage; - /** * The entity * * @var null|object */ - protected $_entity = null; + protected $entity = null; /** * The entity key * * @var null|string */ - protected $_entityKey = null; + protected $entityKey = null; /** * Cache by default * * @var bool */ - protected $_cacheByDefault = true; + protected $cacheByDefault = true; /** * Cache methods * * @var array */ - protected $_cacheMethods = array(); + protected $cacheMethods = array(); /** * Non-cache methods * * @var array */ - protected $_nonCacheMethods = array('__tostring'); + protected $nonCacheMethods = array('__tostring'); /** * Cache magic properties * * @var bool */ - protected $_cacheMagicProperties = false; + protected $cacheMagicProperties = false; /** * Constructor @@ -82,7 +75,6 @@ public function __construct($options = array()) public function getOptions() { $options = parent::getOptions(); - $options['storage'] = $this->getStorage(); $options['entity'] = $this->getEntity(); $options['entity_key'] = $this->getEntityKey(); $options['cache_by_default'] = $this->getCacheByDefault(); @@ -92,40 +84,6 @@ public function getOptions() return $options; } - /** - * Get cache storage - * - * return Zend\Cache\Storage\Adapter - */ - public function getStorage() - { - return $this->_storage; - } - - /** - * Set cache storage - * - * @param Zend\Cache\Storage\Adapter|array|string $storage - * @return Zend\Cache\Pattern\PatternInterface - */ - public function setStorage($storage) - { - if (is_array($storage)) { - $storage = Cache\StorageFactory::factory($storage); - } elseif (is_string($storage)) { - $storage = Cache\StorageFactory::adapterFactory($storage); - } elseif ( !($storage instanceof Cache\Storage\Adapter) ) { - throw new InvalidArgumentException( - 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' - . 'or an array passed to Zend\Cache\Storage::factory ' - . 'or simply the name of the storage adapter' - ); - } - - $this->_storage = $storage; - return $this; - } - /** * Set the entity to cache * @@ -137,7 +95,7 @@ public function setEntity($entity) if (!is_object($entity)) { throw new InvalidArgumentException('Invalid entity, must be an object'); } - $this->_entity = $entity; + $this->entity = $entity; return $this; } @@ -148,7 +106,7 @@ public function setEntity($entity) */ public function getEntity() { - return $this->_entity; + return $this->entity; } /** @@ -166,9 +124,9 @@ public function getEntity() public function setEntityKey($key) { if ($key !== null) { - $this->_entityKey = (string)$key; + $this->entityKey = (string)$key; } else { - $this->_entityKey = null; + $this->entityKey = null; } return $this; @@ -182,7 +140,7 @@ public function setEntityKey($key) */ public function getEntityKey() { - return $this->_entityKey; + return $this->entityKey; } /** @@ -193,7 +151,7 @@ public function getEntityKey() */ public function setCacheByDefault($flag) { - $this->_cacheByDefault = (bool)$flag; + $this->cacheByDefault = (bool)$flag; return $this; } @@ -204,7 +162,7 @@ public function setCacheByDefault($flag) */ public function getCacheByDefault() { - return $this->_cacheByDefault; + return $this->cacheByDefault; } /** @@ -215,7 +173,7 @@ public function getCacheByDefault() */ public function setCacheMethods(array $methods) { - $this->_cacheMethods = array_values(array_unique(array_map(function ($method) { + $this->cacheMethods = array_values(array_unique(array_map(function ($method) { $method = strtolower($method); switch ($method) { @@ -241,7 +199,7 @@ public function setCacheMethods(array $methods) */ public function getCacheMethods() { - return $this->_cacheMethods; + return $this->cacheMethods; } /** @@ -252,7 +210,7 @@ public function getCacheMethods() */ public function setNonCacheMethods(array $methods) { - $this->_nonCacheMethods = array_values(array_unique(array_map(function ($method) { + $this->nonCacheMethods = array_values(array_unique(array_map(function ($method) { $method = strtolower($method); switch ($method) { @@ -278,7 +236,7 @@ public function setNonCacheMethods(array $methods) */ public function getNonCacheMethods() { - return $this->_nonCacheMethods; + return $this->nonCacheMethods; } /** @@ -289,7 +247,7 @@ public function getNonCacheMethods() */ public function setCacheMagicProperties($flag) { - $this->_cacheMagicProperties = (bool)$flag; + $this->cacheMagicProperties = (bool)$flag; return $this; } @@ -300,7 +258,7 @@ public function setCacheMagicProperties($flag) */ public function getCacheMagicProperties() { - return $this->_cacheMagicProperties; + return $this->cacheMagicProperties; } /** diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index c358333c3..4a62e856e 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -15,14 +15,14 @@ class OutputCache extends AbstractPattern * * @var Zend\Cache\Storage\Adapter */ - protected $_storage; + protected $storage; /** * The key stack * * @var array */ - protected $_keyStack = array(); + protected $keyStack = array(); /** * Constructor @@ -58,7 +58,7 @@ public function getOptions() */ public function getStorage() { - return $this->_storage; + return $this->storage; } /** @@ -81,7 +81,7 @@ public function setStorage($storage) ); } - $this->_storage = $storage; + $this->storage = $storage; return $this; } @@ -122,7 +122,7 @@ public function start($key, array $options = array()) ob_start(); ob_implicit_flush(false); - $this->_keyStack[] = $key; + $this->keyStack[] = $key; return false; } @@ -140,7 +140,7 @@ public function start($key, array $options = array()) */ public function end(array $options = array()) { - $key = array_pop($this->_keyStack); + $key = array_pop($this->keyStack); if ($key === null) { throw new RuntimeException('use of end() without a start()'); } From 2ddd3444664f069b5b99d52ae44d8626ae7ad01a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 08:07:50 +0100 Subject: [PATCH 125/311] simplified Utils::bytesFromString --- src/Utils.php | 56 +++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/src/Utils.php b/src/Utils.php index 3499fa487..8257eaca6 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -203,37 +203,37 @@ static public function getHashAlgos() */ static protected function bytesFromString($memStr) { - if (preg_match('/\s*([\-\+]?\d+)\s*(\w*)\s*/', $memStr, $matches)) { - $value = (float)$matches[1]; - $unit = strtolower($matches[2]); - - switch ($unit) { - case '': - case 'b': - break; - - case 'k': - case 'kb': - $value*= 1024; - break; - - case 'm': - case 'mb': - $value*= 1048576; // 1024 * 1024 - break; - - case 'g': - case 'gb': - $value*= 1073741824; // 1024 * 1024 * 1024 - break; - - default: - throw new RuntimeException("Unknown unit '{$unit}'"); - } - } else { + if (!preg_match('/\s*([\-\+]?\d+)\s*(\w*)\s*/', $memStr, $matches)) { throw new RuntimeException("Can't detect bytes of string '{$memStr}'"); } + $value = (float)$matches[1]; + $unit = strtolower($matches[2]); + + switch ($unit) { + case 'g': + case 'gb': + $value*= 1024; + // Break intentionally omitted + + case 'm': + case 'mb': + $value*= 1024; + // Break intentionally omitted + + case 'k': + case 'kb': + $value*= 1024; + // Break intentionally omitted + + case '': + case 'b': + break; + + default: + throw new RuntimeException("Unknown unit '{$unit}'"); + } + return $value; } From 7f16eef7f608bc7b4b3264425180ef82ace17957 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 09:12:57 +0100 Subject: [PATCH 126/311] cleanup memory adapter: - removed underscores of private/protected members - removed unused protected method "_info" - phpdoc --- src/Storage/Adapter/Memory.php | 609 ++++++++++++++++++++++++++------- 1 file changed, 492 insertions(+), 117 deletions(-) diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 1bad31ead..2f7ce1b69 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -1,7 +1,6 @@ optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return mixed Value on success and false on failure + * @throws Zend\Cache\Exception + * + * @triggers getItem.pre(PreEvent) + * @triggers getItem.post(PostEvent) + * @triggers getItem.exception(ExceptionEvent) + */ public function getItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -51,9 +70,9 @@ public function getItem($key, array $options = array()) } $ns = $options['namespace']; - $exist = isset($this->_data[$ns][$key]); + $exist = isset($this->data[$ns][$key]); if ($exist) { - if ($options['ttl'] && microtime(true) >= ($this->_data[$ns][$key][1] + $options['ttl']) ) { + if ($options['ttl'] && microtime(true) >= ($this->data[$ns][$key][1] + $options['ttl']) ) { $exist = false; } } @@ -64,9 +83,9 @@ public function getItem($key, array $options = array()) } $result = false; } else { - $result = $this->_data[$ns][$key][0]; + $result = $this->data[$ns][$key][0]; if (array_key_exists('token', $options)) { - $options['token'] = $this->_data[$ns][$key][0]; + $options['token'] = $this->data[$ns][$key][0]; } } @@ -76,6 +95,24 @@ public function getItem($key, array $options = array()) } } + /** + * Get multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return array Assoziative array of existing keys and values or false on failure + * @throws Zend\Cache\Exception + * + * @triggers getItems.pre(PreEvent) + * @triggers getItems.post(PostEvent) + * @triggers getItems.exception(ExceptionEvent) + */ public function getItems(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -95,15 +132,15 @@ public function getItems(array $keys, array $options = array()) } $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { + if (!isset($this->data[$ns])) { $result = array(); } else { - $data = &$this->_data[$ns]; + $data = &$this->data[$ns]; $keyValuePairs = array(); foreach ($keys as $key) { if (isset($data[$key])) { - if (!$options['ttl'] || microtime(true) < ($this->_data[$ns][$key][1] + $options['ttl']) ) { + if (!$options['ttl'] || microtime(true) < ($this->data[$ns][$key][1] + $options['ttl']) ) { $keyValuePairs[$key] = $data[$key][0]; } } @@ -118,6 +155,24 @@ public function getItems(array $keys, array $options = array()) } } + /** + * Test if an item exists. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers hasItem.pre(PreEvent) + * @triggers hasItem.post(PostEvent) + * @triggers hasItem.exception(ExceptionEvent) + */ public function hasItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -137,7 +192,7 @@ public function hasItem($key, array $options = array()) return $eventRs->last(); } - $result = $this->_exists($key, $options); + $result = $this->checkItem($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { @@ -145,6 +200,26 @@ public function hasItem($key, array $options = array()) } } + /** + * Get metadata of an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return array|boolean Metadata or false on failure + * @throws Zend\Cache\Exception + * + * @triggers getMetadata.pre(PreEvent) + * @triggers getMetadata.post(PostEvent) + * @triggers getMetadata.exception(ExceptionEvent) + */ public function getMetadata($key, array $options = array()) { if (!$this->getReadable()) { @@ -164,7 +239,7 @@ public function getMetadata($key, array $options = array()) return $eventRs->last(); } - if (!$this->_exists($key, $options)) { + if (!$this->checkItem($key, $options)) { if (!$options['ignore_missing_items']) { throw new ItemNotFoundException( "Key '{$key}' not found on namespace '{$options['namespace']}'" @@ -174,8 +249,8 @@ public function getMetadata($key, array $options = array()) } else { $ns = $options['namespace']; $result = array( - 'mtime' => $this->_data[$ns][$key][1], - 'tags' => $this->_data[$ns][$key][2], + 'mtime' => $this->data[$ns][$key][1], + 'tags' => $this->data[$ns][$key][2], ); } @@ -187,6 +262,25 @@ public function getMetadata($key, array $options = array()) /* writing */ + /** + * Store an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers setItem.pre(PreEvent) + * @triggers setItem.post(PostEvent) + * @triggers setItem.exception(ExceptionEvent) + */ public function setItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -208,7 +302,7 @@ public function setItem($key, $value, array $options = array()) } $ns = $options['namespace']; - $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); + $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -217,6 +311,24 @@ public function setItem($key, $value, array $options = array()) } } + /** + * Store multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers setItems.pre(PreEvent) + * @triggers setItems.post(PostEvent) + * @triggers setItems.exception(ExceptionEvent) + */ public function setItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -236,11 +348,11 @@ public function setItems(array $keyValuePairs, array $options = array()) } $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { - $this->_data[$ns] = array(); + if (!isset($this->data[$ns])) { + $this->data[$ns] = array(); } - $data = & $this->_data[$ns]; + $data = & $this->data[$ns]; foreach ($keyValuePairs as $key => $value) { $data[$key] = array($value, microtime(true), $options['tags']); } @@ -252,6 +364,25 @@ public function setItems(array $keyValuePairs, array $options = array()) } } + /** + * Add an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers addItem.pre(PreEvent) + * @triggers addItem.post(PostEvent) + * @triggers addItem.exception(ExceptionEvent) + */ public function addItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -273,10 +404,10 @@ public function addItem($key, $value, array $options = array()) } $ns = $options['namespace']; - if (isset($this->_data[$ns][$key])) { + if (isset($this->data[$ns][$key])) { throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); } - $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); + $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -285,6 +416,24 @@ public function addItem($key, $value, array $options = array()) } } + /** + * Add multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers addItems.pre(PreEvent) + * @triggers addItems.post(PostEvent) + * @triggers addItems.exception(ExceptionEvent) + */ public function addItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -304,11 +453,11 @@ public function addItems(array $keyValuePairs, array $options = array()) } $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { - $this->_data[$ns] = array(); + if (!isset($this->data[$ns])) { + $this->data[$ns] = array(); } - $data = & $this->_data[$ns]; + $data = & $this->data[$ns]; foreach ($keyValuePairs as $key => $value) { if (isset($data[$key])) { throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); @@ -323,6 +472,25 @@ public function addItems(array $keyValuePairs, array $options = array()) } } + /** + * Replace an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers replaceItem.pre(PreEvent) + * @triggers replaceItem.post(PostEvent) + * @triggers replaceItem.exception(ExceptionEvent) + */ public function replaceItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -344,10 +512,10 @@ public function replaceItem($key, $value, array $options = array()) } $ns = $options['namespace']; - if (!isset($this->_data[$ns][$key])) { + if (!isset($this->data[$ns][$key])) { throw new ItemNotFoundException("Key '{$key}' doen't exists within namespace '$ns'"); } - $this->_data[$ns][$key] = array($value, microtime(true), $options['tags']); + $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -356,6 +524,24 @@ public function replaceItem($key, $value, array $options = array()) } } + /** + * Replace multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers replaceItems.pre(PreEvent) + * @triggers replaceItems.post(PostEvent) + * @triggers replaceItems.exception(ExceptionEvent) + */ public function replaceItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -375,11 +561,11 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } $ns = $options['namespace']; - if (!isset($this->_data[$ns])) { + if (!isset($this->data[$ns])) { throw new ItemNotFoundException("Namespace '$ns' doesn't exist"); } - $data = & $this->_data[$ns]; + $data = & $this->data[$ns]; foreach ($keyValuePairs as $key => $value) { if (!isset($data[$key])) { throw new ItemNotFoundException( @@ -396,6 +582,24 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } } + /** + * Reset lifetime of an item + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers touchItem.pre(PreEvent) + * @triggers touchItem.post(PostEvent) + * @triggers touchItem.exception(ExceptionEvent) + */ public function touchItem($key, array $options = array()) { if (!$this->getWritable()) { @@ -416,9 +620,9 @@ public function touchItem($key, array $options = array()) } $ns = $options['namespace']; - if (isset($this->_data[$ns][$key])) { + if (isset($this->data[$ns][$key])) { // update mtime - $this->_data[$ns][$key][1] = microtime(true); + $this->data[$ns][$key][1] = microtime(true); } else { if (!$options['ignore_missing_items']) { throw new ItemNotFoundException( @@ -427,7 +631,7 @@ public function touchItem($key, array $options = array()) } // add an empty item - $this->_data[$ns][$key] = array('', microtime(true), null); + $this->data[$ns][$key] = array('', microtime(true), null); } $result = true; @@ -437,6 +641,24 @@ public function touchItem($key, array $options = array()) } } + /** + * Remove an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers removeItem.pre(PreEvent) + * @triggers removeItem.post(PostEvent) + * @triggers removeItem.exception(ExceptionEvent) + */ public function removeItem($key, array $options = array()) { if (!$this->getWritable()) { @@ -457,12 +679,12 @@ public function removeItem($key, array $options = array()) } $ns = $options['namespace']; - if (isset($this->_data[$ns][$key])) { - unset($this->_data[$ns][$key]); + if (isset($this->data[$ns][$key])) { + unset($this->data[$ns][$key]); // remove empty namespace - if (!$this->_data[$ns]) { - unset($this->_data[$ns]); + if (!$this->data[$ns]) { + unset($this->data[$ns]); } } else { @@ -478,6 +700,24 @@ public function removeItem($key, array $options = array()) } } + /** + * Remove multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * + * @triggers removeItems.pre(PreEvent) + * @triggers removeItems.post(PostEvent) + * @triggers removeItems.exception(ExceptionEvent) + */ public function removeItems(array $keys, array $options = array()) { if (!$this->getWritable()) { @@ -498,11 +738,11 @@ public function removeItems(array $keys, array $options = array()) $ns = $options['namespace']; if ($options['ignore_missing_items'] === false) { - if (!isset($this->_data[$ns])) { + if (!isset($this->data[$ns])) { throw new ItemNotFoundException("Namespace '{$ns}' is empty"); } - $data = &$this->_data[$ns]; + $data = &$this->data[$ns]; $missingItems = null; foreach ($keys as $key) { @@ -518,15 +758,15 @@ public function removeItems(array $keys, array $options = array()) "Keys '" . implode("','", $missingItems) . "' not found on namespace '{$ns}'" ); } - } elseif (isset($this->_data[$ns])) { - $data = & $this->_data[$ns]; + } elseif (isset($this->data[$ns])) { + $data = & $this->data[$ns]; foreach ($keys as $key) { unset($data[$key]); } // remove empty namespace if (!$data) { - unset($this->_data[$ns]); + unset($this->data[$ns]); } } @@ -537,6 +777,25 @@ public function removeItems(array $keys, array $options = array()) } } + /** + * Increment an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param int $value + * @param array $options + * @return int|boolean The new value of false on failure + * @throws Zend\Cache\Exception + * + * @triggers incrementItem.pre(PreEvent) + * @triggers incrementItem.post(PostEvent) + * @triggers incrementItem.exception(ExceptionEvent) + */ public function incrementItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -559,7 +818,7 @@ public function incrementItem($key, $value, array $options = array()) } $ns = $options['namespace']; - $data = & $this->_data[$ns]; + $data = & $this->data[$ns]; if (isset($data[$key])) { $data[$key][0]+= $value; $data[$key][1] = microtime(true); @@ -582,6 +841,25 @@ public function incrementItem($key, $value, array $options = array()) } } + /** + * Decrement an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param int $value + * @param array $options + * @return int|boolean The new value or false or failure + * @throws Zend\Cache\Exception + * + * @triggers decrementItem.pre(PreEvent) + * @triggers decrementItem.post(PostEvent) + * @triggers decrementItem.exception(ExceptionEvent) + */ public function decrementItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -604,7 +882,7 @@ public function decrementItem($key, $value, array $options = array()) } $ns = $options['namespace']; - $data = & $this->_data[$ns]; + $data = & $this->data[$ns]; if (isset($data[$key])) { $data[$key][0]-= $value; $data[$key][1] = microtime(true); @@ -629,6 +907,29 @@ public function decrementItem($key, $value, array $options = array()) /* non-blocking */ + /** + * Find items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * @see fetch() + * @see fetchAll() + * + * @triggers find.pre(PreEvent) + * @triggers find.post(PostEvent) + * @triggers find.exception(ExceptionEvent) + */ public function find($mode = self::MATCH_ACTIVE, array $options=array()) { if (!$this->getReadable()) { @@ -654,20 +955,20 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) $tags = & $options['tags']; $emptyTags = $keys = array(); - foreach ($this->_data[ $options['namespace'] ] as $key => &$item) { + foreach ($this->data[ $options['namespace'] ] as $key => &$item) { // compare expired / active if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { // if MATCH_EXPIRED -> filter active items if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($this->_exists($key, $options)) { + if ($this->checkItem($key, $options)) { continue; } // if MATCH_ACTIVE -> filter expired items } else { - if (!$this->_exists($key, $options)) { + if (!$this->checkItem($key, $options)) { continue; } } @@ -710,6 +1011,17 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) } } + /** + * Fetches the next item from result set + * + * @return array|boolean The next item or false + * @throws Zend\Cache\Exception + * @see fetchAll() + * + * @triggers fetch.pre(PreEvent) + * @triggers fetch.post(PostEvent) + * @triggers fetch.exception(ExceptionEvent) + */ public function fetch() { if (!$this->_stmtActive) { @@ -731,10 +1043,10 @@ public function fetch() if ($key === null) { break; } - if (!$this->_exists($key, $options)) { + if (!$this->checkItem($key, $options)) { continue; } - $ref = & $this->_data[ $options['namespace'] ][$key]; + $ref = & $this->data[ $options['namespace'] ][$key]; break; } while (true); @@ -774,6 +1086,26 @@ public function fetch() /* cleaning */ + /** + * Clear items off all namespaces. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * @see clearByNamespace() + * + * @triggers clear.pre(PreEvent) + * @triggers clear.post(PostEvent) + * @triggers clear.exception(ExceptionEvent) + */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { if (!$this->getWritable()) { @@ -794,10 +1126,10 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { - $this->_data = array(); + $this->data = array(); } else { - foreach ($this->_data as &$data) { - $this->_clearNamespacedDataArray($data, $mode, $options); + foreach ($this->data as &$data) { + $this->clearNamespacedDataArray($data, $mode, $options); } } @@ -808,6 +1140,28 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } } + /** + * Clear items by namespace. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * @see clear() + * + * @triggers clearByNamespace.pre(PreEvent) + * @triggers clearByNamespace.post(PostEvent) + * @triggers clearByNamespace.exception(ExceptionEvent) + */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { if (!$this->getWritable()) { @@ -827,11 +1181,11 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a return $eventRs->last(); } - if (isset($this->_data[ $options['namespace'] ])) { + if (isset($this->data[ $options['namespace'] ])) { if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { - unset($this->_data[ $options['namespace'] ]); + unset($this->data[ $options['namespace'] ]); } else { - $this->_clearNamespacedDataArray($this->_data[ $options['namespace'] ], $mode, $options); + $this->clearNamespacedDataArray($this->data[ $options['namespace'] ], $mode, $options); } } @@ -842,56 +1196,17 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a } } - protected function _clearNamespacedDataArray(array &$data, $mode, &$options) - { - $tags = &$options['tags']; - $time = microtime(true); - $ttl = $options['ttl']; - - $emptyTags = $keys = array(); - foreach ($data as $key => &$item) { - - // compare expired / active - if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { - - // if MATCH_EXPIRED mode selected don't match active items - if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($ttl == 0 || $time <= ($item[1]+$ttl) ) { - continue; - } - - // if MATCH_ACTIVE mode selected don't match expired items - } elseif ($ttl > 0 && $time >= ($item[1]+$ttl)) { - continue; - } - } - - // compare tags - if ($tags !== null) { - $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; - - if ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); - } elseif ( ($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - $matched = (count(array_diff($tags, $tagsStored)) == 0); - } - - // negate - if ( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - $matched = !$matched; - } - - if (!$matched) { - continue; - } - } - - unset($data[$key]); - } - } - /* status */ + /** + * Get capabilities + * + * @return Capabilities + * + * @triggers getCapabilities.pre(PreEvent) + * @triggers getCapabilities.post(PostEvent) + * @triggers getCapabilities.exception(ExceptionEvent) + */ public function getCapabilities() { $args = new \ArrayObject(); @@ -936,6 +1251,17 @@ public function getCapabilities() return $this->triggerPost(__FUNCTION__, $args, $this->_capabilities); } + /** + * Get storage capacity. + * + * @param array $options + * @return array|boolean Capacity as array or false on failure + * @throws Zend\Cache\Exception + * + * @triggers getCapacity.pre(PreEvent) + * @triggers getCapacity.post(PostEvent) + * @triggers getCapacity.exception(ExceptionEvent) + */ public function getCapacity(array $options = array()) { $args = new \ArrayObject(array( @@ -954,42 +1280,91 @@ public function getCapacity(array $options = array()) /* internal */ - protected function _exists($key, array &$options) + /** + * Internal method to check if an key exists + * and if it isn't expired. + * + * Options: + * - namespace required + * - ttl required + * + * @param string $key + * @param array $options + */ + protected function checkItem($key, array &$options) { $ns = $options['namespace']; - if (!isset($this->_data[$ns][$key])) { + if (!isset($this->data[$ns][$key])) { return false; } // check if expired - if ($options['ttl'] && microtime(true) >= ($this->_data[$ns][$key][1] + $options['ttl']) ) { + if ($options['ttl'] && microtime(true) >= ($this->data[$ns][$key][1] + $options['ttl']) ) { return false; } return true; } - public function _info($key, array &$options = array()) + /** + * Internal method to run a clear command + * on a given data array which doesn't contain namespaces. + * + * Options: + * - ttl required + * - tags required + * + * @param array $data + * @param int $mode + * @param array $options + */ + protected function clearNamespacedDataArray(array &$data, $mode, array &$options) { - if (!$this->_exists($key, $options)) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( - "Key '{$key}' not found on namespace '{$options['namespace']}'" - ); + $tags = &$options['tags']; + $time = microtime(true); + $ttl = $options['ttl']; + $emptyTags = $keys = array(); + foreach ($data as $key => &$item) { + + // compare expired / active + if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { + + // if MATCH_EXPIRED mode selected don't match active items + if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { + if ($ttl == 0 || $time <= ($item[1]+$ttl) ) { + continue; + } + + // if MATCH_ACTIVE mode selected don't match expired items + } elseif ($ttl > 0 && $time >= ($item[1]+$ttl)) { + continue; + } } - return false; - } - $ns = $options['namespace']; - $mtime = $this->_data[$ns][$key][1]; + // compare tags + if ($tags !== null) { + $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; + + if ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { + $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); + } elseif ( ($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { + $matched = (count(array_diff($tags, $tagsStored)) == 0); + } - return array( - 'mtime' => $mtime, - 'ttl' => $mtime - microtime(true) + $options['ttl'], - 'tags' => $this->_data[$ns][$key][2] - ); + // negate + if ( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { + $matched = !$matched; + } + + if (!$matched) { + continue; + } + } + + unset($data[$key]); + } } } From 7c2a1a7c389a3600212b1bbdedf04c7a579e0b28 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 17:02:16 +0100 Subject: [PATCH 127/311] removed underscore of private/protected membery of storage adapters --- src/Storage/Adapter/AbstractAdapter.php | 133 ++++---- src/Storage/Adapter/Filesystem.php | 430 ++++++++++++------------ src/Storage/Adapter/Memory.php | 92 ++--- 3 files changed, 330 insertions(+), 325 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 011f4e5ab..bcff231d6 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -23,84 +23,84 @@ abstract class AbstractAdapter implements Adapter * * @var null|EventManager */ - protected $_events = null; + protected $events = null; /** * The plugin registry * * @var array Array of registered plugins */ - protected $_pluginRegistry = array(); + protected $pluginRegistry = array(); /** * Capabilities of this adapter * * @var null|Capabilities */ - protected $_capabilities = null; + protected $capabilities = null; /** * Marker to change capabilities * * @var null|object */ - protected $_capabilityMarker; + protected $capabilityMarker; /** * Writable option * * @var boolean */ - protected $_writable = true; + protected $writable = true; /** * Readable option * * @var boolean */ - protected $_readable = true; + protected $readable = true; /** * TTL option * * @var int|float 0 means infinite or maximum of adapter */ - protected $_ttl = 0; + protected $ttl = 0; /** * Namespace option * * @var string */ - protected $_namespace = 'zfcache'; + protected $namespace = 'zfcache'; /** * Validate namespace against pattern * * @var string */ - protected $_namespacePattern = ''; + protected $namespacePattern = ''; /** * Validate key against pattern * * @var string */ - protected $_keyPattern = ''; + protected $keyPattern = ''; /** * Ignore missing items * * @var boolean */ - protected $_ignoreMissingItems = true; + protected $ignoreMissingItems = true; /** * Statement */ - protected $_stmtActive = false; - protected $_stmtKeys = null; - protected $_stmtOptions = null; + protected $stmtActive = false; + protected $stmtKeys = null; + protected $stmtOptions = null; /** * Constructor @@ -180,7 +180,7 @@ public function getOptions() */ public function setWritable($flag) { - $this->_writable = (bool)$flag; + $this->writable = (bool)$flag; return $this; } @@ -191,7 +191,7 @@ public function setWritable($flag) */ public function getWritable() { - return $this->_writable; + return $this->writable; } /** @@ -202,7 +202,7 @@ public function getWritable() */ public function setReadable($flag) { - $this->_readable = (bool)$flag; + $this->readable = (bool)$flag; return $this; } @@ -213,7 +213,7 @@ public function setReadable($flag) */ public function getReadable() { - return $this->_readable; + return $this->readable; } /** @@ -254,8 +254,8 @@ public function getCaching() */ public function setTtl($ttl) { - $this->_normalizeTtl($ttl); - $this->_ttl = $ttl; + $this->normalizeTtl($ttl); + $this->ttl = $ttl; return $this; } @@ -266,7 +266,7 @@ public function setTtl($ttl) */ public function getTtl() { - return $this->_ttl; + return $this->ttl; } /** @@ -288,7 +288,7 @@ public function setNamespace($namespace) "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" ); } - $this->_namespace = (string)$namespace; + $this->namespace = (string)$namespace; return $this; } @@ -299,7 +299,7 @@ public function setNamespace($namespace) */ public function getNamespace() { - return $this->_namespace; + return $this->namespace; } /** @@ -311,7 +311,7 @@ public function getNamespace() public function setNamespacePattern($pattern) { if (($pattern = (string)$pattern) === '') { - $this->_namespacePattern = ''; + $this->namespacePattern = ''; } else { // validate pattern if (@preg_match($pattern, '') === false) { @@ -326,7 +326,7 @@ public function setNamespacePattern($pattern) ); } - $this->_namespacePattern = $pattern; + $this->namespacePattern = $pattern; } return $this; @@ -339,7 +339,7 @@ public function setNamespacePattern($pattern) */ public function getNamespacePattern() { - return $this->_namespacePattern; + return $this->namespacePattern; } /** @@ -351,7 +351,7 @@ public function getNamespacePattern() public function setKeyPattern($pattern) { if (($pattern = (string)$pattern) === '') { - $this->_keyPattern = ''; + $this->keyPattern = ''; } else { // validate pattern if (@preg_match($pattern, '') === false) { @@ -359,7 +359,7 @@ public function setKeyPattern($pattern) throw new InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); } - $this->_keyPattern = $pattern; + $this->keyPattern = $pattern; } return $this; @@ -372,7 +372,7 @@ public function setKeyPattern($pattern) */ public function getKeyPattern() { - return $this->_keyPattern; + return $this->keyPattern; } /** @@ -393,7 +393,7 @@ public function getKeyPattern() */ public function setIgnoreMissingItems($flag) { - $this->_ignoreMissingItems = (bool)$flag; + $this->ignoreMissingItems = (bool)$flag; return $this; } @@ -405,7 +405,7 @@ public function setIgnoreMissingItems($flag) */ public function getIgnoreMissingItems() { - return $this->_ignoreMissingItems; + return $this->ignoreMissingItems; } /* Event/Plugin handling */ @@ -417,10 +417,10 @@ public function getIgnoreMissingItems() */ public function events() { - if ($this->_events === null) { - $this->_events = new EventManager(array(__CLASS__, get_class($this))); + if ($this->events === null) { + $this->events = new EventManager(array(__CLASS__, get_class($this))); } - return $this->_events; + return $this->events; } /** @@ -490,7 +490,7 @@ protected function triggerException($eventName, \ArrayObject $args, \Exception $ */ public function hasPlugin(Plugin $plugin) { - return in_array($plugin, $this->_pluginRegistry, true); + return in_array($plugin, $this->pluginRegistry, true); } /** @@ -502,12 +502,12 @@ public function hasPlugin(Plugin $plugin) */ public function addPlugin(Plugin $plugin) { - if (in_array($plugin, $this->_pluginRegistry, true)) { + if (in_array($plugin, $this->pluginRegistry, true)) { throw new LogicException('Plugin already registered'); } $plugin->attach($this->events()); - $this->_pluginRegistry[] = $plugin; + $this->pluginRegistry[] = $plugin; return $this; } @@ -521,13 +521,13 @@ public function addPlugin(Plugin $plugin) */ public function removePlugin(Plugin $plugin) { - $pluginRegistryIndex = array_search($plugin, $this->_pluginRegistry, true); + $pluginRegistryIndex = array_search($plugin, $this->pluginRegistry, true); if ($pluginRegistryIndex === false) { throw new LogicException('Plugin not registered'); } $plugin->detach($this->events()); - unset($this->_pluginRegistry[$pluginRegistryIndex]); + unset($this->pluginRegistry[$pluginRegistryIndex]); return $this; } @@ -539,7 +539,7 @@ public function removePlugin(Plugin $plugin) */ public function getPlugins() { - return $this->_pluginRegistry; + return $this->pluginRegistry; } /* reading */ @@ -798,7 +798,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) public function getDelayed(array $keys, array $options = array()) { - if ($this->_stmtActive) { + if ($this->stmtActive) { throw new RuntimeException('Statement already in use'); } @@ -809,16 +809,15 @@ public function getDelayed(array $keys, array $options = array()) return true; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); if (!isset($options['select'])) { $options['select'] = array('key', 'value'); } - $this->_stmtOptions = array_merge($this->getOptions(), $options); - - $this->_stmtKeys = $keys; - $this->_stmtActive = true; + $this->stmtOptions = array_merge($this->getOptions(), $options); + $this->stmtKeys = $keys; + $this->stmtActive = true; if (isset($options['callback'])) { $callback = $options['callback']; @@ -841,14 +840,14 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) public function fetch() { - if (!$this->_stmtActive) { + if (!$this->stmtActive) { return false; } - $options = $this->_stmtOptions; + $options = $this->stmtOptions; do { - $key = array_shift($this->_stmtKeys); + $key = array_shift($this->stmtKeys); if ($key === null) { break; } @@ -890,9 +889,9 @@ public function fetch() } while (true); // clear statement - $this->_stmtActive = false; - $this->_stmtKeys = null; - $this->_stmtOptions = null; + $this->stmtActive = false; + $this->stmtKeys = null; + $this->stmtOptions = null; return false; } @@ -936,11 +935,11 @@ public function optimize(array $options = array()) */ public function getCapabilities() { - if ($this->_capabilities === null) { - $this->_capabilityMarker = new \stdClass(); - $this->_capabilities = new Capabilities($this->_capabilityMarker); + if ($this->capabilities === null) { + $this->capabilityMarker = new \stdClass(); + $this->capabilities = new Capabilities($this->capabilityMarker); } - return $this->_capabilities; + return $this->capabilities; } /* internal */ @@ -950,18 +949,18 @@ public function getCapabilities() * * @param array $options */ - protected function _normalizeOptions(array &$options) + protected function normalizeOptions(array &$options) { // ttl if (isset($options['ttl'])) { - $this->_normalizeTtl($options['ttl']); + $this->normalizeTtl($options['ttl']); } else { $options['ttl'] = $this->getTtl(); } // namespace if (isset($options['namespace'])) { - $this->_normalizeNamespace($options['namespace']); + $this->normalizeNamespace($options['namespace']); } else { $options['namespace'] = $this->getNamespace(); } @@ -975,14 +974,14 @@ protected function _normalizeOptions(array &$options) // tags if (isset($options['tags'])) { - $this->_normalizeTags($options['tags']); + $this->normalizeTags($options['tags']); } else { $options['tags'] = null; } // select if (isset($options['select'])) { - $this->_normalizeSelect($options['select']); + $this->normalizeSelect($options['select']); } else { $options['select'] = array('key', 'value'); } @@ -994,7 +993,7 @@ protected function _normalizeOptions(array &$options) * @param int|float $ttl * @throws InvalidArgumentException */ - protected function _normalizeTtl(&$ttl) + protected function normalizeTtl(&$ttl) { if (!is_int($ttl)) { $ttl = (float)$ttl; @@ -1016,7 +1015,7 @@ protected function _normalizeTtl(&$ttl) * @param string $namespace * @throws InvalidArgumentException */ - protected function _normalizeNamespace(&$namespace) + protected function normalizeNamespace(&$namespace) { $namespace = (string)$namespace; @@ -1035,7 +1034,7 @@ protected function _normalizeNamespace(&$namespace) * @param array $tags * @throws Zend\Cache\InvalidArgumentException */ - protected function _normalizeTags(&$tags) + protected function normalizeTags(&$tags) { if (!is_array($tags)) { throw new InvalidArgumentException('Tags have to be an array'); @@ -1056,7 +1055,7 @@ protected function _normalizeTags(&$tags) * * @param string[]|string */ - protected function _normalizeSelect(&$select) + protected function normalizeSelect(&$select) { if (!is_array($select)) { $select = array((string)$select); @@ -1071,7 +1070,7 @@ protected function _normalizeSelect(&$select) * @param int $mode Matching mode to normalize * @param int $default Default matching mode */ - protected function _normalizeMatchingMode(&$mode, $default, array &$normalizedOptions) + protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOptions) { $mode = (int)$mode; if ( ($mode & self::MATCH_EXPIRED) != self::MATCH_EXPIRED @@ -1089,7 +1088,7 @@ protected function _normalizeMatchingMode(&$mode, $default, array &$normalizedOp * @return string * @throws InvalidArgumentException */ - protected function _key($key) + protected function key($key) { if (($p = $this->getKeyPattern()) && !preg_match($p, $key)) { throw new InvalidArgumentException("The key '{$key}' doesn't match agains pattern '{$p}'"); diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 978cef06d..69ff569ec 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -18,41 +18,41 @@ class Filesystem extends AbstractAdapter * * @var string */ - protected $_namespacePattern = '/^[a-z0-9_\+\-]*$/Di'; + protected $namespacePattern = '/^[a-z0-9_\+\-]*$/Di'; /** * Namespace separator * * @var string */ - protected $_namespaceSeparator = '-'; + protected $namespaceSeparator = '-'; /** * Overwrite default key pattern */ - protected $_keyPattern = '/^[a-z0-9_\+\-]*$/Di'; + protected $keyPattern = '/^[a-z0-9_\+\-]*$/Di'; /** - * Directory where to store cache files + * Directory to store cache files * * @var null|string The cache directory * or NULL for the systems temporary directory */ - protected $_cacheDir = null; + protected $cacheDir = null; /** * Used umask on creating a cache file * * @var int */ - protected $_fileUmask = 0117; + protected $fileUmask = 0117; /** * Lock files on writing * * @var boolean */ - protected $_fileLocking = true; + protected $fileLocking = true; /** * Block writing files until writing by another process finished. @@ -62,35 +62,35 @@ class Filesystem extends AbstractAdapter * * @var boolean */ - protected $_fileBlocking = true; + protected $fileBlocking = true; /** * Used umask on creating a cache directory * * @var int */ - protected $_dirUmask = 0007; + protected $dirUmask = 0007; /** * How much sub-directaries should be created? * * @var int */ - protected $_dirLevel = 1; + protected $dirLevel = 1; /** * Don't get 'fileatime' as 'atime' on metadata * * @var boolean */ - protected $_noAtime = true; + protected $noAtime = true; /** * Don't get 'filectime' as 'ctime' on metadata * * @var boolean */ - protected $_noCtime = true; + protected $noCtime = true; /** * Read control enabled ? @@ -99,34 +99,34 @@ class Filesystem extends AbstractAdapter * * @var boolean */ - protected $_readControl = false; + protected $readControl = false; /** * The used hash algorithm if read control is enabled * * @var string */ - protected $_readControlAlgo = 'crc32'; + protected $readControlAlgo = 'crc32'; /** * Call clearstatcache enabled? * * @var boolean */ - protected $_clearStatCache = true; + protected $clearStatCache = true; /** * Statement */ - protected $_stmtGlob = null; - protected $_stmtMatch = null; + protected $stmtGlob = null; + protected $stmtMatch = null; /** * Buffer vars */ - protected $_lastInfoId = null; - protected $_lastInfoAll = null; - protected $_lastInfo = null; + protected $lastInfoId = null; + protected $lastInfoAll = null; + protected $lastInfo = null; /* configuration */ @@ -152,14 +152,14 @@ public function getOptions() public function setNamespaceSeparator($separator) { - $this->_namespaceSeparator = (string)$separator; - $this->_updateCapabilities(); + $this->namespaceSeparator = (string)$separator; + $this->updateCapabilities(); return $this; } public function getNamespaceSeparator() { - return $this->_namespaceSeparator; + return $this->namespaceSeparator; } public function setCacheDir($dir) @@ -182,17 +182,17 @@ public function setCacheDir($dir) $dir = rtrim(realpath($dir), \DIRECTORY_SEPARATOR); } - $this->_cacheDir = $dir; + $this->cacheDir = $dir; return $this; } public function getCacheDir() { - if ($this->_cacheDir === null) { + if ($this->cacheDir === null) { $this->setCacheDir(sys_get_temp_dir()); } - return $this->_cacheDir; + return $this->cacheDir; } public function setFilePerm($perm) @@ -231,59 +231,59 @@ public function setFileUmask($umask) ); } - $this->_fileUmask = $umask; + $this->fileUmask = $umask; return $this; } public function getFileUmask() { - return $this->_fileUmask; + return $this->fileUmask; } public function setFileLocking($flag) { - $this->_fileLocking = (bool)$flag; + $this->fileLocking = (bool)$flag; return $this; } public function getFileLocking() { - return $this->_fileLocking; + return $this->fileLocking; } public function setFileBlocking($flag) { - $this->_fileBlocking = (bool)$flag; + $this->fileBlocking = (bool)$flag; return $this; } public function getFileBlocking() { - return $this->_fileBlocking; + return $this->fileBlocking; } public function setNoAtime($flag) { - $this->_noAtime = (bool)$flag; - $this->_updateCapabilities(); + $this->noAtime = (bool)$flag; + $this->updateCapabilities(); return $this; } public function getNoAtime() { - return $this->_noAtime; + return $this->noAtime; } public function setNoCtime($flag) { - $this->_noCtime = (bool)$flag; - $this->_updateCapabilities(); + $this->noCtime = (bool)$flag; + $this->updateCapabilities(); return $this; } public function getNoCtime() { - return $this->_noCtime; + return $this->noCtime; } public function setDirPerm($perm) @@ -318,13 +318,13 @@ public function setDirUmask($umask) ); } - $this->_dirUmask = $umask; + $this->dirUmask = $umask; return $this; } public function getDirUmask() { - return $this->_dirUmask; + return $this->dirUmask; } public function setDirLevel($level) @@ -335,24 +335,24 @@ public function setDirLevel($level) "Directory level '{$level}' have to be between 0 and 16" ); } - $this->_dirLevel = $level; + $this->dirLevel = $level; return $this; } public function getDirLevel() { - return $this->_dirLevel; + return $this->dirLevel; } public function setReadControl($flag) { - $this->_readControl = (bool)$flag; + $this->readControl = (bool)$flag; return $this; } public function getReadControl() { - return $this->_readControl; + return $this->readControl; } public function setReadControlAlgo($algo) @@ -363,24 +363,24 @@ public function setReadControlAlgo($algo) throw new InvalidArgumentException("Unsupported hash algorithm '{$algo}"); } - $this->_readControlAlgo = $algo; + $this->readControlAlgo = $algo; return $this; } public function getReadControlAlgo() { - return $this->_readControlAlgo; + return $this->readControlAlgo; } public function setClearStatCache($flag) { - $this->_clearStatCache = (bool)$flag; + $this->clearStatCache = (bool)$flag; return $this; } public function getClearStatCache() { - return $this->_clearStatCache; + return $this->clearStatCache; } /* reading */ @@ -391,8 +391,8 @@ public function getItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -408,10 +408,10 @@ public function getItem($key, array $options = array()) clearstatcache(); } - $result = $this->_get($key, $options); + $result = $this->internalGetItem($key, $options); if (array_key_exists('token', $options)) { // use filemtime + filesize as CAS token - $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + $keyInfo = $this->getKeyInfo($key, $options['namespace']); $options['token'] = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); } @@ -427,7 +427,7 @@ public function getItems(array $keys, array $options = array()) return array(); } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); // don't throw ItemNotFoundException on getItems $options['ignore_missing_items'] = true; @@ -448,7 +448,7 @@ public function getItems(array $keys, array $options = array()) $result = array(); foreach ($keys as $key) { - if ( ($rs = $this->_get($key, $options)) !== false) { + if ( ($rs = $this->internalGetItem($key, $options)) !== false) { $result[$key] = $rs; } } @@ -465,8 +465,8 @@ public function hasItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -482,7 +482,7 @@ public function hasItem($key, array $options = array()) clearstatcache(); } - $result = $this->_exists($key, $options); + $result = $this->internalHasItem($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -495,7 +495,7 @@ public function hasItems(array $keys, array $options = array()) return array(); } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keys' => & $keys, 'options' => & $options @@ -513,7 +513,7 @@ public function hasItems(array $keys, array $options = array()) $result = array(); foreach ($keys as $key) { - if ( $this->_exists($key, $options) === true ) { + if ( $this->internalHasItem($key, $options) === true ) { $result[] = $key; } } @@ -530,8 +530,8 @@ public function getMetadata($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -548,11 +548,11 @@ public function getMetadata($key, array $options = array()) } $lastInfoId = $options['namespace'] . $this->getNamespaceSeparator() . $key; - if ($this->_lastInfoId == $lastInfoId && $this->_lastInfoAll) { - return $this->_lastInfoAll; + if ($this->lastInfoId == $lastInfoId && $this->lastInfoAll) { + return $this->lastInfoAll; } - $this->_lastInfoAll = $result = $this->_info($key, $options); + $this->lastInfoAll = $result = $this->internalGetMetadata($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { @@ -566,7 +566,7 @@ public function getMetadatas(array $keys, array $options = array()) return array(); } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); // don't throw ItemNotFoundException on getMetadatas $options['ignore_missing_items'] = true; @@ -587,8 +587,9 @@ public function getMetadatas(array $keys, array $options = array()) $result = array(); foreach ($keys as $key) { - if ( ($info = $this->_info($key, $options)) !== false ) { - $result[$key] = $info; + $meta = $this->internalGetMetadata($key, $options); + if ($meta !== false ) { + $result[$key] = $meta; } } @@ -606,8 +607,8 @@ public function setItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -624,7 +625,7 @@ public function setItem($key, $value, array $options = array()) clearstatcache(); } - $result = $this->_set($key, $value, $options); + $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -637,7 +638,7 @@ public function setItems(array $keyValuePairs, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options @@ -655,7 +656,7 @@ public function setItems(array $keyValuePairs, array $options = array()) $result = true; foreach ($keyValuePairs as $key => $value) { - $result = $this->_set($key, $value, $options) && $result; + $result = $this->internalSetItem($key, $value, $options) && $result; } return $this->triggerPost(__FUNCTION__, $args, $result); @@ -670,8 +671,8 @@ public function replaceItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -688,11 +689,11 @@ public function replaceItem($key, $value, array $options = array()) clearstatcache(); } - if ( !$this->_exists($key, $options) ) { + if ( !$this->internalHasItem($key, $options) ) { throw new ItemNotFoundException("Key '{$key}' doesn't exist"); } - $result = $this->_set($key, $value, $options); + $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -705,7 +706,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options @@ -723,10 +724,10 @@ public function replaceItems(array $keyValuePairs, array $options = array()) $result = true; foreach ($keyValuePairs as $key => $value) { - if ( !$this->_exists($key, $options) ) { + if ( !$this->internalHasItem($key, $options) ) { throw new ItemNotFoundException("Key '{$key}' doesn't exist"); } - $result = $this->_set($key, $value, $options) && $result; + $result = $this->internalSetItem($key, $value, $options) && $result; } return $this->triggerPost(__FUNCTION__, $args, $result); @@ -741,8 +742,8 @@ public function addItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -759,11 +760,11 @@ public function addItem($key, $value, array $options = array()) clearstatcache(); } - if ( $this->_exists($key, $options) ) { + if ( $this->internalHasItem($key, $options) ) { throw new RuntimeException("Key '{$key}' already exist"); } - $result = $this->_set($key, $value, $options); + $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -776,7 +777,7 @@ public function addItems(array $keyValuePairs, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options @@ -794,11 +795,11 @@ public function addItems(array $keyValuePairs, array $options = array()) $result = true; foreach ($keyValuePairs as $key => $value) { - if ( $this->_exists($key, $options) ) { + if ( $this->internalHasItem($key, $options) ) { throw new RuntimeException("Key '{$key}' already exist"); } - $result = $this->_set($key, $value, $options) && $result; + $result = $this->internalSetItem($key, $value, $options) && $result; } return $this->triggerPost(__FUNCTION__, $args, $result); @@ -813,8 +814,8 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'token' => & $token, 'key' => & $key, @@ -832,7 +833,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) clearstatcache(); } - if ( !($keyInfo = $this->_getKeyInfo($key, $options['namespace'])) ) { + if ( !($keyInfo = $this->getKeyInfo($key, $options['namespace'])) ) { if ($options['ignore_missing_items']) { $result = false; } else { @@ -844,7 +845,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) if ($token != $check) { $result = false; } else { - $result = $this->_set($key, $value, $options); + $result = $this->internalSetItem($key, $value, $options); } } @@ -860,8 +861,8 @@ public function touchItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -877,8 +878,8 @@ public function touchItem($key, array $options = array()) clearstatcache(); } - $this->_touch($key, $options); - $this->_lastInfoId = null; + $this->internalTouchItem($key, $options); + $this->lastInfoId = null; $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -893,7 +894,7 @@ public function touchItems(array $keys, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keys' => & $keys, 'options' => & $options @@ -906,9 +907,9 @@ public function touchItems(array $keys, array $options = array()) } foreach ($keys as $key) { - $this->_touch($key, $options); + $this->internalTouchItem($key, $options); } - $this->_lastInfoId = null; + $this->lastInfoId = null; $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -923,8 +924,8 @@ public function removeItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -937,7 +938,7 @@ public function removeItem($key, array $options = array()) } // unlink is not affected by clearstatcache - $this->_remove($key, $options); + $this->internalRemoveItem($key, $options); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -952,7 +953,7 @@ public function removeItems(array $keys, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keys' => & $keys, 'options' => & $options @@ -966,7 +967,7 @@ public function removeItems(array $keys, array $options = array()) // unlink is not affected by clearstatcache foreach ($keys as $key) { - $this->_remove($key, $options); + $this->internalRemoveItem($key, $options); } $result = true; @@ -980,7 +981,7 @@ public function removeItems(array $keys, array $options = array()) public function find($mode = self::MATCH_ACTIVE, array $options = array()) { - if ($this->_stmtActive) { + if ($this->stmtActive) { throw new RuntimeException('Statement already in use'); } @@ -988,8 +989,8 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) return false; } - $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); $options = array_merge($this->getOptions(), $options); $args = new \ArrayObject(array( 'mode' => & $mode, @@ -1013,10 +1014,10 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; $glob = new \GlobIterator($find); - $this->_stmtActive = true; - $this->_stmtGlob = $glob; - $this->_stmtMatch = $mode; - $this->_stmtOptions = $options; + $this->stmtActive = true; + $this->stmtGlob = $glob; + $this->stmtMatch = $mode; + $this->stmtOptions = $options; } catch (\Exception $e) { throw new RuntimeException('Instantiating glob iterator failed', 0, $e); } @@ -1030,7 +1031,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) public function fetch() { - if (!$this->_stmtActive) { + if (!$this->stmtActive) { return false; } @@ -1042,15 +1043,15 @@ public function fetch() return $eventRs->last(); } - if ($this->_stmtGlob !== null) { - $result = $this->_fetchByGlob(); + if ($this->stmtGlob !== null) { + $result = $this->fetchByGlob(); if ($result === false) { // clear statement - $this->_stmtActive = false; - $this->_stmtGlob = null; - $this->_stmtMatch = null; - $this->_stmtOptions = null; + $this->stmtActive = false; + $this->stmtGlob = null; + $this->stmtMatch = null; + $this->stmtOptions = null; } } else { $result = parent::fetch(); @@ -1066,8 +1067,8 @@ public function fetch() public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { - $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options @@ -1079,7 +1080,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) return $eventRs->last(); } - $result = $this->_clearByPrefix('', $mode, $options); + $result = $this->clearByPrefix('', $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1088,8 +1089,8 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { - $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options @@ -1102,7 +1103,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a } $prefix = $options['namespace'] . $this->getNamespaceSeparator(); - $result = $this->_clearByPrefix($prefix, $mode, $options); + $result = $this->clearByPrefix($prefix, $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1115,7 +1116,7 @@ public function optimize(array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'options' => & $options )); @@ -1128,7 +1129,7 @@ public function optimize(array $options = array()) if ( ($dirLevel = $this->getDirLevel()) ) { // removes only empty directories - $this->_rmDir($this->getCacheDir(), $options['namespace'] . $this->getNamespaceSeparator()); + $this->rmDir($this->getCacheDir(), $options['namespace'] . $this->getNamespaceSeparator()); } $result = true; @@ -1150,10 +1151,10 @@ public function getCapabilities() return $eventRs->last(); } - if ($this->_capabilities === null) { - $this->_capabilityMarker = new \stdClass(); - $this->_capabilities = new Capabilities( - $this->_capabilityMarker, + if ($this->capabilities === null) { + $this->capabilityMarker = new \stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, array( 'supportedDatatypes' => array( 'NULL' => 'string', @@ -1180,10 +1181,10 @@ public function getCapabilities() ); // set dynamic capibilities - $this->_updateCapabilities(); + $this->updateCapabilities(); } - $result = $this->_capabilities; + $result = $this->capabilities; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1209,16 +1210,16 @@ public function getCapacity(array $options = array()) /* internal */ - protected function _set($key, $value, array &$options) + protected function internalSetItem($key, $value, array &$options) { $oldUmask = null; $lastInfoId = $options['namespace'] . $this->getNamespaceSeparator() . $key; - if ($this->_lastInfoId == $lastInfoId) { - $filespec = $this->_lastInfo['filespec']; + if ($this->lastInfoId == $lastInfoId) { + $filespec = $this->lastInfo['filespec']; // if lastKeyInfo is available I'm sure that the cache directory exist } else { - $filespec = $this->_getKeyFileSpec($key, $options['namespace']); + $filespec = $this->getFileSpec($key, $options['namespace']); if ($this->getDirLevel() > 0) { $path = dirname($filespec); if (!file_exists($path)) { @@ -1252,18 +1253,18 @@ protected function _set($key, $value, array &$options) $oldUmask = umask($this->getFileUmask()); } - $ret = $this->_putFileContent($filespec . '.dat', $value); + $ret = $this->putFileContent($filespec . '.dat', $value); if ($ret && $info) { // Don't throw exception if writing of info file failed // -> only return false try { - $ret = $this->_putFileContent($filespec . '.ifo', serialize($info)); + $ret = $this->putFileContent($filespec . '.ifo', serialize($info)); } catch (\Exception $e) { $ret = false; } } - $this->_lastInfoId = null; + $this->lastInfoId = null; // reset file_umask umask($oldUmask); @@ -1277,40 +1278,44 @@ protected function _set($key, $value, array &$options) } } - protected function _remove($key, array &$options) + protected function internalRemoveItem($key, array &$options) { - $filespec = $this->_getKeyFileSpec($key, $options['namespace']); + $filespec = $this->getFileSpec($key, $options['namespace']); if (!$options['ignore_missing_items'] && !file_exists($filespec . '.dat')) { throw new ItemNotFoundException("Key '{$key}' with file '{$filespec}.dat' not found"); } - $this->_unlink($filespec . '.dat'); - $this->_unlink($filespec . '.ifo'); - $this->_lastInfoId = null; + $this->unlink($filespec . '.dat'); + $this->unlink($filespec . '.ifo'); + $this->lastInfoId = null; } - protected function _get($key, array &$options) + protected function internalGetItem($key, array &$options) { - if ( !$this->_exists($key, $options) - || !($keyInfo=$this->_getKeyInfo($key, $options['namespace'])) ) { + if ( !$this->internalHasItem($key, $options) + || !($keyInfo=$this->getKeyInfo($key, $options['namespace'])) + ) { if ($options['ignore_missing_items']) { return false; } else { - throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + throw new ItemNotFoundException( + "Key '{$key}' not found within namespace '{$options['namespace']}'" + ); } } try { - $data = $this->_getFileContent($keyInfo['filespec'] . '.dat'); + $data = $this->getFileContent($keyInfo['filespec'] . '.dat'); if ($this->getReadControl()) { - if ( ($info = $this->_readInfoFile($keyInfo['filespec'] . '.ifo')) - && isset($info['hash'], $info['algo']) ) { + if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) + && isset($info['hash'], $info['algo']) + ) { $hashData = Utils::generateHash($info['algo'], $data, true); if ($hashData != $info['hash']) { throw new UnexpectedValueException( - 'readControl: Stored hash and computed hash don\'t match' + 'ReadControl: Stored hash and computed hash don\'t match' ); } } @@ -1321,16 +1326,16 @@ protected function _get($key, array &$options) } catch (\Exception $e) { try { // remove cache file on exception - $this->_remove($key, $options); + $this->internalRemoveItem($key, $options); } catch (\Exception $tmp) {} // do not throw remove exception on this point throw $e; } } - protected function _exists($key, array &$options) + protected function internalHasItem($key, array &$options) { - $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + $keyInfo = $this->getKeyInfo($key, $options['namespace']); if (!$keyInfo) { return false; // missing or corrupted cache data } @@ -1344,8 +1349,8 @@ protected function _exists($key, array &$options) return false; } - protected function _info($key, array &$options) { - $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + protected function internalGetMetadata($key, array &$options) { + $keyInfo = $this->getKeyInfo($key, $options['namespace']); if (!$keyInfo) { if ($options['ignore_missing_items']) { return false; @@ -1354,16 +1359,16 @@ protected function _info($key, array &$options) { } } - if ( ($info = $this->_readInfoFile($keyInfo['filespec'] . '.ifo')) ) { + if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) ) { return $keyInfo + $info; } return $keyInfo; } - protected function _touch($key, array &$options) + protected function internalTouchItem($key, array &$options) { - $keyInfo = $this->_getKeyInfo($key, $options['namespace']); + $keyInfo = $this->getKeyInfo($key, $options['namespace']); if (!$keyInfo) { if ($options['ignore_missing_items']) { return false; @@ -1378,17 +1383,17 @@ protected function _touch($key, array &$options) } } - protected function _fetchByGlob() + protected function fetchByGlob() { - $options = $this->_stmtOptions; - $mode = $this->_stmtMatch; + $options = $this->stmtOptions; + $mode = $this->stmtMatch; $prefix = $options['namespace'] . $this->getNamespaceSeparator(); $prefixL = strlen($prefix); do { try { - $valid = $this->_stmtGlob->valid(); + $valid = $this->stmtGlob->valid(); } catch (\LogicException $e) { // @link https://bugs.php.net/bug.php?id=55701 // GlobIterator throws LogicException with message @@ -1400,10 +1405,10 @@ protected function _fetchByGlob() } $item = array(); - $info = null; + $meta = null; - $current = $this->_stmtGlob->current(); - $this->_stmtGlob->next(); + $current = $this->stmtGlob->current(); + $this->stmtGlob->next(); $filename = $current->getFilename(); if ($prefix !== '') { @@ -1439,23 +1444,23 @@ protected function _fetchByGlob() // check tags only if one of the tag matching mode is selected if (($mode & 070) > 0) { - $info = $this->_info($key, $options); + $meta = $this->internalGetMetadata($key, $options); // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { - if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { + if (!isset($meta['tags']) || count(array_diff($opts['tags'], $meta['tags'])) > 0) { continue; } // if MATCH_NO_TAGS mode -> check if no given tag available in current cache } elseif( ($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS ) { - if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { + if (isset($meta['tags']) && count(array_diff($opts['tags'], $meta['tags'])) != count($opts['tags'])) { continue; } // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { - if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { + if (!isset($meta['tags']) || count(array_diff($opts['tags'], $meta['tags'])) == count($opts['tags'])) { continue; } @@ -1466,12 +1471,12 @@ protected function _fetchByGlob() if ($select == 'key') { $item['key'] = $key; } else if ($select == 'value') { - $item['value'] = $this->_getFileContent($current->getPathname()); + $item['value'] = $this->getFileContent($current->getPathname()); } else if ($select != 'key') { - if ($info === null) { - $info = $this->_info($key, $options); + if ($meta === null) { + $meta = $this->internalGetMetadata($key, $options); } - $item[$select] = isset($info[$select]) ? $info[$select] : null; + $item[$select] = isset($meta[$select]) ? $meta[$select] : null; } } @@ -1479,7 +1484,7 @@ protected function _fetchByGlob() } while (true); } - protected function _clearByPrefix($prefix, $mode, array &$opts) + protected function clearByPrefix($prefix, $mode, array &$opts) { if (!$this->getWritable()) { return false; @@ -1531,7 +1536,7 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) // check tags only if one of the tag matching mode is selected if (($mode & 070) > 0) { - $info = $this->_readInfoFile($filespec . '.ifo'); + $info = $this->readInfoFile($filespec . '.ifo'); // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { @@ -1558,8 +1563,8 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) // on this time all tests match //////////////////////////////////////// - $this->_unlink($pathnameSpec . '.dat'); // delete data file - $this->_unlink($pathnameSpec . '.ifo'); // delete info file + $this->unlink($pathnameSpec . '.dat'); // delete data file + $this->unlink($pathnameSpec . '.ifo'); // delete info file } return true; @@ -1571,7 +1576,7 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) * @param string $dir Directory to delete * @param string $prefix Namespace + Separator */ - protected function _rmDir($dir, $prefix) + protected function rmDir($dir, $prefix) { $glob = glob( $dir . \DIRECTORY_SEPARATOR . $prefix . '*', @@ -1586,7 +1591,7 @@ protected function _rmDir($dir, $prefix) foreach ($glob as $subdir) { // ignore not empty directories // skip removing current directory if removing of sub-directory failed - $ret = $this->_rmDir($subdir, $prefix) && @rmdir($subdir); + $ret = $this->rmDir($subdir, $prefix) && @rmdir($subdir); } return $ret; } @@ -1599,50 +1604,50 @@ protected function _rmDir($dir, $prefix) * @param string $ns * @return array|boolean */ - protected function _getKeyInfo($key, $ns) + protected function getKeyInfo($key, $ns) { $lastInfoId = $ns . $this->getNamespaceSeparator() . $key; - if ($this->_lastInfoId == $lastInfoId) { - return $this->_lastInfo; + if ($this->lastInfoId == $lastInfoId) { + return $this->lastInfo; } - $filespec = $this->_getKeyFileSpec($key, $ns); + $filespec = $this->getFileSpec($key, $ns); if ( ($filemtime = @filemtime($filespec . '.dat')) === false ) { return false; } - $this->_lastInfoId = $lastInfoId; - $this->_lastInfoAll = null; - $this->_lastInfo = array( + $this->lastInfoId = $lastInfoId; + $this->lastInfoAll = null; + $this->lastInfo = array( 'filespec' => $filespec, 'mtime' => $filemtime ); if (!$this->getNoCtime()) { - $this->_lastInfo['ctime'] = filectime($filespec . '.dat'); + $this->lastInfo['ctime'] = filectime($filespec . '.dat'); } if (!$this->getNoAtime()) { - $this->_lastInfo['atime'] = fileatime($filespec . '.dat'); + $this->lastInfo['atime'] = fileatime($filespec . '.dat'); } - return $this->_lastInfo; + return $this->lastInfo; } /** - * Get cache file spec + * Get file spec of the given key and namespace * * @param string $key * @param string $ns * @return string */ - protected function _getKeyFileSpec($key, $ns) + protected function getFileSpec($key, $ns) { $prefix = $ns . $this->getNamespaceSeparator(); $lastInfoId = $prefix . $key; - if ($this->_lastInfoId == $lastInfoId) { - return $this->_lastInfo['filespec']; + if ($this->lastInfoId == $lastInfoId) { + return $this->lastInfo['filespec']; } $path = $this->getCacheDir(); @@ -1665,17 +1670,18 @@ protected function _getKeyFileSpec($key, $ns) * @return array|boolean The info array or false if file wasn't found * @throws RuntimeException */ - protected function _readInfoFile($file) { - if ( file_exists($file) ) { - $info = @unserialize($this->_getFileContent($file)); - if (!is_array($info)) { - $err = error_get_last(); - throw new RuntimeException("Corrupted info file '{$file}': {$err['message']}"); - } - return $info; + protected function readInfoFile($file) { + if (!file_exists($file)) { + return false; } - return false; + $info = @unserialize($this->getFileContent($file)); + if (!is_array($info)) { + $err = error_get_last(); + throw new RuntimeException("Corrupted info file '{$file}': {$err['message']}"); + } + + return $info; } /** @@ -1684,7 +1690,7 @@ protected function _readInfoFile($file) { * @param string $file File complete path * @throws RuntimeException */ - protected function _getFileContent($file) + protected function getFileContent($file) { // if file locking enabled -> file_get_contents can't be used if ($this->getFileLocking()) { @@ -1729,7 +1735,7 @@ protected function _getFileContent($file) * @param string $data Data to write * @throws RuntimeException */ - protected function _putFileContent($file, $data) + protected function putFileContent($file, $data) { $locking = $this->getFileLocking(); $blocking = $locking ? $this->getFileBlocking() : false; @@ -1742,7 +1748,7 @@ protected function _putFileContent($file, $data) } if(!flock($fp, \LOCK_EX | \LOCK_NB)) { - // file is locked by another process -> aborting writing + // file is locked by another process -> abort writing fclose($fp); return false; } @@ -1780,7 +1786,7 @@ protected function _putFileContent($file, $data) * @param string $file * @throw RuntimeException */ - protected function _unlink($file) { + protected function unlink($file) { if (!@unlink($file)) { // only throw exception if file still exists after deleting if (file_exists($file)) { @@ -1793,13 +1799,13 @@ protected function _unlink($file) { /** * Update dynamic capabilities only if already created */ - protected function _updateCapabilities() + protected function updateCapabilities() { - if ($this->_capabilities) { + if ($this->capabilities) { // update namespace separator - $this->_capabilities->setNamespaceSeparator( - $this->_capabilityMarker, + $this->capabilities->setNamespaceSeparator( + $this->capabilityMarker, $this->getNamespaceSeparator() ); @@ -1814,8 +1820,8 @@ protected function _updateCapabilities() $metadata[] = 'atime'; } - $this->_capabilities->setSupportedMetadata( - $this->_capabilityMarker, + $this->capabilities->setSupportedMetadata( + $this->capabilityMarker, $metadata ); } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 2f7ce1b69..1e65e5f66 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -56,8 +56,8 @@ public function getItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -119,7 +119,7 @@ public function getItems(array $keys, array $options = array()) return array(); } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keys' => & $keys, 'options' => & $options @@ -179,8 +179,8 @@ public function hasItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -226,8 +226,8 @@ public function getMetadata($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -287,8 +287,8 @@ public function setItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -335,7 +335,7 @@ public function setItems(array $keyValuePairs, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, @@ -389,8 +389,8 @@ public function addItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -440,7 +440,7 @@ public function addItems(array $keyValuePairs, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, @@ -497,8 +497,8 @@ public function replaceItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -548,7 +548,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = \ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, @@ -606,8 +606,8 @@ public function touchItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -665,8 +665,8 @@ public function removeItem($key, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -724,7 +724,7 @@ public function removeItems(array $keys, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $args = new \ArrayObject(array( 'keys' => & $keys, 'options' => & $options, @@ -802,8 +802,8 @@ public function incrementItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); - $key = $this->_key($key); + $this->normalizeOptions($options); + $key = $this->key($key); $value = (int)$value; $args = new \ArrayObject(array( 'key' => & $key, @@ -866,9 +866,9 @@ public function decrementItem($key, $value, array $options = array()) return false; } - $this->_normalizeOptions($options); + $this->normalizeOptions($options); $value = (int)$value; - $key = $this->_key($key); + $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -936,12 +936,12 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) return false; } - if ($this->_stmtActive) { + if ($this->stmtActive) { throw new RuntimeException('Statement already in use'); } - $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options, @@ -1000,9 +1000,9 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) // don't check expiry on fetch $options['ttl'] = 0; - $this->_stmtKeys = $keys; - $this->_stmtOptions = $options; - $this->_stmtActive = true; + $this->stmtKeys = $keys; + $this->stmtOptions = $options; + $this->stmtActive = true; $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -1024,7 +1024,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) */ public function fetch() { - if (!$this->_stmtActive) { + if (!$this->stmtActive) { return false; } @@ -1035,11 +1035,11 @@ public function fetch() return $eventRs->last(); } - $options = & $this->_stmtOptions; + $options = & $this->stmtOptions; // get the next valid item do { - $key = array_shift($this->_stmtKeys); + $key = array_shift($this->stmtKeys); if ($key === null) { break; } @@ -1071,9 +1071,9 @@ public function fetch() } else { // free statement after last item - $this->_stmtActive = false; - $this->_stmtKeys = null; - $this->_stmtOptions = null; + $this->stmtActive = false; + $this->stmtKeys = null; + $this->stmtOptions = null; $result = false; } @@ -1112,8 +1112,8 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) return false; } - $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options, @@ -1168,8 +1168,8 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a return false; } - $this->_normalizeOptions($options); - $this->_normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); $args = new \ArrayObject(array( 'mode' => & $mode, 'options' => & $options, @@ -1216,10 +1216,10 @@ public function getCapabilities() return $eventRs->last(); } - if ($this->_capabilities === null) { - $this->_capabilityMarker = new \stdClass(); - $this->_capabilities = new Capabilities( - $this->_capabilityMarker, + if ($this->capabilities === null) { + $this->capabilityMarker = new \stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, array( 'supportedDatatypes' => array( 'NULL' => true, @@ -1248,7 +1248,7 @@ public function getCapabilities() ); } - return $this->triggerPost(__FUNCTION__, $args, $this->_capabilities); + return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); } /** From cc3aa1b69171485f1f75c24e51e95e34c3147dce Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Sat, 10 Dec 2011 17:30:10 +0100 Subject: [PATCH 128/311] Added PhpDoc for Zend\Cache, refactored for UnsupportedMethodCallExceptions to be consistent with Zend\Search\Lucence\Exception\UnsupportedMethodCallException --- .../UnsupportedMethodCallException.php | 7 + src/Storage/Adapter/AbstractAdapter.php | 195 +++++++- src/Storage/Adapter/Filesystem.php | 422 ++++++++++++++++++ src/Storage/Capabilities.php | 51 ++- src/Storage/Plugin/ClearByFactor.php | 38 ++ src/Storage/Plugin/ExceptionHandler.php | 66 +++ src/Storage/Plugin/OptimizeByFactor.php | 42 +- src/Storage/Plugin/Serializer.php | 125 ++++++ src/Storage/PluginBroker.php | 2 + src/Storage/PluginLoader.php | 4 +- 10 files changed, 945 insertions(+), 7 deletions(-) create mode 100644 src/Exception/UnsupportedMethodCallException.php diff --git a/src/Exception/UnsupportedMethodCallException.php b/src/Exception/UnsupportedMethodCallException.php new file mode 100644 index 000000000..bc2e118d2 --- /dev/null +++ b/src/Exception/UnsupportedMethodCallException.php @@ -0,0 +1,7 @@ +getReadable()) { @@ -565,6 +591,13 @@ public function getItems(array $keys, array $options = array()) return $ret; } + /** + * Checks if adapter has an item + * + * @param string $key + * @param array $options + * @return bool + */ public function hasItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -580,6 +613,13 @@ public function hasItem($key, array $options = array()) return $ret; } + /** + * Checks if adapter has items + * + * @param array $keys + * @param array $options + * @return array + */ public function hasItems(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -596,6 +636,13 @@ public function hasItems(array $keys, array $options = array()) return $ret; } + /** + * Get Metadatas + * + * @param array $keys + * @param array $options + * @return array + */ public function getMetadatas(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -619,6 +666,13 @@ public function getMetadatas(array $keys, array $options = array()) /* writing */ + /** + * Set items + * + * @param array $keyValuePairs + * @param array $options + * @return bool + */ public function setItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -633,6 +687,15 @@ public function setItems(array $keyValuePairs, array $options = array()) return $ret; } + /** + * Add an item + * + * @param $key + * @param $value + * @param array $options + * @return bool + * @throws RuntimeException + */ public function addItem($key, $value, array $options = array()) { if ($this->hasItem($key, $options)) { @@ -641,6 +704,13 @@ public function addItem($key, $value, array $options = array()) return $this->setItem($key, $value, $options); } + /** + * Add items + * + * @param array $keyValuePairs + * @param array $options + * @return bool + */ public function addItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -655,6 +725,15 @@ public function addItems(array $keyValuePairs, array $options = array()) return $ret; } + /** + * Replace an item + * + * @param $key + * @param $value + * @param array $options + * @return bool + * @throws ItemNotFoundException + */ public function replaceItem($key, $value, array $options = array()) { if (!$this->hasItem($key, $options)) { @@ -663,6 +742,13 @@ public function replaceItem($key, $value, array $options = array()) return $this->setItem($key, $value, $options); } + /** + * Replace items + * + * @param array $keyValuePairs + * @param array $options + * @return bool + */ public function replaceItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -677,6 +763,15 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return $ret; } + /** + * Check and set item + * + * @param $token + * @param $key + * @param $value + * @param array $options + * @return bool + */ public function checkAndSetItem($token, $key, $value, array $options = array()) { $oldValue = $this->getItem($key, $options); @@ -687,6 +782,13 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) return $this->setItem($key, $value, $options); } + /** + * Touch an item + * + * @param $key + * @param array $options + * @return bool + */ public function touchItem($key, array $options = array()) { if (!$this->getWritable() || !$this->getReadable()) { @@ -714,6 +816,13 @@ public function touchItem($key, array $options = array()) } } + /** + * Touch items + * + * @param array $keys + * @param array $options + * @return bool + */ public function touchItems(array $keys, array $options = array()) { // Don't check readable because not all adapters needs to read the item before @@ -728,6 +837,13 @@ public function touchItems(array $keys, array $options = array()) return $ret; } + /** + * Remove items + * + * @param array $keys + * @param array $options + * @return bool + */ public function removeItems(array $keys, array $options = array()) { if (!$this->getWritable()) { @@ -742,6 +858,14 @@ public function removeItems(array $keys, array $options = array()) return $ret; } + /** + * Increment an item + * + * @param $key + * @param $value + * @param array $options + * @return bool|int + */ public function incrementItem($key, $value, array $options = array()) { if (!$this->getWritable() || !$this->getReadable()) { @@ -754,6 +878,13 @@ public function incrementItem($key, $value, array $options = array()) return $get + $value; } + /** + * Increment items + * + * @param array $keyValuePairs + * @param array $options + * @return bool + */ public function incrementItems(array $keyValuePairs, array $options = array()) { // Don't check readable because not all adapters needs read the value before @@ -768,6 +899,14 @@ public function incrementItems(array $keyValuePairs, array $options = array()) return $ret; } + /** + * Decrement an item + * + * @param $key + * @param $value + * @param array $options + * @return bool|int + */ public function decrementItem($key, $value, array $options = array()) { if (!$this->getWritable() || !$this->getReadable()) { @@ -780,6 +919,13 @@ public function decrementItem($key, $value, array $options = array()) return $get - $value; } + /** + * Decrement items + * + * @param array $keyValuePairs + * @param array $options + * @return bool + */ public function decrementItems(array $keyValuePairs, array $options = array()) { // Don't check readable because not all adapters needs read the value before @@ -796,6 +942,14 @@ public function decrementItems(array $keyValuePairs, array $options = array()) /* non-blocking */ + /** + * Get delayed + * + * @param array $keys + * @param array $options + * @return bool + * @throws InvalidArgumentException|RuntimeException + */ public function getDelayed(array $keys, array $options = array()) { if ($this->_stmtActive) { @@ -834,11 +988,23 @@ public function getDelayed(array $keys, array $options = array()) return true; } + /** + * Find + * + * @param int $mode + * @param array $options + * @throws UnsupportedMethodCallException + */ public function find($mode = self::MATCH_ACTIVE, array $options = array()) { - throw new BadMethodCallException('find isn\'t supported by this adapter'); + throw new UnsupportedMethodCallException('find isn\'t supported by this adapter'); } + /** + * Fetch + * + * @return array|bool + */ public function fetch() { if (!$this->_stmtActive) { @@ -897,6 +1063,11 @@ public function fetch() return false; } + /** + * Fetch all + * + * @return array + */ public function fetchAll() { $rs = array(); @@ -908,6 +1079,13 @@ public function fetchAll() /* cleaning */ + /** + * Clear + * + * @param int $mode + * @param array $options + * @throws RuntimeException + */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { throw new RuntimeException( @@ -915,6 +1093,13 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) ); } + /** + * Clear by namespace + * + * @param int $mode + * @param array $options + * @throws RuntimeException + */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { throw new RuntimeException( @@ -922,6 +1107,12 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a ); } + /** + * Optimize + * + * @param array $options + * @return bool + */ public function optimize(array $options = array()) { return true; diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 978cef06d..007dec3ad 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -117,19 +117,42 @@ class Filesystem extends AbstractAdapter /** * Statement + * + * @var \GlobIterator|null */ protected $_stmtGlob = null; + + /** + * Statement match + * + * @var integer|null + */ protected $_stmtMatch = null; /** * Buffer vars + * + * @var string|null */ protected $_lastInfoId = null; + + /** + * @var array|bool|null + */ protected $_lastInfoAll = null; + + /** + * @var array|null + */ protected $_lastInfo = null; /* configuration */ + /** + * Get options + * + * @return array + */ public function getOptions() { $options = parent::getOptions(); @@ -150,6 +173,12 @@ public function getOptions() return $options; } + /** + * Set namespace separator + * + * @param string $separator + * @return Filesystem + */ public function setNamespaceSeparator($separator) { $this->_namespaceSeparator = (string)$separator; @@ -157,11 +186,23 @@ public function setNamespaceSeparator($separator) return $this; } + /** + * Get namespace separator + * + * @return string + */ public function getNamespaceSeparator() { return $this->_namespaceSeparator; } + /** + * Set cache dir + * + * @param string $dir + * @return Filesystem + * @throws InvalidArgumentException + */ public function setCacheDir($dir) { if ($dir !== null) { @@ -186,6 +227,11 @@ public function setCacheDir($dir) return $this; } + /** + * Get cache dir + * + * @return null|string + */ public function getCacheDir() { if ($this->_cacheDir === null) { @@ -195,6 +241,12 @@ public function getCacheDir() return $this->_cacheDir; } + /** + * Set file perm + * + * @param $perm + * @return Filesystem + */ public function setFilePerm($perm) { if (is_string($perm)) { @@ -207,11 +259,23 @@ public function setFilePerm($perm) return $this->setFileUmask(~$perm); } + /** + * Get file perm + * + * @return int + */ public function getFilePerm() { return ~$this->getFileUmask(); } + /** + * Set file umask + * + * @param $umask + * @return Filesystem + * @throws InvalidArgumentException + */ public function setFileUmask($umask) { if (is_string($umask)) { @@ -235,33 +299,66 @@ public function setFileUmask($umask) return $this; } + /** + * Get file umask + * + * @return int + */ public function getFileUmask() { return $this->_fileUmask; } + /** + * Set file locking + * + * @param bool $flag + * @return Filesystem + */ public function setFileLocking($flag) { $this->_fileLocking = (bool)$flag; return $this; } + /** + * Get file locking + * + * @return bool + */ public function getFileLocking() { return $this->_fileLocking; } + /** + * Set file blocking + * + * @param bool $flag + * @return Filesystem + */ public function setFileBlocking($flag) { $this->_fileBlocking = (bool)$flag; return $this; } + /** + * Get file blocking + * + * @return bool + */ public function getFileBlocking() { return $this->_fileBlocking; } + /** + * Set no atime + * + * @param bool $flag + * @return Filesystem + */ public function setNoAtime($flag) { $this->_noAtime = (bool)$flag; @@ -269,11 +366,22 @@ public function setNoAtime($flag) return $this; } + /** + * Get no atime + * + * @return bool + */ public function getNoAtime() { return $this->_noAtime; } + /** + * Set no ctime + * + * @param bool $flag + * @return Filesystem + */ public function setNoCtime($flag) { $this->_noCtime = (bool)$flag; @@ -281,11 +389,22 @@ public function setNoCtime($flag) return $this; } + /** + * Get no ctime + * + * @return bool + */ public function getNoCtime() { return $this->_noCtime; } + /** + * Set dir perm + * + * @param string|integer $perm + * @return Filesystem + */ public function setDirPerm($perm) { if (is_string($perm)) { @@ -298,11 +417,23 @@ public function setDirPerm($perm) return $this->setDirUmask(~$perm); } + /** + * Get dir perm + * + * @return int + */ public function getDirPerm() { return ~$this->getDirUmask(); } + /** + * Set dir umask + * + * @param string|integer $umask + * @return Filesystem + * @throws InvalidArgumentException + */ public function setDirUmask($umask) { if (is_string($umask)) { @@ -322,11 +453,23 @@ public function setDirUmask($umask) return $this; } + /** + * Get dir umask + * + * @return int + */ public function getDirUmask() { return $this->_dirUmask; } + /** + * Set dir level + * + * @param integer $level + * @return Filesystem + * @throws InvalidArgumentException + */ public function setDirLevel($level) { $level = (int)$level; @@ -339,22 +482,45 @@ public function setDirLevel($level) return $this; } + /** + * Get dir level + * + * @return int + */ public function getDirLevel() { return $this->_dirLevel; } + /** + * Set read control + * + * @param bool $flag + * @return Filesystem + */ public function setReadControl($flag) { $this->_readControl = (bool)$flag; return $this; } + /** + * Get read control + * + * @return bool + */ public function getReadControl() { return $this->_readControl; } + /** + * Set real control algo + * + * @param string $algo + * @return Filesystem + * @throws InvalidArgumentException + */ public function setReadControlAlgo($algo) { $algo = strtolower($algo); @@ -367,17 +533,33 @@ public function setReadControlAlgo($algo) return $this; } + /** + * Get read control algo + * + * @return string + */ public function getReadControlAlgo() { return $this->_readControlAlgo; } + /** + * Set clear stat cache + * + * @param bool $flag + * @return Filesystem + */ public function setClearStatCache($flag) { $this->_clearStatCache = (bool)$flag; return $this; } + /** + * Get clear stat cache + * + * @return bool + */ public function getClearStatCache() { return $this->_clearStatCache; @@ -385,6 +567,13 @@ public function getClearStatCache() /* reading */ + /** + * Get item + * + * @param $key + * @param array $options + * @return bool|mixed + */ public function getItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -421,6 +610,13 @@ public function getItem($key, array $options = array()) } } + /** + * Get items + * + * @param array $keys + * @param array $options + * @return array|mixed + */ public function getItems(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -459,6 +655,13 @@ public function getItems(array $keys, array $options = array()) } } + /** + * Check for an item + * + * @param $key + * @param array $options + * @return bool|mixed + */ public function hasItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -489,6 +692,13 @@ public function hasItem($key, array $options = array()) } } + /** + * Check for items + * + * @param array $keys + * @param array $options + * @return array|mixed + */ public function hasItems(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -524,6 +734,13 @@ public function hasItems(array $keys, array $options = array()) } } + /** + * Get metadata + * + * @param $key + * @param array $options + * @return array|bool|mixed|null + */ public function getMetadata($key, array $options = array()) { if (!$this->getReadable()) { @@ -560,6 +777,13 @@ public function getMetadata($key, array $options = array()) } } + /** + * Get metadatas + * + * @param array $keys + * @param array $options + * @return array|mixed + */ public function getMetadatas(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -600,6 +824,14 @@ public function getMetadatas(array $keys, array $options = array()) /* writing */ + /** + * Set item + * + * @param $key + * @param $value + * @param array $options + * @return bool|mixed + */ public function setItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -631,6 +863,13 @@ public function setItem($key, $value, array $options = array()) } } + /** + * Set items + * + * @param array $keyValuePairs + * @param array $options + * @return bool|mixed + */ public function setItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -664,6 +903,15 @@ public function setItems(array $keyValuePairs, array $options = array()) } } + /** + * Replace an item + * + * @param $key + * @param $value + * @param array $options + * @return bool|mixed + * @throws ItemNotFoundException + */ public function replaceItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -699,6 +947,14 @@ public function replaceItem($key, $value, array $options = array()) } } + /** + * Replace items + * + * @param array $keyValuePairs + * @param array $options + * @return bool|mixed + * @throws ItemNotFoundException + */ public function replaceItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -735,6 +991,15 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } } + /** + * Add an item + * + * @param $key + * @param $value + * @param array $options + * @return bool|mixed + * @throws RuntimeException + */ public function addItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -770,6 +1035,14 @@ public function addItem($key, $value, array $options = array()) } } + /** + * Add items + * + * @param array $keyValuePairs + * @param array $options + * @return bool|mixed + * @throws RuntimeException + */ public function addItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -807,6 +1080,16 @@ public function addItems(array $keyValuePairs, array $options = array()) } } + /** + * check and set item + * + * @param $token + * @param $key + * @param $value + * @param array $options + * @return bool|mixed + * @throws ItemNotFoundException + */ public function checkAndSetItem($token, $key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -854,6 +1137,13 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) } } + /** + * Touch an item + * + * @param $key + * @param array $options + * @return bool|mixed + */ public function touchItem($key, array $options = array()) { if (!$this->getWritable()) { @@ -887,6 +1177,13 @@ public function touchItem($key, array $options = array()) } } + /** + * Touch items + * + * @param array $keys + * @param array $options + * @return bool|mixed + */ public function touchItems(array $keys, array $options = array()) { if (!$this->getWritable()) { @@ -917,6 +1214,13 @@ public function touchItems(array $keys, array $options = array()) } } + /** + * Remove an item + * + * @param $key + * @param array $options + * @return bool|mixed + */ public function removeItem($key, array $options = array()) { if (!$this->getWritable()) { @@ -946,6 +1250,13 @@ public function removeItem($key, array $options = array()) } } + /** + * Remove items + * + * @param array $keys + * @param array $options + * @return bool|mixed + */ public function removeItems(array $keys, array $options = array()) { if (!$this->getWritable()) { @@ -978,6 +1289,14 @@ public function removeItems(array $keys, array $options = array()) /* non-blocking */ + /** + * Find + * + * @param int $mode + * @param array $options + * @return bool|mixed + * @throws RuntimeException + */ public function find($mode = self::MATCH_ACTIVE, array $options = array()) { if ($this->_stmtActive) { @@ -1028,6 +1347,11 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) } } + /** + * Fetch + * + * @return bool|mixed + */ public function fetch() { if (!$this->_stmtActive) { @@ -1064,6 +1388,13 @@ public function fetch() /* cleaning */ + /** + * Clear + * + * @param int $mode + * @param array $options + * @return mixed + */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { $this->_normalizeOptions($options); @@ -1086,6 +1417,13 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } } + /** + * Clear by namespace + * + * @param int $mode + * @param array $options + * @return mixed + */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { $this->_normalizeOptions($options); @@ -1109,6 +1447,12 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a } } + /** + * Optimize + * + * @param array $options + * @return bool|mixed + */ public function optimize(array $options = array()) { if (!$this->getWritable()) { @@ -1140,6 +1484,11 @@ public function optimize(array $options = array()) /* status */ + /** + * Get capabilities + * + * @return mixed + */ public function getCapabilities() { $args = new \ArrayObject(); @@ -1190,6 +1539,12 @@ public function getCapabilities() } } + /** + * Get capacity + * + * @param array $options + * @return mixed + */ public function getCapacity(array $options = array()) { $args = new \ArrayObject(); @@ -1209,6 +1564,15 @@ public function getCapacity(array $options = array()) /* internal */ + /** + * Set key value pair + * + * @param $key + * @param $value + * @param array $options + * @return bool + * @throws RuntimeException + */ protected function _set($key, $value, array &$options) { $oldUmask = null; @@ -1277,6 +1641,13 @@ protected function _set($key, $value, array &$options) } } + /** + * Remove a key + * + * @param $key + * @param array $options + * @throws ItemNotFoundException + */ protected function _remove($key, array &$options) { $filespec = $this->_getKeyFileSpec($key, $options['namespace']); @@ -1290,6 +1661,14 @@ protected function _remove($key, array &$options) $this->_lastInfoId = null; } + /** + * Get by key + * + * @param $key + * @param array $options + * @return bool|string + * @throws \Exception|ItemNotFoundException|UnexpectedValueException + */ protected function _get($key, array &$options) { if ( !$this->_exists($key, $options) @@ -1328,6 +1707,13 @@ protected function _get($key, array &$options) } } + /** + * Checks for a key + * + * @param $key + * @param array $options + * @return bool + */ protected function _exists($key, array &$options) { $keyInfo = $this->_getKeyInfo($key, $options['namespace']); @@ -1344,6 +1730,14 @@ protected function _exists($key, array &$options) return false; } + /** + * Get info by key + * + * @param $key + * @param array $options + * @return array|bool + * @throws ItemNotFoundException + */ protected function _info($key, array &$options) { $keyInfo = $this->_getKeyInfo($key, $options['namespace']); if (!$keyInfo) { @@ -1361,6 +1755,14 @@ protected function _info($key, array &$options) { return $keyInfo; } + /** + * Touch a key + * + * @param $key + * @param array $options + * @return bool + * @throws ItemNotFoundException|RuntimeException + */ protected function _touch($key, array &$options) { $keyInfo = $this->_getKeyInfo($key, $options['namespace']); @@ -1378,6 +1780,11 @@ protected function _touch($key, array &$options) } } + /** + * Fetch by glob + * + * @return array|bool + */ protected function _fetchByGlob() { $options = $this->_stmtOptions; @@ -1479,6 +1886,15 @@ protected function _fetchByGlob() } while (true); } + /** + * Clear by prefix + * + * @param $prefix + * @param $mode + * @param array $opts + * @return bool + * @throws RuntimeException + */ protected function _clearByPrefix($prefix, $mode, array &$opts) { if (!$this->getWritable()) { @@ -1570,6 +1986,7 @@ protected function _clearByPrefix($prefix, $mode, array &$opts) * * @param string $dir Directory to delete * @param string $prefix Namespace + Separator + * @return bool */ protected function _rmDir($dir, $prefix) { @@ -1682,6 +2099,7 @@ protected function _readInfoFile($file) { * Read a complete file * * @param string $file File complete path + * @return string * @throws RuntimeException */ protected function _getFileContent($file) @@ -1727,6 +2145,7 @@ protected function _getFileContent($file) * * @param string $file File complete path * @param string $data Data to write + * @return bool * @throws RuntimeException */ protected function _putFileContent($file, $data) @@ -1778,6 +2197,7 @@ protected function _putFileContent($file, $data) * Unlink a file * * @param string $file + * @return void * @throw RuntimeException */ protected function _unlink($file) { @@ -1792,6 +2212,8 @@ protected function _unlink($file) { /** * Update dynamic capabilities only if already created + * + * @return void */ protected function _updateCapabilities() { diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 729070f1f..6a5340fa7 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -25,7 +25,7 @@ class Capabilities */ protected $_eventManager; - /**#@+ + /** * Capability property * * If it's NULL the capability isn't set and the getter @@ -34,19 +34,66 @@ class Capabilities * @var null|mixed */ protected $_supportedDatatypes; + + /** + * Supported metdata + */ protected $_supportedMetadata; + + /** + * Max ttl + */ protected $_maxTtl; + + /** + * Static ttl + */ protected $_staticTtl; + + /** + * Ttl precision + */ protected $_ttlPrecision; + + /** + * Use request time + */ protected $_useRequestTime; + + /** + * Expire read + */ protected $_expiredRead; + + /** + * Max key length + */ protected $_maxKeyLength; + + /** + * Namespace is prefix + */ protected $_namespaceIsPrefix; + + /** + * Namespace separator + */ protected $_namespaceSeparator; + + /** + * Iterable + */ protected $_iterable; + + /** + * Clear all namespaces + */ protected $_clearAllNamespaces; + + /** + * Clear by namespace + */ protected $_clearByNamespace; - /**#@-*/ /** * Base capabilities diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 283baaaa6..57aa82c76 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -25,13 +25,30 @@ class ClearByFactor implements Plugin */ protected $_clearByNamespace = true; + /** + * Handles + * + * @var array + */ protected $handles = array(); + /** + * Constructor + * + * @param array|\Traversable $options + * @return void + */ public function __construct($options = array()) { $this->setOptions($options); } + /** + * Set options + * + * @param array|\Traversable $options + * @return void + */ public function setOptions($options) { foreach ($options as $name => $value) { @@ -40,6 +57,11 @@ public function setOptions($options) } } + /** + * Get options + * + * @return array + */ public function getOptions() { return array( @@ -63,6 +85,7 @@ public function getClearingFactor() * * @param int $factor * @return Zend\Cache\Storage\Plugin\ClearByFactor Fluent interface + * @throws InvalidArgumentException */ public function setClearingFactor($factor) { @@ -97,6 +120,13 @@ public function setClearByNamespace($flag) return $this; } + /** + * Attach + * + * @param EventCollection $eventCollection + * @return ClearByFactor + * @throws LogicException + */ public function attach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -115,6 +145,13 @@ public function attach(EventCollection $eventCollection) return $this; } + /** + * Detach + * + * @param EventCollection $eventCollection + * @return ClearByFactor + * @throws LogicException + */ public function detach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -137,6 +174,7 @@ public function detach(EventCollection $eventCollection) * Clear storage by factor on a success _RESULT_ * * @param Zend\Cache\Storage\PostEvent $event + * @return void */ public function clearByFactor(PostEvent $event) { diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index b5adcff06..d5ef49d71 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -9,14 +9,35 @@ class ExceptionHandler implements Plugin { + /** + * Callback + */ protected $_callback = null; + + /** + * Throw exceptions + * + * @var bool + */ protected $_throwExceptions = true; + /** + * Constructor + * + * @param array|\Traversable $options + * @return void + */ public function __construct($options = array()) { $this->setOptions($options); } + /** + * Set options + * + * @param array|\Traversable $options + * @return void + */ public function setOptions($options) { foreach ($options as $name => $value) { @@ -25,6 +46,11 @@ public function setOptions($options) } } + /** + * Get options + * + * @return array + */ public function getOptions() { $options = parent::getOptions(); @@ -33,6 +59,12 @@ public function getOptions() return $options; } + /** + * Set callback + * + * @param $callback + * @throws InvalidArgumentException + */ public function setCallback($callback) { if (!is_callable($callback, true)) { @@ -41,21 +73,42 @@ public function setCallback($callback) $this->_callback = $callback; } + /** + * Get callback + */ public function getCallback() { return $this->_callback; } + /** + * Set throw exceptions + * + * @param bool $flag + * @return void + */ public function setThrowExceptions($flag) { $this->_throwExceptions = (bool)$flag; } + /** + * Get throw exceptions + * + * @return bool + */ public function getThrowExceptions() { return $this->_throwExceptions; } + /** + * Attach + * + * @param EventCollection $eventCollection + * @return ExceptionHandler + * @throws LogicException + */ public function attach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -120,6 +173,13 @@ public function attach(EventCollection $eventCollection) return $this; } + /** + * Detach + * + * @param EventCollection $eventCollection + * @return ExceptionHandler + * @throws LogicException + */ public function detach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -138,6 +198,12 @@ public function detach(EventCollection $eventCollection) return $this; } + /** + * On exception + * + * @param \ExceptionEvent $event + * @return void + */ public function onException(ExceptionEvent $event) { if ( ($callback = $this->getCallback()) ) { diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index 6745e714a..c042ca183 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -11,6 +11,11 @@ class OptimizeByFactor implements Plugin { + /** + * Handles + * + * @var array + */ protected $handles = array(); /** @@ -20,11 +25,23 @@ class OptimizeByFactor implements Plugin */ protected $_optimizingFactor = 0; + /** + * Constructor + * + * @param array|\Traversable $options + * @return void + */ public function __construct($options = array()) { $this->setOptions($options); } + /** + * Set options + * + * @param array|\Traversable $options + * @return void + */ public function setOptions($options) { foreach ($options as $name => $value) { @@ -33,6 +50,11 @@ public function setOptions($options) } } + /** + * Get options + * + * @return array + */ public function getOptions() { return array( @@ -54,7 +76,8 @@ public function getOptimizingFactor() * Set automatic optimizing factor * * @param int $factor - * @return Zend\Cache\Storage\Plugin\AutomaticOptimize + * @return OptimizeByFactor + * @throws InvalidArgumentAxception */ public function setOptimizingFactor($factor) { @@ -67,6 +90,13 @@ public function setOptimizingFactor($factor) return $this; } + /** + * Attach + * + * @param EventCollection $eventCollection + * @return OptimizeByFactor + * @throws LogicException + */ public function attach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -85,6 +115,13 @@ public function attach(EventCollection $eventCollection) return $this; } + /** + * Detach + * + * @param EventCollection $eventCollection + * @return OptimizeByFactor + * @throws LogicException + */ public function detach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -106,7 +143,8 @@ public function detach(EventCollection $eventCollection) /** * Optimize by factor on a success _RESULT_ * - * @param Zend\Cache\Storage\PostEvent $event + * @param PostEvent $event + * @return void */ public function optimizeByFactor(PostEvent $event) { diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index b07a1579a..6e643c484 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -13,15 +13,44 @@ class Serializer implements Plugin { + /** + * Serializer adapter + * + * @var SerializerAdapter + */ protected $serializer; + + /** + * Capabilities + * + * @var array + */ protected $capabilities = array(); + + /** + * Handles + * + * @var array + */ protected $handles = array(); + /** + * Constructor + * + * @param array|\Traversable $options + * @return void + */ public function __construct($options = array()) { $this->setOptions($options); } + /** + * Set options + * + * @param array|\Traversable $options + * @return void + */ public function setOptions($options) { foreach ($options as $name => $value) { @@ -30,6 +59,11 @@ public function setOptions($options) } } + /** + * Get options + * + * @return array + */ public function getOptions() { return array( @@ -37,12 +71,23 @@ public function getOptions() ); } + /** + * Set serializer + * + * @param SerializerAdapter $serializer + * @return Serializer + */ public function setSerializer(SerializerAdapter $serializer) { $this->serializer = $serializer; return $this; } + /** + * Get serializer + * + * @return SerializerAdapter + */ public function getSerializer() { if (!$this->serializer) { @@ -51,6 +96,13 @@ public function getSerializer() return $this->serializer; } + /** + * Attach + * + * @param EventCollection $eventCollection + * @return Serializer + * @throws LogicException + */ public function attach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -94,6 +146,13 @@ public function attach(EventCollection $eventCollection) return $this; } + /** + * Detach + * + * @param EventCollection $eventCollection + * @return Serializer + * @throws LogicException + */ public function detach(EventCollection $eventCollection) { $index = \spl_object_hash($eventCollection); @@ -112,6 +171,12 @@ public function detach(EventCollection $eventCollection) return $this; } + /** + * On read item post + * + * @param PostEvent $event + * @return void + */ public function onReadItemPost(PostEvent $event) { $serializer = $this->getSerializer(); @@ -120,6 +185,12 @@ public function onReadItemPost(PostEvent $event) $event->setResult($result); } + /** + * On read items post + * + * @param PostEvent $event + * @return void + */ public function onReadItemsPost(PostEvent $event) { $serializer = $this->getSerializer(); @@ -130,6 +201,12 @@ public function onReadItemsPost(PostEvent $event) $event->setResult($result); } + /** + * On fetch post + * + * @param PostEvent $event + * @return void + */ public function onFetchPost(PostEvent $event) { $item = $event->getResult(); @@ -139,6 +216,12 @@ public function onFetchPost(PostEvent $event) $event->setResult($item); } + /** + * On fetch all post + * + * @param PostEvent $event + * @return void + */ public function onFetchAllPost(PostEvent $event) { $serializer = $this->getSerializer(); @@ -151,6 +234,12 @@ public function onFetchAllPost(PostEvent $event) $event->setResult($result); } + /** + * On write item pre + * + * @param Event $event + * @return void + */ public function onWriteItemPre(Event $event) { $serializer = $this->getSerializer(); @@ -158,6 +247,12 @@ public function onWriteItemPre(Event $event) $params['value'] = $serializer->serialize($params['value']); } + /** + * On write items pre + * + * @param Event $event + * @return void + */ public function onWriteItemsPre(Event $event) { $serializer = $this->getSerializer(); @@ -167,6 +262,12 @@ public function onWriteItemsPre(Event $event) } } + /** + * On increment item pre + * + * @param Event $event + * @return mixed + */ public function onIncrementItemPre(Event $event) { $event->stopPropagation(true); @@ -178,6 +279,12 @@ public function onIncrementItemPre(Event $event) return $cache->checkAndSetItem($token, $oldValue + $params['value'], $params['key'], $params['options']); } + /** + * On increment items pre + * + * @param Event $event + * @return mixed + */ public function onIncrementItemsPre(Event $event) { $event->stopPropagation(true); @@ -195,6 +302,12 @@ public function onIncrementItemsPre(Event $event) return $cache->setItems($keyValuePairs, $params['options']); } + /** + * On decrement item pre + * + * @param Event $event + * @return mixed + */ public function onDecrementItemPre(Event $event) { $event->stopPropagation(true); @@ -206,6 +319,12 @@ public function onDecrementItemPre(Event $event) return $cache->checkAndSetItem($token, $oldValue - $params['value'], $params['key'], $params['options']); } + /** + * On decrement items pre + * + * @param Event $event + * @return mixed + */ public function onDecrementItemsPre(Event $event) { $event->stopPropagation(true); @@ -223,6 +342,12 @@ public function onDecrementItemsPre(Event $event) return $cache->setItems($keyValuePairs, $params['options']); } + /** + * On get capabilities + * + * @param PostEvent $event + * @return void + */ public function onGetCapabilitiesPost(PostEvent $event) { $baseCapabilities = $event->getResult(); diff --git a/src/Storage/PluginBroker.php b/src/Storage/PluginBroker.php index b18d78236..f9e4c6057 100644 --- a/src/Storage/PluginBroker.php +++ b/src/Storage/PluginBroker.php @@ -34,6 +34,8 @@ class PluginBroker extends Loader\PluginBroker { /** + * Default class loader + * * @var string Default plugin loading strategy */ protected $defaultClassLoader = 'Zend\Cache\Storage\PluginLoader'; diff --git a/src/Storage/PluginLoader.php b/src/Storage/PluginLoader.php index fa5448310..d7edd74c9 100644 --- a/src/Storage/PluginLoader.php +++ b/src/Storage/PluginLoader.php @@ -33,7 +33,9 @@ class PluginLoader extends PluginClassLoader { /** - * @var array Pre-aliased adapters + * Pre-aliased adapters + * + * @var array */ protected $plugins = array( 'clear_by_factor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', From d1a962e10b6c271d2455573d239c151a5d7529b9 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 17:45:38 +0100 Subject: [PATCH 129/311] renamed internal method key() -> normalizeKey and set by ref --- src/Storage/Adapter/AbstractAdapter.php | 16 ++++++++-------- src/Storage/Adapter/Filesystem.php | 18 +++++++++--------- src/Storage/Adapter/Memory.php | 20 ++++++++++---------- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 6813ac09b..779374bb0 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -652,9 +652,9 @@ public function getMetadatas(array $keys, array $options = array()) $ret = array(); foreach ($keys as $key) { try { - $info = $this->getMetadata($key, $options); - if ($info !== false) { - $ret[$key] = $info; + $meta = $this->getMetadata($key, $options); + if ($meta !== false) { + $ret[$key] = $meta; } } catch (ItemNotFoundException $e) { // ignore missing items @@ -1273,19 +1273,19 @@ protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOpt } /** - * Get, validate and normalize key. + * Validates and normalizes a key * * @param string $key * @return string - * @throws InvalidArgumentException + * @throws InvalidArgumentException On an invalid key */ - protected function key($key) + protected function normalizeKey(&$key) { + $key = (string)$key; + if (($p = $this->getKeyPattern()) && !preg_match($p, $key)) { throw new InvalidArgumentException("The key '{$key}' doesn't match agains pattern '{$p}'"); } - - return (string)$key; } } diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 8e35e5223..345b88014 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -581,7 +581,7 @@ public function getItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -669,7 +669,7 @@ public function hasItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -748,7 +748,7 @@ public function getMetadata($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -840,7 +840,7 @@ public function setItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -920,7 +920,7 @@ public function replaceItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -1008,7 +1008,7 @@ public function addItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -1098,7 +1098,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'token' => & $token, 'key' => & $key, @@ -1152,7 +1152,7 @@ public function touchItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -1229,7 +1229,7 @@ public function removeItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 1e65e5f66..ff68548d4 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -57,7 +57,7 @@ public function getItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options @@ -180,7 +180,7 @@ public function hasItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -227,7 +227,7 @@ public function getMetadata($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -288,7 +288,7 @@ public function setItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -390,7 +390,7 @@ public function addItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -498,7 +498,7 @@ public function replaceItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, @@ -607,7 +607,7 @@ public function touchItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -666,7 +666,7 @@ public function removeItem($key, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $args = new \ArrayObject(array( 'key' => & $key, 'options' => & $options, @@ -803,7 +803,7 @@ public function incrementItem($key, $value, array $options = array()) } $this->normalizeOptions($options); - $key = $this->key($key); + $this->normalizeKey($key); $value = (int)$value; $args = new \ArrayObject(array( 'key' => & $key, @@ -867,8 +867,8 @@ public function decrementItem($key, $value, array $options = array()) } $this->normalizeOptions($options); + $this->normalizeKey($key); $value = (int)$value; - $key = $this->key($key); $args = new \ArrayObject(array( 'key' => & $key, 'value' => & $value, From 8d8705408a6654c97d97971f3a42e4319941626c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 19:00:43 +0100 Subject: [PATCH 130/311] removed underscores (if possible) of protected members of capabilities --- src/Storage/Capabilities.php | 103 +++++++++++++++++------------------ 1 file changed, 50 insertions(+), 53 deletions(-) diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 6a5340fa7..05a262264 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -1,9 +1,6 @@ _marker = $marker; - $this->_baseCapabilities = $baseCapabilities; + $this->marker = $marker; + $this->baseCapabilities = $baseCapabilities; foreach ($capabilities as $name => $value) { - $this->_setCapability($marker, $name, $value); + $this->setCapability($marker, $name, $value); } } @@ -128,7 +125,7 @@ public function __construct( */ public function hasEventManager() { - return ($this->_eventManager !== null || class_exists('Zend\EventManager\EventManager')); + return ($this->eventManager !== null || class_exists('Zend\EventManager\EventManager')); } /** @@ -139,7 +136,7 @@ public function hasEventManager() */ public function getEventManager() { - if ($this->_eventManager === null) { + if ($this->eventManager === null) { if (!class_exists('Zend\EventManager\EventManager')) { throw new MissingDependencyException('Zend\EventManager not found'); } @@ -148,17 +145,17 @@ public function getEventManager() $eventManager = new EventManager(); // trigger change event on change of a base capability - if ($this->_baseCapabilities && $this->_baseCapabilities->hasEventManager()) { + if ($this->baseCapabilities && $this->baseCapabilities->hasEventManager()) { $onChange = function ($event) use ($eventManager) { $eventManager->trigger('change', $event->getTarget(), $event->getParams()); }; - $this->_baseCapabilities->getEventManager()->attach('change', $onChange); + $this->baseCapabilities->getEventManager()->attach('change', $onChange); } // register event manager - $this->_eventManager = $eventManager; + $this->eventManager = $eventManager; } - return $this->_eventManager; + return $this->eventManager; } /** @@ -168,7 +165,7 @@ public function getEventManager() */ public function getSupportedDatatypes() { - return $this->_getCapability('supportedDatatypes', array( + return $this->getCapability('supportedDatatypes', array( 'NULL' => false, 'boolean' => false, 'integer' => false, @@ -216,7 +213,7 @@ public function setSupportedDatatypes(\stdClass $marker, array $datatypes) $datatypes[type] = false; } - return $this->_setCapability($marker, 'supportedDatatypes', $datatypes); + return $this->setCapability($marker, 'supportedDatatypes', $datatypes); } /** @@ -226,7 +223,7 @@ public function setSupportedDatatypes(\stdClass $marker, array $datatypes) */ public function getSupportedMetadata() { - return $this->_getCapability('supportedMetadata', array()); + return $this->getCapability('supportedMetadata', array()); } /** @@ -243,7 +240,7 @@ public function setSupportedMetadata(\stdClass $marker, array $metadata) throw new InvalidArgumentException('$metadata must be an array of strings'); } } - return $this->_setCapability($marker, 'supportedMetadata', $metadata); + return $this->setCapability($marker, 'supportedMetadata', $metadata); } /** @@ -253,7 +250,7 @@ public function setSupportedMetadata(\stdClass $marker, array $metadata) */ public function getMaxTtl() { - return $this->_getCapability('maxTtl', 0); + return $this->getCapability('maxTtl', 0); } /** @@ -269,7 +266,7 @@ public function setMaxTtl(\stdClass $marker, $maxTtl) if ($maxTtl < 0) { throw new InvalidArgumentException('$maxTtl must be greater or equal 0'); } - return $this->_setCapability($marker, 'maxTtl', $maxTtl); + return $this->setCapability($marker, 'maxTtl', $maxTtl); } /** @@ -280,7 +277,7 @@ public function setMaxTtl(\stdClass $marker, $maxTtl) */ public function getStaticTtl() { - return $this->_getCapability('staticTtl', false); + return $this->getCapability('staticTtl', false); } /** @@ -293,7 +290,7 @@ public function getStaticTtl() */ public function setStaticTtl(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'staticTtl', (bool)$flag); + return $this->setCapability($marker, 'staticTtl', (bool)$flag); } /** @@ -303,7 +300,7 @@ public function setStaticTtl(\stdClass $marker, $flag) */ public function getTtlPrecision() { - return $this->_getCapability('ttlPrecision', 1); + return $this->getCapability('ttlPrecision', 1); } /** @@ -319,7 +316,7 @@ public function setTtlPrecision(\stdClass $marker, $ttlPrecision) if ($ttlPrecision <= 0) { throw new InvalidArgumentException('$ttlPrecision must be greater than 0'); } - return $this->_setCapability($marker, 'ttlPrecision', $ttlPrecision); + return $this->setCapability($marker, 'ttlPrecision', $ttlPrecision); } /** @@ -329,7 +326,7 @@ public function setTtlPrecision(\stdClass $marker, $ttlPrecision) */ public function getUseRequestTime() { - return $this->_getCapability('useRequestTime', false); + return $this->getCapability('useRequestTime', false); } /** @@ -341,7 +338,7 @@ public function getUseRequestTime() */ public function setUseRequestTime(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'useRequestTime', (bool)$flag); + return $this->setCapability($marker, 'useRequestTime', (bool)$flag); } /** @@ -351,7 +348,7 @@ public function setUseRequestTime(\stdClass $marker, $flag) */ public function getExpiredRead() { - return $this->_getCapability('expiredRead', false); + return $this->getCapability('expiredRead', false); } /** @@ -363,7 +360,7 @@ public function getExpiredRead() */ public function setExpiredRead(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'expiredRead', (bool)$flag); + return $this->setCapability($marker, 'expiredRead', (bool)$flag); } /** @@ -373,7 +370,7 @@ public function setExpiredRead(\stdClass $marker, $flag) */ public function getMaxKeyLength() { - return $this->_getCapability('maxKeyLength', -1); + return $this->getCapability('maxKeyLength', -1); } /** @@ -389,7 +386,7 @@ public function setMaxKeyLength(\stdClass $marker, $maxKeyLength) if ($maxKeyLength < -1) { throw new InvalidArgumentException('$maxKeyLength must be greater or equal than -1'); } - return $this->_setCapability($marker, 'maxKeyLength', $maxKeyLength); + return $this->setCapability($marker, 'maxKeyLength', $maxKeyLength); } /** @@ -399,7 +396,7 @@ public function setMaxKeyLength(\stdClass $marker, $maxKeyLength) */ public function getNamespaceIsPrefix() { - return $this->_getCapability('namespaceIsPrefix', true); + return $this->getCapability('namespaceIsPrefix', true); } /** @@ -411,7 +408,7 @@ public function getNamespaceIsPrefix() */ public function setNamespaceIsPrefix(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'namespaceIsPrefix', (bool)$flag); + return $this->setCapability($marker, 'namespaceIsPrefix', (bool)$flag); } /** @@ -421,7 +418,7 @@ public function setNamespaceIsPrefix(\stdClass $marker, $flag) */ public function getNamespaceSeparator() { - return $this->_getCapability('namespaceSeparator', ''); + return $this->getCapability('namespaceSeparator', ''); } /** @@ -433,7 +430,7 @@ public function getNamespaceSeparator() */ public function setNamespaceSeparator(\stdClass $marker, $separator) { - return $this->_setCapability($marker, 'namespaceSeparator', (string)$separator); + return $this->setCapability($marker, 'namespaceSeparator', (string)$separator); } /** @@ -443,7 +440,7 @@ public function setNamespaceSeparator(\stdClass $marker, $separator) */ public function getIterable() { - return $this->_getCapability('iterable', false); + return $this->getCapability('iterable', false); } /** @@ -455,7 +452,7 @@ public function getIterable() */ public function setIterable(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'iterable', (bool)$flag); + return $this->setCapability($marker, 'iterable', (bool)$flag); } /** @@ -465,7 +462,7 @@ public function setIterable(\stdClass $marker, $flag) */ public function getClearAllNamespaces() { - return $this->_getCapability('clearAllNamespaces', false); + return $this->getCapability('clearAllNamespaces', false); } /** @@ -477,7 +474,7 @@ public function getClearAllNamespaces() */ public function setClearAllNamespaces(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'clearAllNamespaces', (bool)$flag); + return $this->setCapability($marker, 'clearAllNamespaces', (bool)$flag); } /** @@ -487,7 +484,7 @@ public function setClearAllNamespaces(\stdClass $marker, $flag) */ public function getClearByNamespace() { - return $this->_getCapability('clearByNamespace', false); + return $this->getCapability('clearByNamespace', false); } /** @@ -499,7 +496,7 @@ public function getClearByNamespace() */ public function setClearByNamespace(\stdClass $marker, $flag) { - return $this->_setCapability($marker, 'clearByNamespace', (bool)$flag); + return $this->setCapability($marker, 'clearByNamespace', (bool)$flag); } /** @@ -509,14 +506,14 @@ public function setClearByNamespace(\stdClass $marker, $flag) * @param mixed $default * @return mixed */ - protected function _getCapability($name, $default = null) + protected function getCapability($name, $default = null) { $property = '_' . $name; if ($this->$property !== null) { return $this->$property; - } elseif ($this->_baseCapabilities) { + } elseif ($this->baseCapabilities) { $getMethod = 'get' . $name; - return $this->_baseCapabilities->$getMethod(); + return $this->baseCapabilities->$getMethod(); } return $default; } @@ -530,9 +527,9 @@ protected function _getCapability($name, $default = null) * @return Zend\Cache\Storage\Capabilities Fluent interface * @throws InvalidArgumentException */ - protected function _setCapability(\stdClass $marker, $name, $value) + protected function setCapability(\stdClass $marker, $name, $value) { - if ($this->_marker !== $marker) { + if ($this->marker !== $marker) { throw new InvalidArgumentException('Invalid marker'); } From 5e867626cba984b38f417606786acf4f0d292649 Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Sat, 10 Dec 2011 23:06:47 +0100 Subject: [PATCH 131/311] Plugins have fluent interface --- src/Storage/Plugin/ClearByFactor.php | 3 ++- src/Storage/Plugin/ExceptionHandler.php | 3 ++- src/Storage/Plugin/OptimizeByFactor.php | 3 ++- src/Storage/Plugin/Serializer.php | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 57aa82c76..6972dd7b7 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -47,7 +47,7 @@ public function __construct($options = array()) * Set options * * @param array|\Traversable $options - * @return void + * @return ClearByFactor */ public function setOptions($options) { @@ -55,6 +55,7 @@ public function setOptions($options) $m = 'set' . str_replace('_', '', $name); $this->$m($value); } + return $this; } /** diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index d5ef49d71..b2d37bb7b 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -36,7 +36,7 @@ public function __construct($options = array()) * Set options * * @param array|\Traversable $options - * @return void + * @return ExceptionHandler */ public function setOptions($options) { @@ -44,6 +44,7 @@ public function setOptions($options) $m = 'set' . str_replace('_', '', $name); $this->$m($value); } + return $this; } /** diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index c042ca183..c74fc4c3a 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -40,7 +40,7 @@ public function __construct($options = array()) * Set options * * @param array|\Traversable $options - * @return void + * @return OptimizeByFactor */ public function setOptions($options) { @@ -48,6 +48,7 @@ public function setOptions($options) $m = 'set' . str_replace('_', '', $name); $this->$m($value); } + return $this; } /** diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 6e643c484..43bc1ce10 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -49,7 +49,7 @@ public function __construct($options = array()) * Set options * * @param array|\Traversable $options - * @return void + * @return Serializer */ public function setOptions($options) { @@ -57,6 +57,7 @@ public function setOptions($options) $m = 'set' . $name; $this->$m($value); } + return $this; } /** From 14177971d6a34233f2d02adba188fc685659d1f4 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 19:33:25 +0100 Subject: [PATCH 132/311] phpdoc --- src/PatternBroker.php | 7 +++---- src/PatternLoader.php | 3 +-- src/Storage/AdapterBroker.php | 7 +++---- src/Storage/Event.php | 10 +++++----- src/Storage/ExceptionEvent.php | 6 ++++-- src/Storage/PostEvent.php | 4 ++-- src/StorageFactory.php | 6 +++++- src/Utils.php | 12 ++++++------ 8 files changed, 29 insertions(+), 26 deletions(-) diff --git a/src/PatternBroker.php b/src/PatternBroker.php index e47f5035f..734d7fdf4 100644 --- a/src/PatternBroker.php +++ b/src/PatternBroker.php @@ -19,7 +19,6 @@ */ namespace Zend\Cache; - use Zend\Loader\PluginBroker, Zend\Cache\Exception\RuntimeException; @@ -40,10 +39,10 @@ class PatternBroker extends PluginBroker /** * Determine if we have a valid pattern - * - * @param mixed $plugin + * + * @param mixed $plugin * @return true - * @throws Exception + * @throws RuntimeException */ protected function validatePlugin($plugin) { diff --git a/src/PatternLoader.php b/src/PatternLoader.php index 62885c1f2..a49212ea9 100644 --- a/src/PatternLoader.php +++ b/src/PatternLoader.php @@ -19,7 +19,6 @@ */ namespace Zend\Cache; - use Zend\Loader\PluginClassLoader; /** @@ -33,7 +32,7 @@ class PatternLoader extends PluginClassLoader { /** - * @var array Pre-aliased adapters + * @var array Pre-aliased adapters */ protected $plugins = array( 'callback' => 'Zend\Cache\Pattern\CallbackCache', diff --git a/src/Storage/AdapterBroker.php b/src/Storage/AdapterBroker.php index 7352e1fcf..c81a6f91f 100644 --- a/src/Storage/AdapterBroker.php +++ b/src/Storage/AdapterBroker.php @@ -19,7 +19,6 @@ */ namespace Zend\Cache\Storage; - use Zend\Loader\PluginBroker, Zend\Cache\Exception\RuntimeException; @@ -40,10 +39,10 @@ class AdapterBroker extends PluginBroker /** * Determine if we have a valid adapter - * - * @param mixed $plugin + * + * @param mixed $plugin * @return true - * @throws Exception + * @throws RuntimeException */ protected function validatePlugin($plugin) { diff --git a/src/Storage/Event.php b/src/Storage/Event.php index 1510cf04c..43d5045f3 100644 --- a/src/Storage/Event.php +++ b/src/Storage/Event.php @@ -26,8 +26,8 @@ public function __construct($name, Adapter $storage, ArrayObject $params) /** * Set the event target/context * - * @param Zend\Cache\Storage\Adapter $target - * @return Zend\Cache\Storage\Event + * @param Adapter $target + * @return Event * @see Zend\EventManager\Event::setTarget() */ public function setTarget($target) @@ -38,8 +38,8 @@ public function setTarget($target) /** * Alias of setTarget * - * @param Zend\Cache\Storage\Adapter $adapter - * @return Zend\Cache\Storage\Event + * @param Adapter $adapter + * @return Event * @see Zend\EventManager\Event::setTarget() */ public function setStorage(Adapter $adapter) @@ -51,7 +51,7 @@ public function setStorage(Adapter $adapter) /** * Alias of getTarget * - * @return Zend\Cache\Storage\Adapter + * @return Adapter */ public function getStorage() { diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index c5cccbfda..50883344c 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -35,7 +35,7 @@ class ExceptionEvent extends Event * Accept a target and its parameters. * * @param string $name Event name - * @param Zend\Cache\Storage\Adapter $storage + * @param Adapter $storage * @param ArrayObject $params * @param Exception $exception * @return void @@ -50,6 +50,7 @@ public function __construct($name, Adapter $storage, ArrayObject $params, Except * Set the exception to be throw * * @param Exception $exception + * @return ExceptionEvent */ public function setException(Exception $exception) { @@ -71,6 +72,7 @@ public function getException() * Throw the exception or use the result * * @param boolean $flag + * @return ExceptionEvent */ public function setThrowException($flag) { @@ -92,7 +94,7 @@ public function getThrowException() * Set the result/return value * * @param mixed $value - * @return Zend\Cache\Storage\PostEvent + * @return ExceptionEvent */ public function setResult(&$value) { diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index 7a08b3896..1a17e1f5f 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -19,7 +19,7 @@ class PostEvent extends Event * Accept a target and its parameters. * * @param string $name Event name - * @param Zend\Cache\Storage\Adapter $storage + * @param Adapter $storage * @param ArrayObject $params * @param mixed $result * @return void @@ -34,7 +34,7 @@ public function __construct($name, Adapter $storage, ArrayObject $params, &$resu * Set the result/return value * * @param mixed $value - * @return Zend\Cache\Storage\PostEvent + * @return PostEvent */ public function setResult(&$value) { diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 923ec9178..b61dc7a86 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -28,7 +28,7 @@ class StorageFactory * * @param array|\Zend\Config $cfg * @return Zend\Cache\Storage\Adapter - * @throws Zend\Cache\RuntimeException + * @throws InvalidArgumentException */ public static function factory($cfg) { @@ -157,6 +157,8 @@ public static function setAdapterBroker(Broker $broker) /** * Resets the internal adapter broker + * + * @return void */ public static function resetAdapterBroker() { @@ -208,6 +210,8 @@ public static function setPluginBroker(Broker $broker) /** * Resets the internal plugin broker + * + * @return void */ public static function resetPluginBroker() { diff --git a/src/Utils.php b/src/Utils.php index 8257eaca6..3b29231b2 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -11,7 +11,7 @@ class Utils * * @param string $path A directory of the filesystem or disk partition * @return array - * @throws Zend\Cache\Exception\RuntimeException + * @throws RuntimeException */ static public function getDiskCapacity($path) { @@ -37,7 +37,7 @@ static public function getDiskCapacity($path) * Get php memory capacity * * @return array - * @throws Zend\Cache\Exception\RuntimeException + * @throws RuntimeException */ static public function getPhpMemoryCapacity() { @@ -59,7 +59,7 @@ static public function getPhpMemoryCapacity() * Get system memory capacity * * @return array - * @throws Zend\Cache\Exception\RuntimeException + * @throws RuntimeException */ static public function getSystemMemoryCapacity() { @@ -105,7 +105,7 @@ static public function getSystemMemoryCapacity() * Get system memory capacity on windows systems * * @return array - * @throws Zend\Cache\Exception\RuntimeException + * @throws RuntimeException */ static protected function _getSystemMemoryCapacityWin() { @@ -160,7 +160,7 @@ static protected function _getSystemMemoryCapacityWin() * @param string $data Message to be hashed. * @param bool $raw When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits. * @return string Hash value - * @throws Zend\Cache\RuntimeException + * @throws RuntimeException */ static public function generateHash($algo, $data, $raw = false) { @@ -199,7 +199,7 @@ static public function getHashAlgos() * * @param string $memStr * @return float - * @throws Zend\Cache\Exception\RuntimeException + * @throws RuntimeException */ static protected function bytesFromString($memStr) { From 7a8ecbeec62d66bd592a747e585e514569e587ff Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 20:10:28 +0100 Subject: [PATCH 133/311] - added CommonPluginTest - moved CommonStorageTest into CommonAdapterTest & CommonPluginTest - removed CommonStorageTest - fixed issues identified by CommonPluginTest --- src/Storage/Plugin/ExceptionHandler.php | 23 ++- test/Storage/Adapter/AbstractAdapterTest.php | 12 +- test/Storage/Adapter/CommonAdapterTest.php | 136 ++++++++++++++- test/Storage/CommonStorageTest.php | 169 ------------------- test/Storage/Plugin/ClearByFactorTest.php | 11 +- test/Storage/Plugin/CommonPluginTest.php | 105 ++++++++++++ test/Storage/Plugin/ExceptionHandlerTest.php | 11 +- test/Storage/Plugin/OptimizeByFactorTest.php | 9 +- test/Storage/Plugin/SerializerTest.php | 9 +- 9 files changed, 271 insertions(+), 214 deletions(-) delete mode 100644 test/Storage/CommonStorageTest.php create mode 100644 test/Storage/Plugin/CommonPluginTest.php diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index b2d37bb7b..303947885 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -21,6 +21,13 @@ class ExceptionHandler implements Plugin */ protected $_throwExceptions = true; + /** + * Handles + * + * @var array + */ + protected $handles = array(); + /** * Constructor * @@ -54,24 +61,26 @@ public function setOptions($options) */ public function getOptions() { - $options = parent::getOptions(); - $options['callback'] = $this->getExceptionHandler(); - $options['throw_exceptions'] = $this->getThrowExceptions(); - return $options; + return array( + 'callback' => $this->getCallback(), + 'throw_exceptions' => $this->getThrowExceptions(), + ); } /** * Set callback * - * @param $callback + * @param null|callback $callback + * @return ExceptionHandler * @throws InvalidArgumentException */ public function setCallback($callback) { - if (!is_callable($callback, true)) { + if ($callback !== null && !is_callable($callback, true)) { throw new InvalidArgumentException('Not a valid callback'); } $this->_callback = $callback; + return $this; } /** @@ -86,11 +95,13 @@ public function getCallback() * Set throw exceptions * * @param bool $flag + * @return ExceptionHandler * @return void */ public function setThrowExceptions($flag) { $this->_throwExceptions = (bool)$flag; + return $this; } /** diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 6e37c5060..4c9c1d546 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -21,8 +21,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; -use ZendTest\Cache\Storage\CommonStorageTest, - Zend\Cache, +use Zend\Cache, Zend\Cache\Exception\RuntimeException; /** @@ -33,9 +32,16 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class AbstractAdapterTest extends CommonStorageTest +class AbstractAdapterTest extends \PHPUnit_Framework_TestCase { + /** + * Mock of the abstract storage adapter + * + * @var Zend\Cache\Storage\Adapter\AbstractAdapter + */ + protected $_storage; + public function setUp() { $this->_storage = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 379ca22bd..28de77610 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -21,8 +21,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; -use ZendTest\Cache\Storage\CommonStorageTest, - Zend\Cache\Storage\Adapter, +use Zend\Cache\Storage\Adapter, Zend\Cache; /** @@ -37,12 +36,45 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -abstract class CommonAdapterTest extends CommonStorageTest +abstract class CommonAdapterTest extends \PHPUnit_Framework_TestCase { + /** + * The storage adapter + * + * @var Zend\Cache\Storage\Adapter + */ + protected $_storage; + + /** + * All datatypes of PHP + * + * @var string[] + */ + protected $_phpDatatypes = array( + 'NULL', 'boolean', 'integer', 'double', + 'string', 'array', 'object', 'resource' + ); + public function setUp() { - parent::setUp(); + $this->assertInstanceOf( + 'Zend\Cache\Storage\Adapter', + $this->_storage, + 'Storage adapter instance is needed for tests' + ); + } + + public function testOptionNamesValid() + { + $options = $this->_storage->getOptions(); + foreach ($options as $name => $value) { + $this->assertRegExp( + '/^[a-z]+[a-z0-9_]*[a-z0-9]+$/', + $name, + "Invalid option name '{$name}'" + ); + } } public function testGettersAndSettersOfOptionsExists() @@ -64,6 +96,102 @@ public function testGettersAndSettersOfOptionsExists() } } + public function testOptionsGetAndSetDefault() + { + $options = $this->_storage->getOptions(); + $this->_storage->setOptions($options); + $this->assertEquals($options, $this->_storage->getOptions()); + } + + public function testOptionsFluentInterface() + { + $options = $this->_storage->getOptions(); + foreach ($options as $option => $value) { + $method = ucwords(str_replace('_', ' ', $option)); + $method = 'set' . str_replace(' ', '', $method); + $this->assertSame( + $this->_storage, + $this->_storage->{$method}($value), + "Method '{$method}' doesn't implement the fluent interface" + ); + } + + $this->assertSame( + $this->_storage, + $this->_storage->setOptions(array()), + "Method 'setOptions' doesn't implement the fluent interface" + ); + } + + public function testGetCapabilities() + { + $capabilities = $this->_storage->getCapabilities(); + $this->assertInstanceOf('Zend\Cache\Storage\Capabilities', $capabilities); + } + + public function testDatatypesCapability() + { + $capabilities = $this->_storage->getCapabilities(); + $datatypes = $capabilities->getSupportedDatatypes(); + $this->assertInternalType('array', $datatypes); + + foreach ($datatypes as $sourceType => $targetType) { + $this->assertContains( + $sourceType, $this->_phpDatatypes, + "Unknown source type '{$sourceType}'" + ); + if (is_string($targetType)) { + $this->assertContains( + $targetType, $this->_phpDatatypes, + "Unknown target type '{$targetType}'" + ); + } else { + $this->assertInternalType( + 'bool', $targetType, + "Target type must be a string or boolean" + ); + } + } + } + + public function testSupportedMetadataCapability() + { + $capabilities = $this->_storage->getCapabilities(); + $metadata = $capabilities->getSupportedMetadata(); + $this->assertInternalType('array', $metadata); + + foreach ($metadata as $property) { + $this->assertInternalType('string', $property); + } + } + + public function testTtlCapabilities() + { + $capabilities = $this->_storage->getCapabilities(); + + $this->assertInternalType('integer', $capabilities->getMaxTtl()); + $this->assertGreaterThanOrEqual(0, $capabilities->getMaxTtl()); + + $this->assertInternalType('bool', $capabilities->getStaticTtl()); + + $this->assertInternalType('numeric', $capabilities->getTtlPrecision()); + $this->assertGreaterThan(0, $capabilities->getTtlPrecision()); + + $this->assertInternalType('bool', $capabilities->getExpiredRead()); + } + + public function testKeyCapabilities() + { + $capabilities = $this->_storage->getCapabilities(); + + $this->assertInternalType('integer', $capabilities->getMaxKeyLength()); + $this->assertGreaterThanOrEqual(-1, $capabilities->getMaxKeyLength()); + + $this->assertInternalType('bool', $capabilities->getNamespaceIsPrefix()); + + $this->assertInternalType('string', $capabilities->getNamespaceSeparator()); + } + public function testGetItemReturnsFalseIfIgnoreMissingItemsEnabled() { $this->_storage->setIgnoreMissingItems(true); diff --git a/test/Storage/CommonStorageTest.php b/test/Storage/CommonStorageTest.php deleted file mode 100644 index 418e22a7b..000000000 --- a/test/Storage/CommonStorageTest.php +++ /dev/null @@ -1,169 +0,0 @@ -assertInstanceOf( - 'Zend\Cache\Storage\Adapter', - $this->_storage, - 'Internal storage instance is needed for tests' - ); - } - - public function testGetCapabilities() - { - $capabilities = $this->_storage->getCapabilities(); - $this->assertInstanceOf('Zend\Cache\Storage\Capabilities', $capabilities); - } - - public function testDatatypesCapability() - { - $capabilities = $this->_storage->getCapabilities(); - $datatypes = $capabilities->getSupportedDatatypes(); - $this->assertInternalType('array', $datatypes); - - foreach ($datatypes as $sourceType => $targetType) { - $this->assertContains( - $sourceType, $this->_phpDatatypes, - "Unknown source type '{$sourceType}'" - ); - if (is_string($targetType)) { - $this->assertContains( - $targetType, $this->_phpDatatypes, - "Unknown target type '{$targetType}'" - ); - } else { - $this->assertInternalType( - 'bool', $targetType, - "Target type must be a string or boolean" - ); - } - } - } - - public function testSupportedMetadataCapability() - { - $capabilities = $this->_storage->getCapabilities(); - $metadata = $capabilities->getSupportedMetadata(); - $this->assertInternalType('array', $metadata); - - foreach ($metadata as $property) { - $this->assertInternalType('string', $property); - } - } - - public function testTtlCapabilities() - { - $capabilities = $this->_storage->getCapabilities(); - - $this->assertInternalType('integer', $capabilities->getMaxTtl()); - $this->assertGreaterThanOrEqual(0, $capabilities->getMaxTtl()); - - $this->assertInternalType('bool', $capabilities->getStaticTtl()); - - $this->assertInternalType('numeric', $capabilities->getTtlPrecision()); - $this->assertGreaterThan(0, $capabilities->getTtlPrecision()); - - $this->assertInternalType('bool', $capabilities->getExpiredRead()); - } - - public function testKeyCapabilities() - { - $capabilities = $this->_storage->getCapabilities(); - - $this->assertInternalType('integer', $capabilities->getMaxKeyLength()); - $this->assertGreaterThanOrEqual(-1, $capabilities->getMaxKeyLength()); - - $this->assertInternalType('bool', $capabilities->getNamespaceIsPrefix()); - - $this->assertInternalType('string', $capabilities->getNamespaceSeparator()); - } - - public function testOptionNamesValid() - { - $options = $this->_storage->getOptions(); - foreach ($options as $name => $value) { - $this->assertRegExp( - '/^[a-z]*[a-z0-9_]*[a-z0-9]*$/', - $name, - "Invalid option name '{$name}'" - ); - } - } - - public function testOptionsGetAndSetDefault() - { - $options = $this->_storage->getOptions(); - $this->_storage->setOptions($options); - $this->assertEquals($options, $this->_storage->getOptions()); - } - - public function testOptionsFluentInterface() - { - $options = $this->_storage->getOptions(); - foreach ($options as $option => $value) { - $method = ucwords(str_replace('_', ' ', $option)); - $method = 'set' . str_replace(' ', '', $method); - $this->assertSame( - $this->_storage, - $this->_storage->{$method}($value), - "Method '{$method}' doesn't implement the fluent interface" - ); - } - - $this->assertSame( - $this->_storage, - $this->_storage->setOptions(array()), - "Method 'setOptions' doesn't implement the fluent interface" - ); - } - -} diff --git a/test/Storage/Plugin/ClearByFactorTest.php b/test/Storage/Plugin/ClearByFactorTest.php index 7945d7966..4912e630a 100644 --- a/test/Storage/Plugin/ClearByFactorTest.php +++ b/test/Storage/Plugin/ClearByFactorTest.php @@ -6,7 +6,7 @@ ZendTest\Cache\Storage\TestAsset\MockAdapter, ArrayObject; -class ClearByFactorTest extends \PHPUnit_Framework_TestCase +class ClearByFactorTest extends CommonPluginTest { /** @@ -16,19 +16,14 @@ class ClearByFactorTest extends \PHPUnit_Framework_TestCase */ protected $_adapter; - /** - * The serializer plugin - * - * @var Zend\Cache\Storage\Plugin\OptimizeByFactor - */ - protected $_plugin; - public function setUp() { $this->_adapter = new MockAdapter(); $this->_plugin = new Cache\Storage\Plugin\ClearByFactor(array( 'clearing_factor' => 1, )); + + parent::setUp(); } public function testAddPlugin() diff --git a/test/Storage/Plugin/CommonPluginTest.php b/test/Storage/Plugin/CommonPluginTest.php new file mode 100644 index 000000000..34c5f66d9 --- /dev/null +++ b/test/Storage/Plugin/CommonPluginTest.php @@ -0,0 +1,105 @@ +_plugin->getOptions(); + foreach ($options as $name => $value) { + $this->assertRegExp( + '/^[a-z]+[a-z0-9_]*[a-z0-9]+$/', + $name, + "Invalid option name '{$name}'" + ); + } + } + + public function testGettersAndSettersOfOptionsExists() + { + $options = $this->_plugin->getOptions(); + foreach ($options as $option => $value) { + $method = ucwords(str_replace('_', ' ', $option)); + $method = str_replace(' ', '', $method); + + $this->assertTrue( + method_exists($this->_plugin, 'set' . $method), + "Missing method 'set'{$method}" + ); + + $this->assertTrue( + method_exists($this->_plugin, 'get' . $method), + "Missing method 'get'{$method}" + ); + } + } + + public function testOptionsGetAndSetDefault() + { + $options = $this->_plugin->getOptions(); + $this->_plugin->setOptions($options); + $this->assertEquals($options, $this->_plugin->getOptions()); + } + + public function testOptionsFluentInterface() + { + $options = $this->_plugin->getOptions(); + foreach ($options as $option => $value) { + $method = ucwords(str_replace('_', ' ', $option)); + $method = 'set' . str_replace(' ', '', $method); + $this->assertSame( + $this->_plugin, + $this->_plugin->{$method}($value), + "Method '{$method}' doesn't implement the fluent interface" + ); + } + + $this->assertSame( + $this->_plugin, + $this->_plugin->setOptions(array()), + "Method 'setOptions' doesn't implement the fluent interface" + ); + } + +} diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php index 6263db0a5..17b0cd182 100644 --- a/test/Storage/Plugin/ExceptionHandlerTest.php +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -6,7 +6,7 @@ ZendTest\Cache\Storage\TestAsset\MockAdapter, ArrayObject; -class ExceptionHandlerTest extends \PHPUnit_Framework_TestCase +class ExceptionHandlerTest extends CommonPluginTest { /** @@ -16,17 +16,12 @@ class ExceptionHandlerTest extends \PHPUnit_Framework_TestCase */ protected $_adapter; - /** - * The serializer plugin - * - * @var Zend\Cache\Storage\Plugin\OptimizeByFactor - */ - protected $_plugin; - public function setUp() { $this->_adapter = new MockAdapter(); $this->_plugin = new Cache\Storage\Plugin\ExceptionHandler(); + + parent::setUp(); } public function testAddPlugin() diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index c70a55505..4e90026f6 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -6,7 +6,7 @@ ZendTest\Cache\Storage\TestAsset\MockAdapter, ArrayObject; -class OptimizeByFactorTest extends \PHPUnit_Framework_TestCase +class OptimizeByFactorTest extends CommonPluginTest { /** @@ -16,13 +16,6 @@ class OptimizeByFactorTest extends \PHPUnit_Framework_TestCase */ protected $_adapter; - /** - * The serializer plugin - * - * @var Zend\Cache\Storage\Plugin\OptimizeByFactor - */ - protected $_plugin; - public function setUp() { $this->_adapter = new MockAdapter(); diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index 561dc805e..20c044dfe 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -35,7 +35,7 @@ * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ -class SerializerTest extends \PHPUnit_Framework_TestCase +class SerializerTest extends CommonPluginTest { /** @@ -45,13 +45,6 @@ class SerializerTest extends \PHPUnit_Framework_TestCase */ protected $_adapter; - /** - * The serializer plugin - * - * @var Zend\Cache\Storage\Plugin\Serializer - */ - protected $_plugin; - public function setUp() { $this->_adapter = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); From edbb3678a624bb82c9938cccfcd23ba7ee147cfd Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 10 Dec 2011 20:15:09 +0100 Subject: [PATCH 134/311] removed undescores of protected members ob plugins --- src/Storage/Plugin/ClearByFactor.php | 12 ++++++------ src/Storage/Plugin/ExceptionHandler.php | 12 ++++++------ src/Storage/Plugin/OptimizeByFactor.php | 6 +++--- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 6972dd7b7..d0a6fd439 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -16,14 +16,14 @@ class ClearByFactor implements Plugin * * @var int */ - protected $_clearingFactor = 0; + protected $clearingFactor = 0; /** * Flag to clear items by namespace * * @var boolean */ - protected $_clearByNamespace = true; + protected $clearByNamespace = true; /** * Handles @@ -78,7 +78,7 @@ public function getOptions() */ public function getClearingFactor() { - return $this->_clearingFactor; + return $this->clearingFactor; } /** @@ -94,7 +94,7 @@ public function setClearingFactor($factor) if ($factor < 0) { throw new InvalidArgumentAxception("Invalid clearing factor '{$factor}': must be greater or equal 0"); } - $this->_clearingFactor = $factor; + $this->clearingFactor = $factor; return $this; } @@ -106,7 +106,7 @@ public function setClearingFactor($factor) */ public function getClearByNamespace() { - return $this->_clearByNamespace; + return $this->clearByNamespace; } /** @@ -117,7 +117,7 @@ public function getClearByNamespace() */ public function setClearByNamespace($flag) { - $this->_clearByNamespace = $flag; + $this->clearByNamespace = $flag; return $this; } diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 303947885..9bc5fde6c 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -12,14 +12,14 @@ class ExceptionHandler implements Plugin /** * Callback */ - protected $_callback = null; + protected $callback = null; /** * Throw exceptions * * @var bool */ - protected $_throwExceptions = true; + protected $throwExceptions = true; /** * Handles @@ -79,7 +79,7 @@ public function setCallback($callback) if ($callback !== null && !is_callable($callback, true)) { throw new InvalidArgumentException('Not a valid callback'); } - $this->_callback = $callback; + $this->callback = $callback; return $this; } @@ -88,7 +88,7 @@ public function setCallback($callback) */ public function getCallback() { - return $this->_callback; + return $this->callback; } /** @@ -100,7 +100,7 @@ public function getCallback() */ public function setThrowExceptions($flag) { - $this->_throwExceptions = (bool)$flag; + $this->throwExceptions = (bool)$flag; return $this; } @@ -111,7 +111,7 @@ public function setThrowExceptions($flag) */ public function getThrowExceptions() { - return $this->_throwExceptions; + return $this->throwExceptions; } /** diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index c74fc4c3a..7e12d7960 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -23,7 +23,7 @@ class OptimizeByFactor implements Plugin * * @var int */ - protected $_optimizingFactor = 0; + protected $optimizingFactor = 0; /** * Constructor @@ -70,7 +70,7 @@ public function getOptions() */ public function getOptimizingFactor() { - return $this->_optimizingFactor; + return $this->optimizingFactor; } /** @@ -86,7 +86,7 @@ public function setOptimizingFactor($factor) if ($factor < 0) { throw new InvalidArgumentAxception("Invalid optimizing factor '{$factor}': must be greater or equal 0"); } - $this->_optimizingFactor = $factor; + $this->optimizingFactor = $factor; return $this; } From 8d1e6235938b4b2076c08a2772b71bf7181e2f2b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 11 Dec 2011 20:51:57 +0100 Subject: [PATCH 135/311] - added apc iterator TODO: trigger events --- src/Storage/Adapter/Apc.php | 741 +++++++++++++++++++++++++++++++ test/Storage/Adapter/ApcTest.php | 88 ++++ 2 files changed, 829 insertions(+) create mode 100644 src/Storage/Adapter/Apc.php create mode 100644 test/Storage/Adapter/ApcTest.php diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php new file mode 100644 index 000000000..246585f07 --- /dev/null +++ b/src/Storage/Adapter/Apc.php @@ -0,0 +1,741 @@ + 0) { + throw new ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); + } + + $enabled = ini_get('apc.enabled'); + if (PHP_SAPI == 'cli') { + $enabled = $enabled && (bool)ini_get('apc.enable_cli'); + } + if (!$enabled) { + throw new ExtensionNotLoadedException( + "ext/apc is disabled - see 'apc.enabled' and 'apc.enable_cli'" + ); + } + + // init select map + if (self::$selectMap === null) { + self::$selectMap = array( + // 'key' => \APC_ITER_KEY, + 'value' => \APC_ITER_VALUE, + 'mtime' => \APC_ITER_MTIME, + 'ctime' => \APC_ITER_CTIME, + 'atime' => \APC_ITER_ATIME, + 'rtime' => \APC_ITER_DTIME, + 'ttl' => \APC_ITER_TTL, + 'num_hits' => \APC_ITER_NUM_HITS, + 'ref_count' => \APC_ITER_REFCOUNT, + 'mem_size' => \APC_ITER_MEM_SIZE, + + // virtual keys + 'internal_key' => \APC_ITER_KEY, + ); + } + + parent::__construct($options); + } + + /* options */ + + public function setNamespaceSeparator($separator) + { + $this->namespaceSeparator = (string)$separator; + return $this; + } + + public function getNamespaceSeparator() + { + return $this->namespaceSeparator; + } + + /* reading */ + + public function getItem($key, array $options = array()) + { + if (!$this->getReadable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + $value = apc_fetch($key, $success); + if (!$success) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found"); + } + return false; + } + + if (array_key_exists('token', $options)) { + $options['token'] = $value; + } + + return $value; + } + + public function getItems(array $keys, array $options = array()) + { + if (!$this->getReadable()) { + return array(); + } + + $this->normalizeOptions($options); + foreach ($keys as &$key) { + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + } + + $ret = apc_fetch($keys); + + if (!$options['ignore_missing_items']) { + if (count($keys) != count($ret)) { + $missing = implode("', '", array_diff($keys, array_keys($ret))); + throw new ItemNotFoundException('Keys not found: ' . $missing); + } + } + + // remove namespace prefix + $nsl = strlen($options['namespace']); + $ret2 = array(); + foreach ($ret as $key => &$value) { + $ret2[ substr($key, $nsl+1) ] = $value; + } + + return $ret2; + } + + public function hasItem($key, array $options = array()) + { + if (!$this->getReadable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + return apc_exists($key); + } + + public function hasItems(array $keys, array $options = array()) + { + if (!$this->getReadable()) { + return array(); + } + + $this->normalizeOptions($options); + foreach ($keys as &$key) { + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + } + + return apc_exists($keys); + } + + public function getMetadata($key, array $options = array()) + { + if (!$this->getReadable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + $regexp = '/^' . preg_quote($key, '/') . '$/'; + $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $metadata = $it->current(); + + // @see http://pecl.php.net/bugs/bug.php?id=22564 + if (!apc_exists($key)) { + $metadata = false; + } + + if (!$metadata) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException( + "Key '{$key}' nout found" + ); + } + + return false; + } + + $this->normalizeMetadata($metadata); + return $metadata; + } + + public function getMetadatas(array $keys, array $options = array()) + { + if (!$this->getReadable()) { + return array(); + } + + $this->normalizeOptions($options); + $nsl = strlen($options['namespace']); + + $keysRegExp = array(); + foreach ($keys as &$key) { + $keysRegExp[] = preg_quote($options['namespace'] . $this->getNamespaceSeparator() . $key, '/'); + } + $regexp = '/^(' . implode('|', $keysRegExp) . ')$/'; + + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + + $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $ret = array(); + foreach ($it as $internalKey => $metadata) { + // @see http://pecl.php.net/bugs/bug.php?id=22564 + if (!apc_exists($internalKey)) { + continue; + } + + $this->normalizeMetadata($metadata); + $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); + $ret[$key] = & $metadata; + } + + if (!$options['ignore_missing_items']) { + if (count($keys) != count($ret)) { + $missing = implode("', '", array_diff($keys, array_keys($ret))); + throw new ItemNotFoundException('Keys not found: ' . $missing); + } + } + + return $ret; + } + + /* writing */ + + public function setItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + if (!apc_store($key, $value, $options['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); + } + + return true; + } + + public function setItems(array $keyValuePairs, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + + $keyValuePairs2 = array(); + foreach ($keyValuePairs as $key => &$value) { + $keyValuePairs2[ $options['namespace'] . $this->getNamespaceSeparator() . $key ] = &$value; + } + + $errKeys = apc_store($keyValuePairs2, null, $options['ttl']); + + if ($errKeys) { + throw new RuntimeException( + "apc_store(, null, {$options['ttl']}) failed for keys: " + . "'" . implode("','", $errKeys) . "'" + ); + } + + return true; + } + + public function addItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + if (!apc_add($key, $value, $options['ttl'])) { + if (apc_exists($key)) { + throw new RuntimeException("Key '{$key}' already exists"); + } + + $type = is_object($value) ? get_class($value) : gettype($value); + throw new RuntimeException("apc_add('{$key}', <{$type}>, {$options['ttl']}) failed"); + } + + return true; + } + + public function addItems(array $keyValuePairs, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + + $keyValuePairs2 = array(); + foreach ($keyValuePairs as $key => &$value) { + $keyValuePairs2[ $options['namespace'] . $this->getNamespaceSeparator() . $key ] = &$value; + } + + $errKeys = apc_add($keyValuePairs2, null, $options['ttl']); + + if ($errKeys) { + throw new RuntimeException( + "apc_add(, null, {$options['ttl']}) failed for keys: " + . "'" . implode("','", $errKeys) . "'" + ); + } + + return true; + } + + public function replaceItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + if (!apc_exists($key)) { + throw new ItemNotFoundException("Key '{$key}' doesn't exist"); + } + + if (!apc_store($key, $value, $options['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); + } + + return true; + } + + public function removeItem($key, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + if (!apc_delete($key)) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found"); + } + } + + return true; + } + + public function removeItems(array $keys, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + foreach ($keys as &$key) { + $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + } + + $errKeys = apc_delete($keys); + if ($errKeys) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); + } + } + + return true; + } + + public function incrementItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + $value = (int)$value; + $newValue = apc_inc($internalKey, $value); + if ($newValue === false) { + if (!apc_exists($internalKey)) { + if ($options['ignore_missing_items']) { + $this->addItem($key, $value, $options); + $newValue = $value; + } else { + throw new ItemNotFoundException( + "Key '{$internalKey}' not found" + ); + } + } else { + throw new RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + } + } + + return $newValue; + } + + public function decrementItem($key, $value, array $options = array()) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + + $value = (int)$value; + $newValue = apc_dec($internalKey, $value); + if ($newValue === false) { + if (!apc_exists($internalKey)) { + if ($options['ignore_missing_items']) { + $this->addItem($key, -$value, $options); + $newValue = -$value; + } else { + throw new ItemNotFoundException( + "Key '{$internalKey}' not found" + ); + } + } else { + throw new RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + } + } + + return $newValue; + } + + /* non-blocking */ + + public function getDelayed(array $keys, array $options = array()) + { + if ($this->stmtActive) { + throw new RuntimeException('Statement already in use'); + } + + if (!$this->getReadable()) { + return false; + } + + if (!$keys) { + return true; + } + + $this->normalizeOptions($options); + + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = preg_quote($prefix, '/'); + + $format = 0; + foreach ($options['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; + } + } + + $search = array(); + foreach ($keys as $key) { + $search[] = preg_quote($key, '/'); + } + $search = '/^' . $prefix . '(' . implode('|', $search) . ')$/'; + + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = &$options; + + if (isset($options['callback'])) { + $callback = $options['callback']; + if (!is_callable($callback, false)) { + $this->stmtActive = false; + $this->stmtIterator = null; + $this->stmtOptions = null; + throw new InvalidArgumentException('Invalid callback'); + } + + while ( ($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + return true; + } + + public function find($mode = self::MATCH_ACTIVE, array $options = array()) + { + if ($this->stmtActive) { + throw new RuntimeException('Statement already in use'); + } + + if (!$this->getReadable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); + if (($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE) { + // This adapter doen't support to read expired items + return true; + } + + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $search = '/^' . preg_quote($prefix, '/') . '+/'; + + $format = 0; + foreach ($options['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; + } + } + + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = &$options; + + return true; + } + + public function fetch() + { + if (!$this->stmtActive) { + return false; + } + + do { + if (!$this->stmtIterator->valid()) { + // clear stmt + $this->stmtActive = false; + $this->stmtIterator = null; + $this->stmtOptions = null; + + return false; + } + + // @see http://pecl.php.net/bugs/bug.php?id=22564 + $exist = apc_exists($this->stmtIterator->key()); + + if ($exist) { + $metadata = $this->stmtIterator->current(); + $this->normalizeMetadata($metadata); + + $select = $this->stmtOptions['select']; + if (in_array('key', $select)) { + $internalKey = $this->stmtIterator->key(); + $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); + $metadata['key'] = $key; + } + } + + $this->stmtIterator->next(); + + } while (!$exist); + + return $metadata; + } + + /* cleaning */ + + public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + { + $this->normalizeOptions($options); + return $this->clearByRegEx('/.*/', $mode, $options); + } + + public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + { + $this->normalizeOptions($options); + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $regex = '/^' . preg_quote($prefix, '/') . '+/'; + + return $this->clearByRegEx($regex, $mode, $options); + } + + /* status */ + + public function getCapabilities() + { + if ($this->capabilities === null) { + $this->capabilityMarker = new \stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false + ), + 'supportedMetadata' => array( + 'mtime', 'ctime', 'atime', 'rtime', 'ttl', + 'num_hits', 'ref_count', 'mem_size', 'internal_key' + ), + 'maxTtl' => 0, + 'staticTtl' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => (bool)ini_get('apc.use_request_time'), + 'expiredRead' => false, + 'maxKeyLength' => 5182, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getNamespaceSeparator(), + 'iterable' => true, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); + } + + return $this->capabilities; + } + + public function getCapacity(array $options = array()) + { + $mem = apc_sma_info(true); + + return array( + 'free' => $mem['avail_mem'], + 'total' => $mem['num_seg'] * $mem['seg_size'], + ); + } + + /* internal */ + + protected function clearByRegEx($regex, $mode, array &$options) + { + if (!$this->getWritable()) { + return false; + } + + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + if (($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE) { + // no need to clear expired items + return true; + } + + return apc_delete(new APCIterator('user', $regex, 0, 1, \APC_LIST_ACTIVE)); + } + + protected function normalizeMetadata(array &$metadata) + { + // rename + if (isset($metadata['creation_time'])) { + $metadata['ctime'] = $metadata['creation_time']; + unset($metadata['creation_time']); + } + + if (isset($metadata['access_time'])) { + $metadata['atime'] = $metadata['access_time']; + unset($metadata['access_time']); + } + + if (isset($metadata['deletion_time'])) { + $metadata['rtime'] = $metadata['deletion_time']; + unset($metadata['deletion_time']); + } + + // remove namespace prefix + if (isset($metadata['key'])) { + $pos = strpos($metadata['key'], $this->getNamespaceSeparator()); + if ($pos !== false) { + $metadata['internal_key'] = $metadata['key']; + } else { + $metadata['internal_key'] = $metadata['key']; + } + + unset($metadata['key']); + } + } + +} diff --git a/test/Storage/Adapter/ApcTest.php b/test/Storage/Adapter/ApcTest.php new file mode 100644 index 000000000..fd8a611a1 --- /dev/null +++ b/test/Storage/Adapter/ApcTest.php @@ -0,0 +1,88 @@ + 0) { + try { + new Cache\Storage\Adapter\Apc(); + $this->fail("Expected exception Zend\Cache\Exception\ExtensionNotLoadedException"); + } catch (Cache\Exception\ExtensionNotLoadedException $e) { + $this->markTestSkipped("Missing ext/apc >= 3.1.6"); + } + } + + $enabled = (bool)ini_get('apc.enabled'); + if (PHP_SAPI == 'cli') { + $enabled = $enabled && (bool)ini_get('apc.enable_cli'); + } + if (!$enabled) { + try { + new Cache\Storage\Adapter\Apc(); + $this->fail("Expected exception Zend\Cache\Exception\ExtensionNotLoadedException"); + } catch (Cache\Exception\ExtensionNotLoadedException $e) { + $this->markTestSkipped("ext/apc is disabled - see 'apc.enabled' and 'apc.enable_cli'"); + } + } + + // needed on test expirations + $this->iniUseRequestTime = ini_get('apc.use_request_time'); + ini_set('apc.use_request_time', 0); + + $this->_storage = new Cache\Storage\Adapter\Apc(); + + parent::setUp(); + } + + public function tearDown() + { + if (function_exists('apc_clear_cache')) { + apc_clear_cache('user'); + } + + // reset ini configurations + ini_set('apc.use_request_time', $this->iniUseRequestTime); + + parent::tearDown(); + } + +} From 3ca3088b69ebdf588e36e3ce6807708e131bd0e0 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 12 Dec 2011 08:50:19 +0100 Subject: [PATCH 136/311] apc adapter: trigger events on [get|has]Item(s) --- src/Storage/Adapter/Apc.php | 132 +++++++++++++++++++++++++++--------- 1 file changed, 99 insertions(+), 33 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 246585f07..2479c759d 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -133,21 +133,34 @@ public function getItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $value = apc_fetch($key, $success); - if (!$success) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found"); + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $result = apc_fetch($internalKey, $success); + if (!$success) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$internalKey}' not found"); + } + $result = false; + } else { + if (array_key_exists('token', $options)) { + $options['token'] = $result; + } } - return false; - } - if (array_key_exists('token', $options)) { - $options['token'] = $value; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - return $value; } public function getItems(array $keys, array $options = array()) @@ -157,27 +170,41 @@ public function getItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - foreach ($keys as &$key) { - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; - } + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $ret = apc_fetch($keys); + $internalKeys = array(); + foreach ($keys as $key) { + $internalKeys[] = $options['namespace'] . $this->getNamespaceSeparator() . $key; + } - if (!$options['ignore_missing_items']) { - if (count($keys) != count($ret)) { - $missing = implode("', '", array_diff($keys, array_keys($ret))); - throw new ItemNotFoundException('Keys not found: ' . $missing); + $fetch = apc_fetch($internalKeys); + if (!$options['ignore_missing_items']) { + if (count($keys) != count($fetch)) { + $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); + throw new ItemNotFoundException('Keys not found: ' . $missing); + } } - } - // remove namespace prefix - $nsl = strlen($options['namespace']); - $ret2 = array(); - foreach ($ret as $key => &$value) { - $ret2[ substr($key, $nsl+1) ] = $value; - } + // remove namespace prefix + $prefixL = strlen($options['namespace'] . $this->getNamespaceSeparator()); + $result = array(); + foreach ($fetch as $internalKey => &$value) { + $result[ substr($internalKey, $prefixL) ] = $value; + } - return $ret2; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function hasItem($key, array $options = array()) @@ -188,9 +215,24 @@ public function hasItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new \ArrayObject(array( + 'key' => & $key, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - return apc_exists($key); + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $result = apc_exists($internalKey); + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function hasItems(array $keys, array $options = array()) @@ -200,11 +242,35 @@ public function hasItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - foreach ($keys as &$key) { - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; - } + $args = new \ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $internalKeys = array(); + foreach ($keys as $key) { + $internalKeys[] = $options['namespace'] . $this->getNamespaceSeparator() . $key; + } - return apc_exists($keys); + $exists = apc_exists($internalKeys); + $result = array(); + $prefixL = strlen($options['namespace'] . $this->getNamespaceSeparator()); + foreach ($exists as $internalKey => $bool) { + if ($bool === true) { + $result[] = substr($internalKey, $prefixL); + } + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function getMetadata($key, array $options = array()) From f2070459b988f97a243a5a227fd183a536bc767a Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 12 Dec 2011 14:13:36 -0600 Subject: [PATCH 137/311] Ensured ready for CS review - Added all docblocks - Reviewed for import statements, CS whitespace, etc. --- src/Exception.php | 9 +- src/Exception/BadMethodCallException.php | 31 +- src/Exception/ExtensionNotLoadedException.php | 31 +- src/Exception/InvalidArgumentException.php | 31 +- src/Exception/ItemNotFoundException.php | 27 +- src/Exception/LogicException.php | 31 +- src/Exception/MissingDependencyException.php | 27 +- src/Exception/MissingKeyException.php | 27 +- src/Exception/RuntimeException.php | 31 +- src/Exception/UnexpectedValueException.php | 31 +- .../UnsupportedMethodCallException.php | 34 +- src/Pattern.php | 26 +- src/Pattern/AbstractPattern.php | 45 +- src/Pattern/CallbackCache.php | 83 ++-- src/Pattern/CaptureCache.php | 108 +++-- src/Pattern/ClassCache.php | 87 ++-- src/Pattern/ObjectCache.php | 160 +++--- src/Pattern/OutputCache.php | 76 +-- src/PatternBroker.php | 12 +- src/PatternFactory.php | 60 ++- src/PatternLoader.php | 5 +- src/Storage/Adapter.php | 236 +++++---- src/Storage/Adapter/AbstractAdapter.php | 426 ++++++++-------- src/Storage/Adapter/Apc.php | 457 +++++++++++++++--- src/Storage/Adapter/Filesystem.php | 356 +++++++------- src/Storage/Adapter/Memory.php | 287 ++++++----- src/Storage/AdapterBroker.php | 15 +- src/Storage/AdapterLoader.php | 6 +- src/Storage/Capabilities.php | 233 +++++---- src/Storage/Event.php | 45 +- src/Storage/ExceptionEvent.php | 48 +- src/Storage/Plugin.php | 39 +- src/Storage/Plugin/ClearByFactor.php | 90 +++- src/Storage/Plugin/ExceptionHandler.php | 89 +++- src/Storage/Plugin/OptimizeByFactor.php | 79 ++- src/Storage/Plugin/Serializer.php | 144 ++++-- src/Storage/PluginBroker.php | 16 +- src/Storage/PluginLoader.php | 6 +- src/Storage/PostEvent.php | 32 +- src/StorageFactory.php | 125 +++-- src/Utils.php | 90 ++-- 41 files changed, 2546 insertions(+), 1245 deletions(-) diff --git a/src/Exception.php b/src/Exception.php index 6f592093a..27fc3e5b4 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -20,5 +20,12 @@ namespace Zend\Cache; +/** + * @category Zend + * @package Zend_Cache + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @license http://framework.zend.com/license/new-bsd New BSD License + */ interface Exception -{} +{ +} diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index 762ceb79c..6de22de90 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -1,6 +1,33 @@ $value) { $method = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($option)))); + if (!method_exists($this, $method)) { + continue; + } $this->{$method}($value); } @@ -50,5 +80,4 @@ public function getOptions() { return array(); } - } diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index 40474e35d..ae13d5044 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -1,17 +1,43 @@ getStorage()) { - throw new InvalidArgumentException("Missing option 'storage'"); + throw new Exception\InvalidArgumentException("Missing option 'storage'"); } } @@ -53,7 +79,7 @@ public function getOptions() /** * Get cache storage * - * return Zend\Cache\Storage\Adapter + * return StorageAdapter */ public function getStorage() { @@ -63,17 +89,17 @@ public function getStorage() /** * Set cache storage * - * @param Zend\Cache\Storage\Adapter|array|string $storage - * @return Zend\Cache\Pattern\PatternInterface + * @param StorageAdapter|array|string $storage + * @return CallbackCache */ public function setStorage($storage) { if (is_array($storage)) { - $storage = Cache\StorageFactory::factory($storage); + $storage = StorageFactory::factory($storage); } elseif (is_string($storage)) { - $storage = Cache\StorageFactory::adapterFactory($storage); - } elseif ( !($storage instanceof Cache\Storage\Adapter) ) { - throw new InvalidArgumentException( + $storage = StorageFactory::adapterFactory($storage); + } elseif ( !($storage instanceof StorageAdapter) ) { + throw new Exception\InvalidArgumentException( 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' . 'or an array passed to Zend\Cache\Storage::factory ' . 'or simply the name of the storage adapter' @@ -91,7 +117,7 @@ public function setStorage($storage) */ public function setCacheOutput($flag) { - $this->cacheOutput = (bool)$flag; + $this->cacheOutput = (bool) $flag; return $this; } @@ -112,14 +138,14 @@ public function getCacheOutput() * @param array $args Callback arguments * @param array $options Options * @return mixed Result - * @throws Zend\Cache\Exception + * @throws Exception */ public function call($callback, array $args = array(), array $options = array()) { $key = $this->_generateKey($callback, $args, $options); if ( ($rs = $this->getStorage()->getItem($key, $options)) !== false ) { if (!isset($rs[0])) { - throw new RuntimeException("Invalid cached data for key '{$key}'"); + throw new Exception\RuntimeException("Invalid cached data for key '{$key}'"); } echo isset($rs[1]) ? $rs[1] : ''; @@ -163,7 +189,7 @@ public function call($callback, array $args = array(), array $options = array()) * @param string $function Function name to call * @param array $args Function arguments * @return mixed - * @throws Zend\Cache\Exception + * @throws Exception */ public function __call($function, array $args) { @@ -184,7 +210,7 @@ public function __call($function, array $args) * @param array $args Callback arguments * @param array $options Options * @return string - * @throws Zend\Cache\Exception + * @throws Exception */ public function generateKey($callback, array $args = array(), array $options = array()) { @@ -199,8 +225,8 @@ public function generateKey($callback, array $args = array(), array $options = a * @param array $args Callback arguments * @param array $options Options * @return string - * @throws \Zend\Cache\Exception\InvalidArgumentException - * @throws \Zend\Cache\Exception\RuntimeException + * @throws Exception\InvalidArgumentException + * @throws Exception\RuntimeException */ protected function _generateKey($callback, array $args, array $options) { @@ -212,11 +238,11 @@ protected function _generateKey($callback, array $args, array $options) $callbackKey = (string)$options['callback_key']; if (!is_callable($callback, false)) { - throw new InvalidArgumentException('Invalid callback'); + throw new Exception\InvalidArgumentException('Invalid callback'); } } else { if (!is_callable($callback, false, $callbackKey)) { - throw new InvalidArgumentException('Invalid callback'); + throw new Exception\InvalidArgumentException('Invalid callback'); } // functions, methods and classnames are case-insensitive @@ -232,14 +258,14 @@ protected function _generateKey($callback, array $args, array $options) try { $serializedObject = @serialize($object); } catch (\Exception $e) { - throw new RuntimeException( + throw new Exception\RuntimeException( "Can't serialize callback: see previous exception" , 0, $e); } if (!$serializedObject) { $lastErr = error_get_last(); - throw new RuntimeException( + throw new Exception\RuntimeException( "Can't serialize callback: " . $lastErr['message'] ); @@ -255,14 +281,14 @@ protected function _generateKey($callback, array $args, array $options) try { $serializedArgs = @serialize(array_values($args)); } catch (\Exception $e) { - throw new RuntimeException( + throw new Exception\RuntimeException( "Can't serialize arguments: see previous exception" , 0, $e); } if (!$serializedArgs) { $lastErr = error_get_last(); - throw new RuntimeException( + throw new Exception\RuntimeException( "Can't serialize arguments: " . $lastErr['message'] ); @@ -274,5 +300,4 @@ protected function _generateKey($callback, array $args, array $options) // merge and return the key parts return md5($callbackKey.$argumentKey); } - } diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 844773b65..5d3e95235 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -1,11 +1,38 @@ 0) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Invalid file umask or file permission: ' . 'executable cache files are not allowed' ); @@ -253,12 +280,12 @@ public function getFileUmask() /** * Set file locking * - * @param bool $flag + * @param bool $flag * @return CaptureCache */ public function setFileLocking($flag) { - $this->fileLocking = (boolean)$flag; + $this->fileLocking = (bool) $flag; return $this; } @@ -275,12 +302,12 @@ public function getFileLocking() /** * Set index filename * - * @param string $filename + * @param string $filename * @return CaptureCache */ public function setIndexFilename($filename) { - $this->indexFilename = (string)$filename; + $this->indexFilename = (string) $filename; return $this; } @@ -297,7 +324,7 @@ public function getIndexFilename() /** * Set a storage for tagging or remove the storage * - * @param null|StorageAdapter $storage + * @param null|StorageAdapter $storage * @return CaptureCache */ public function setTagStorage(StorageAdapter $storage = null) @@ -319,13 +346,13 @@ public function getTagStorage() /** * Set cache item key to store tags * - * @param $tagKey string + * @param $tagKey string * @return CaptureCache */ public function setTagKey($tagKey) { if (($tagKey = (string)$tagKey) === '') { - throw new InvalidArgumentException("Missing tag key '{$tagKey}'"); + throw new Exception\InvalidArgumentException("Missing tag key '{$tagKey}'"); } $this->tagKey = $tagKey; @@ -345,7 +372,7 @@ public function getTagKey() /** * Set tags to store * - * @param array $tags + * @param array $tags * @return CaptureCache */ public function setTags(array $tags) @@ -367,14 +394,14 @@ public function getTags() /** * Start the cache * - * @param string $pageId Page identifier - * @param array $options Options + * @param string $pageId Page identifier + * @param array $options Options * @return boolean false */ public function start($pageId = null, array $options = array()) { if ($this->pageId !== null) { - throw new RuntimeException("Capturing already stated with page id '{$this->pageId}'"); + throw new Exception\RuntimeException("Capturing already stated with page id '{$this->pageId}'"); } if (isset($options['tags'])) { @@ -383,7 +410,7 @@ public function start($pageId = null, array $options = array()) } if ($this->getTags() && !$this->getTagStorage()) { - throw new RuntimeException('Tags are defined but missing a tag storage'); + throw new Exception\RuntimeException('Tags are defined but missing a tag storage'); } if (($pageId = (string)$pageId) === '') { @@ -400,10 +427,10 @@ public function start($pageId = null, array $options = array()) /** * Get from cache * - * @param null|string $pageId - * @param array $options + * @param null|string $pageId + * @param array $options * @return bool|string - * @throws RuntimeException + * @throws Exception\RuntimeException */ public function get($pageId = null, array $options = array()) { @@ -418,7 +445,7 @@ public function get($pageId = null, array $options = array()) if (file_exists($file)) { if (($content = @file_get_contents($file)) === false) { $lastErr = error_get_last(); - throw new RuntimeException("Failed to read cached pageId '{$pageId}': {$lastErr['message']}"); + throw new Exception\RuntimeException("Failed to read cached pageId '{$pageId}': {$lastErr['message']}"); } return $content; } @@ -429,8 +456,8 @@ public function get($pageId = null, array $options = array()) /** * Checks if a cache with given id exists * - * @param null|string $pageId - * @param array $options + * @param null|string $pageId + * @param array $options * @return bool */ public function exists($pageId = null, array $options = array()) @@ -449,9 +476,9 @@ public function exists($pageId = null, array $options = array()) /** * Remove from cache * - * @param null|string $pageId - * @param array $options - * @throws RuntimeException + * @param null|string $pageId + * @param array $options + * @throws Exception\RuntimeException * @return void */ public function remove($pageId = null, array $options = array()) @@ -467,7 +494,7 @@ public function remove($pageId = null, array $options = array()) if (file_exists($file)) { if (!@unlink($file)) { $lastErr = error_get_last(); - throw new RuntimeException("Failed to remove cached pageId '{$pageId}': {$lastErr['message']}"); + throw new Exception\RuntimeException("Failed to remove cached pageId '{$pageId}': {$lastErr['message']}"); } } } @@ -544,7 +571,7 @@ protected function flush($output) * Save the cache * * @param $output - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function save($output) { @@ -554,7 +581,7 @@ protected function save($output) $oldUmask = umask($this->getDirUmask()); if (!@mkdir($fullPath, 0777, true)) { $lastErr = error_get_last(); - throw new RuntimeException( + throw new Exception\RuntimeException( "Can't create directory '{$fullPath}': {$lastErr['message']}" ); } @@ -594,7 +621,7 @@ protected function save($output) * * @param string $file File complete path * @param string $data Data to write - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function putFileContent($file, $data) { @@ -607,8 +634,7 @@ protected function putFileContent($file, $data) if ( $put < strlen((binary)$data) ) { $lastErr = error_get_last(); @unlink($file); // remove old or incomplete written file - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } } - } diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index c22c68356..fc3651f72 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -1,13 +1,37 @@ getEntity()) { - throw new InvalidArgumentException("Missing option 'entity'"); + throw new Exception\InvalidArgumentException("Missing option 'entity'"); } elseif (!$this->getStorage()) { - throw new InvalidArgumentException("Missing option 'storage'"); + throw new Exception\InvalidArgumentException("Missing option 'storage'"); } } @@ -71,13 +95,13 @@ public function getOptions() /** * Set the entity to cache * - * @param string $entity The entity as classname - * @return Zend\Cache\Pattern\ClassCache + * @param string $entity The entity as classname + * @return ClassCache */ public function setEntity($entity) { if (!is_string($entity)) { - throw new InvalidArgumentException('Invalid entity, must be a classname'); + throw new Exception\InvalidArgumentException('Invalid entity, must be a classname'); } $this->entity = $entity; return $this; @@ -96,12 +120,12 @@ public function getEntity() /** * Enable or disable caching of methods by default. * - * @param boolean $flag - * @return Zend\Cache\Pattern\ClassCache + * @param boolean $flag + * @return ClassCache */ public function setCacheByDefault($flag) { - $this->cacheByDefault = (bool)$flag; + $this->cacheByDefault = (bool) $flag; return $this; } @@ -118,12 +142,12 @@ public function getCacheByDefault() /** * Enable cache methods * - * @param string[] $methods - * @return Zend\Cache\Pattern\ClassCache + * @param string[] $methods + * @return ClassCache */ public function setCacheMethods(array $methods) { - $this->cacheMethods = array_values(array_unique(array_map(function ($method) { + $this->cacheMethods = array_values(array_unique(array_map(function($method) { return strtolower($method); }, $methods))); @@ -143,12 +167,12 @@ public function getCacheMethods() /** * Disable cache methods * - * @param string[] $methods - * @return Zend\Cache\Pattern\ClassCache + * @param string[] $methods + * @return ClassCache */ public function setNonCacheMethods(array $methods) { - $this->nonCacheMethods = array_values(array_unique(array_map(function ($method) { + $this->nonCacheMethods = array_values(array_unique(array_map(function($method) { return strtolower($method); }, $methods))); @@ -172,7 +196,7 @@ public function getNonCacheMethods() * @param array $args Method arguments * @param array $options Cache options * @return mixed - * @throws Zend\Cache\Exception + * @throws Exception */ public function call($method, array $args = array(), array $options = array()) { @@ -209,7 +233,7 @@ public function call($method, array $args = array(), array $options = array()) * @param string $method The method name * @param array $args Method arguments * @return string - * @throws Zend\Cache\Exception + * @throws Exception */ public function generateKey($method, array $args = array(), array $options = array()) { @@ -230,7 +254,7 @@ public function generateKey($method, array $args = array(), array $options = arr * @param string $method Method name to call * @param array $args Method arguments * @return mixed - * @throws Zend\Cache\Exception + * @throws Exception */ public function __call($method, array $args) { @@ -240,9 +264,10 @@ public function __call($method, array $args) /** * Set a static property * - * @param string $name - * @param mixed $value - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + * @param string $name + * @param mixed $value + * @return void + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members */ public function __set($name, $value) { @@ -253,9 +278,9 @@ public function __set($name, $value) /** * Get a static property * - * @param string $name + * @param string $name * @return mixed - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members */ public function __get($name) { @@ -266,7 +291,7 @@ public function __get($name) /** * Is a static property exists. * - * @param string $name + * @param string $name * @return bool */ public function __isset($name) @@ -278,12 +303,12 @@ public function __isset($name) /** * Unset a static property * - * @param string $name + * @param string $name + * @return void */ public function __unset($name) { $class = $this->getEntity(); unset($class::$name); } - } diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index cf2bfa871..f4b24b260 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -1,13 +1,37 @@ getEntity()) { - throw new InvalidArgumentException("Missing option 'entity'"); + throw new Exception\InvalidArgumentException("Missing option 'entity'"); } elseif (!$this->getStorage()) { - throw new InvalidArgumentException("Missing option 'storage'"); + throw new Exception\InvalidArgumentException("Missing option 'storage'"); } } @@ -87,13 +111,13 @@ public function getOptions() /** * Set the entity to cache * - * @param object $entity - * @return Zend\Cache\Pattern\ObjectCache + * @param object $entity + * @return ObjectCache */ public function setEntity($entity) { if (!is_object($entity)) { - throw new InvalidArgumentException('Invalid entity, must be an object'); + throw new Exception\InvalidArgumentException('Invalid entity, must be an object'); } $this->entity = $entity; return $this; @@ -117,14 +141,14 @@ public function getEntity() * * NOTE: This option has no effect if callback_key was given. * - * @param null|string $key The key part as string or NULL to auto-generate - * @return Zend\Cache\Pattern\ObjectCache - * @see generateKey + * @param null|string $key The key part as string or NULL to auto-generate + * @return ObjectCache + * @see generateKey() */ public function setEntityKey($key) { if ($key !== null) { - $this->entityKey = (string)$key; + $this->entityKey = (string) $key; } else { $this->entityKey = null; } @@ -136,7 +160,7 @@ public function setEntityKey($key) * Get the entity key part. * * @return null|string - * @see setEntityKey + * @see setEntityKey() */ public function getEntityKey() { @@ -146,12 +170,12 @@ public function getEntityKey() /** * Enable or disable caching of methods by default. * - * @param boolean $flag - * @return Zend\Cache\Pattern\ObjectCache + * @param boolean $flag + * @return ObjectCache */ public function setCacheByDefault($flag) { - $this->cacheByDefault = (bool)$flag; + $this->cacheByDefault = (bool) $flag; return $this; } @@ -168,12 +192,12 @@ public function getCacheByDefault() /** * Enable cache methods * - * @param string[] $methods - * @return Zend\Cache\Pattern\ObjectCache + * @param string[] $methods + * @return ObjectCache */ public function setCacheMethods(array $methods) { - $this->cacheMethods = array_values(array_unique(array_map(function ($method) { + $this->cacheMethods = array_values(array_unique(array_map(function($method) { $method = strtolower($method); switch ($method) { @@ -181,7 +205,7 @@ public function setCacheMethods(array $methods) case '__get': case '__unset': case '__isset': - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Magic properties are handled by option 'cache_magic_properties'" ); } @@ -205,12 +229,12 @@ public function getCacheMethods() /** * Disable cache methods * - * @param string[] $methods - * @return Zend\Cache\Pattern\ObjectCache + * @param string[] $methods + * @return ObjectCache */ public function setNonCacheMethods(array $methods) { - $this->nonCacheMethods = array_values(array_unique(array_map(function ($method) { + $this->nonCacheMethods = array_values(array_unique(array_map(function($method) { $method = strtolower($method); switch ($method) { @@ -218,7 +242,7 @@ public function setNonCacheMethods(array $methods) case '__get': case '__unset': case '__isset': - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Magic properties are handled by option 'cache_magic_properties'" ); } @@ -242,12 +266,12 @@ public function getNonCacheMethods() /** * Enable or disable caching of magic property calls * - * @param boolean $flag - * @return Zend\Cache\Pattern\ObjectCache + * @param boolean $flag + * @return ObjectCache */ public function setCacheMagicProperties($flag) { - $this->cacheMagicProperties = (bool)$flag; + $this->cacheMagicProperties = (bool) $flag; return $this; } @@ -268,7 +292,7 @@ public function getCacheMagicProperties() * @param array $args Method arguments * @param array $options Cache options * @return mixed - * @throws Zend\Cache\Exception + * @throws Exception */ public function call($method, array $args = array(), array $options = array()) { @@ -283,8 +307,9 @@ public function call($method, array $args = array(), array $options = array()) $object->{$property} = $value; - if ( !$this->getCacheMagicProperties() - || property_exists($object, $property) ) { + if (!$this->getCacheMagicProperties() + || property_exists($object, $property) + ) { // no caching if property isn't magic // or caching magic properties is disabled return; @@ -306,8 +331,9 @@ public function call($method, array $args = array(), array $options = array()) case '__get': $property = array_shift($args); - if ( !$this->getCacheMagicProperties() - || property_exists($object, $property)) { + if (!$this->getCacheMagicProperties() + || property_exists($object, $property) + ) { // no caching if property isn't magic // or caching magic properties is disabled return $object->{$property}; @@ -316,8 +342,10 @@ public function call($method, array $args = array(), array $options = array()) array_unshift($args, $property); if (!isset($options['callback_key'])) { - if ( (isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null)) { + if ((isset($options['entity_key']) + && ($entityKey = $options['entity_key']) !== null) + || ($entityKey = $this->getEntityKey() !== null) + ) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); } @@ -328,16 +356,19 @@ public function call($method, array $args = array(), array $options = array()) case '__isset': $property = array_shift($args); - if ( !$this->getCacheMagicProperties() - || property_exists($object, $property)) { + if (!$this->getCacheMagicProperties() + || property_exists($object, $property) + ) { // no caching if property isn't magic // or caching magic properties is disabled return isset($object->{$property}); } if (!isset($options['callback_key'])) { - if ( (isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null)) { + if ((isset($options['entity_key']) + && ($entityKey = $options['entity_key']) !== null) + || ($entityKey = $this->getEntityKey() !== null) + ) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); } @@ -350,8 +381,9 @@ public function call($method, array $args = array(), array $options = array()) unset($object->{$property}); - if ( !$this->getCacheMagicProperties() - || property_exists($object, $property)) { + if (!$this->getCacheMagicProperties() + || property_exists($object, $property) + ) { // no caching if property isn't magic // or caching magic properties is disabled return; @@ -381,14 +413,14 @@ public function call($method, array $args = array(), array $options = array()) if (!$cache) { if ($args) { return call_user_func_array(array($object, $method), $args); - } else { - return $object->{$method}(); - } + } + return $object->{$method}(); } if (!isset($options['callback_key'])) { - if ( (isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null)) { + if ((isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) + || ($entityKey = $this->getEntityKey() !== null) + ) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); } @@ -404,7 +436,7 @@ public function call($method, array $args = array(), array $options = array()) * @param array $args Method arguments * @param array $options Options * @return string - * @throws Zend\Cache\Exception + * @throws Exception */ public function generateKey($method, array $args = array(), array $options = array()) { @@ -425,7 +457,7 @@ public function generateKey($method, array $args = array(), array $options = arr * @param string $method Method name to call * @param array $args Method arguments * @return mixed - * @throws Zend\Cache\Exception + * @throws Exception */ public function __call($method, array $args) { @@ -440,9 +472,10 @@ public function __call($method, array $args) * is enabled and the property doesn't exist in real. If so it calls __set * and removes cached data of previous __get and __isset calls. * - * @param string $name - * @param mixed $value - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + * @param string $name + * @param mixed $value + * @return void + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members */ public function __set($name, $value) { @@ -456,7 +489,7 @@ public function __set($name, $value) * Magic properties will be cached too if the option cacheMagicProperties * is enabled and the property doesn't exist in real. If so it calls __get. * - * @param string $name + * @param string $name * @return mixed * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members */ @@ -472,9 +505,9 @@ public function __get($name) * Magic properties will be cached too if the option cacheMagicProperties * is enabled and the property doesn't exist in real. If so it calls __get. * - * @param string $name + * @param string $name * @return bool - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members */ public function __isset($name) { @@ -489,8 +522,9 @@ public function __isset($name) * is enabled and the property doesn't exist in real. If so it removes * previous cached __isset and __get calls. * - * @param string $name - * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members + * @param string $name + * @return void + * @see http://php.net/manual/language.oop5.overloading.php#language.oop5.overloading.members */ public function __unset($name) { @@ -501,7 +535,7 @@ public function __unset($name) * Handle casting to string * * @return string - * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.tostring + * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.tostring */ public function __toString() { @@ -512,10 +546,10 @@ public function __toString() * Handle invoke calls * * @return mixed - * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.invoke + * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.invoke */ - public function __invoke() { + public function __invoke() + { return $this->call('__invoke', func_get_args()); } - -} \ No newline at end of file +} diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index 4a62e856e..965379b77 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -1,19 +1,43 @@ getStorage()) { - throw new InvalidArgumentException("Missing option 'storage'"); + throw new Exception\InvalidArgumentException("Missing option 'storage'"); } } @@ -54,7 +78,7 @@ public function getOptions() /** * Get cache storage * - * return Zend\Cache\Storage\Adapter + * return StorageAdapter */ public function getStorage() { @@ -64,17 +88,17 @@ public function getStorage() /** * Set cache storage * - * @param Zend\Cache\Storage\Adapter|array|string $storage - * @return Zend\Cache\Pattern\PatternInterface + * @param StorageAdapter|array|string $storage + * @return OutputCache */ public function setStorage($storage) { if (is_array($storage)) { - $storage = Cache\StorageFactory::factory($storage); + $storage = StorageFactory::factory($storage); } elseif (is_string($storage)) { - $storage = Cache\StorageFactory::adapterFactory($storage); - } elseif ( !($storage instanceof Cache\Storage\Adapter) ) { - throw new InvalidArgumentException( + $storage = StorageFactory::adapterFactory($storage); + } elseif (!($storage instanceof StorageAdapter)) { + throw new Exception\InvalidArgumentException( 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' . 'or an array passed to Zend\Cache\Storage::factory ' . 'or simply the name of the storage adapter' @@ -96,17 +120,17 @@ public function setStorage($storage) * @param string $key Key * @param array $options Output start options (ttl | validate | output) * @return boolean|string True if the cache is hit or if output disabled the cached data, false else - * @throws Zend_Cache_Exception + * @throws Exception */ public function start($key, array $options = array()) { - if (($key = (string)$key) === '') { - throw new MissingKeyException('Missing key to read/write output from storage'); + if (($key = (string) $key) === '') { + throw new Exception\MissingKeyException('Missing key to read/write output from storage'); } $optOutput = true; if (isset($options['output'])) { - $optOutput = (bool)$options['output']; + $optOutput = (bool) $options['output']; unset($options['output']); // don't forword this option to storage } @@ -115,9 +139,8 @@ public function start($key, array $options = array()) if ($optOutput) { echo $data; return true; - } else { - return (string)$data; } + return (string) $data; } ob_start(); @@ -136,13 +159,13 @@ public function start($key, array $options = array()) * * @param array $options * @return boolean - * @throws Zend_Cache_Exception + * @throws Exception */ public function end(array $options = array()) { $key = array_pop($this->keyStack); if ($key === null) { - throw new RuntimeException('use of end() without a start()'); + throw new Exception\RuntimeException('use of end() without a start()'); } $optOutput = true; @@ -158,10 +181,9 @@ public function end(array $options = array()) } if ($data === false) { - throw new RuntimeException('Output buffering not active'); + throw new Exception\RuntimeException('Output buffering not active'); } return $this->getStorage()->setItem($key, $data, $options); } - } diff --git a/src/PatternBroker.php b/src/PatternBroker.php index 734d7fdf4..5b1fe91b8 100644 --- a/src/PatternBroker.php +++ b/src/PatternBroker.php @@ -14,20 +14,20 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache; -use Zend\Loader\PluginBroker, - Zend\Cache\Exception\RuntimeException; + +use Zend\Loader\PluginBroker; /** * Broker for cache pattern instances * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PatternBroker extends PluginBroker @@ -42,12 +42,12 @@ class PatternBroker extends PluginBroker * * @param mixed $plugin * @return true - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function validatePlugin($plugin) { if (!$plugin instanceof Pattern) { - throw new RuntimeException('Cache pattern must implement Zend\Cache\Pattern'); + throw new Exception\RuntimeException('Cache pattern must implement Zend\Cache\Pattern'); } return true; } diff --git a/src/PatternFactory.php b/src/PatternFactory.php index db9b6509b..5efb95f93 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -1,26 +1,49 @@ load($patternName, $options); + return static::getBroker()->load($patternName, $options); } /** * Get the pattern broker * - * @return Zend\Loader\Broker + * @return Broker */ public static function getBroker() { - if (self::$broker === null) { - self::$broker = self::_getDefaultBroker(); + if (static::$broker === null) { + static::$broker = static::getDefaultBroker(); } - return self::$broker; + return static::$broker; } /** * Set the pattern broker * - * @param Zend\Loader\Broker $broker + * @param Broker $broker * @return void */ public static function setBroker(Broker $broker) { - self::$broker = $broker; + static::$broker = $broker; } /** @@ -64,17 +87,16 @@ public static function setBroker(Broker $broker) */ public static function resetBroker() { - self::$broker = null; + static::$broker = null; } /** * Get internal pattern broker * - * @return Zend\Loader\Broker + * @return PatternBroker */ - protected static function _getDefaultBroker() + protected static function getDefaultBroker() { return new PatternBroker(); } - } diff --git a/src/PatternLoader.php b/src/PatternLoader.php index a49212ea9..dfa355891 100644 --- a/src/PatternLoader.php +++ b/src/PatternLoader.php @@ -14,11 +14,12 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache; + use Zend\Loader\PluginClassLoader; /** @@ -26,7 +27,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PatternLoader extends PluginClassLoader diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index fd13927e1..0285eb707 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -1,10 +1,35 @@ $value) { $method = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($option)))); + if (!method_exists($this, $method)) { + continue; + } $this->{$method}($value); } @@ -194,12 +221,12 @@ public function getOptions() /** * Enable/Disable writing data to cache. * - * @param boolean $flag + * @param boolean $flag * @return AbstractAdapter */ public function setWritable($flag) { - $this->writable = (bool)$flag; + $this->writable = (bool) $flag; return $this; } @@ -216,12 +243,12 @@ public function getWritable() /** * Enable/Disable reading data from cache. * - * @param boolean $flag + * @param boolean $flag * @return AbstractAdapter */ public function setReadable($flag) { - $this->readable = (bool)$flag; + $this->readable = (bool) $flag; return $this; } @@ -237,16 +264,17 @@ public function getReadable() /** * Enable/Disable caching. + * * Alias of setWritable and setReadable. * - * @see setWritable - * @see setReadable - * @param boolean $flag + * @see setWritable() + * @see setReadable() + * @param boolean $flag * @return AbstractAdapter */ public function setCaching($flag) { - $flag = (bool)$flag; + $flag = (bool) $flag; $this->setWritable($flag); $this->setReadable($flag); return $this; @@ -254,10 +282,11 @@ public function setCaching($flag) /** * Get caching enabled. + * * Alias of getWritable and getReadable. * - * @see getWritable - * @see getReadable + * @see getWritable() + * @see getReadable() * @return boolean */ public function getCaching() @@ -266,9 +295,9 @@ public function getCaching() } /** - * Set time to life. + * Set time to live. * - * @param int|float $ttl + * @param int|float $ttl * @return AbstractAdapter */ public function setTtl($ttl) @@ -279,7 +308,7 @@ public function setTtl($ttl) } /** - * Get time to life. + * Get time to live. * * @return float */ @@ -291,23 +320,24 @@ public function getTtl() /** * Set namespace. * - * @param string $namespace + * @param string $namespace * @return AbstractAdapter */ public function setNamespace($namespace) { $nameapace = (string)$namespace; if ($namespace === '') { - throw new InvalidArgumentException('No namespace given'); + throw new Exception\InvalidArgumentException('No namespace given'); } - if ( ($pattern = $this->getNamespacePattern()) - && !preg_match($pattern, $namespace)) { - throw new InvalidArgumentException( + if (($pattern = $this->getNamespacePattern()) + && !preg_match($pattern, $namespace) + ) { + throw new Exception\InvalidArgumentException( "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" ); } - $this->namespace = (string)$namespace; + $this->namespace = (string) $namespace; return $this; } @@ -324,30 +354,31 @@ public function getNamespace() /** * Set namespace pattern * - * @param null|string $pattern + * @param null|string $pattern * @return AbstractAdapter */ public function setNamespacePattern($pattern) { - if (($pattern = (string)$pattern) === '') { + if (($pattern = (string) $pattern) === '') { $this->namespacePattern = ''; - } else { - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - - // validate current namespace - } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { - throw new RuntimeException( - "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" - . " - please change the namespace first" - ); - } + return $this; + } + + // validate pattern + if (@preg_match($pattern, '') === false) { + $err = error_get_last(); + throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - $this->namespacePattern = $pattern; + // validate current namespace + } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { + throw new Exception\RuntimeException( + "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" + . " - please change the namespace first" + ); } + $this->namespacePattern = $pattern; + return $this; } @@ -364,23 +395,24 @@ public function getNamespacePattern() /** * Set key pattern * - * @param null|string $pattern + * @param null|string $pattern * @return AbstractAdapter */ public function setKeyPattern($pattern) { if (($pattern = (string)$pattern) === '') { $this->keyPattern = ''; - } else { - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - } + return $this; + } - $this->keyPattern = $pattern; + // validate pattern + if (@preg_match($pattern, '') === false) { + $err = error_get_last(); + throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); } + $this->keyPattern = $pattern; + return $this; } @@ -407,12 +439,12 @@ public function getKeyPattern() * - getItem, getMetadata, incrementItem[s], decrementItem[s], touchItem[s] * throws ItemNotFoundException * - * @param boolean $flag + * @param boolean $flag * @return Adapter */ public function setIgnoreMissingItems($flag) { - $this->ignoreMissingItems = (bool)$flag; + $this->ignoreMissingItems = (bool) $flag; return $this; } @@ -420,7 +452,7 @@ public function setIgnoreMissingItems($flag) * Ignore missing items * * @return boolean - * @see setIgnoreMissingItems() to get more information + * @see setIgnoreMissingItems() */ public function getIgnoreMissingItems() { @@ -429,15 +461,30 @@ public function getIgnoreMissingItems() /* Event/Plugin handling */ + /** + * Set event manager instance + * + * @param EventCollection $events + * @return AbstractAdapter + */ + public function setEventManager(EventCollection $events) + { + $this->events = $events; + return $this; + } + /** * Get the event manager * - * @return Zend\EventManager\EventManager + * @return EventManager */ public function events() { if ($this->events === null) { - $this->events = new EventManager(array(__CLASS__, get_class($this))); + $this->setEventManager(new EventManager(array( + __CLASS__, + get_class($this), + ))); } return $this->events; } @@ -445,11 +492,11 @@ public function events() /** * Trigger an pre event and return the event response collection * - * @param string $eventName - * @param ArrayObject $args - * @return Zend\EventManager\ResponseCollection All handler return values + * @param string $eventName + * @param ArrayObject $args + * @return \Zend\EventManager\ResponseCollection All handler return values */ - protected function triggerPre($eventName, \ArrayObject $args) + protected function triggerPre($eventName, ArrayObject $args) { return $this->events()->trigger(new Event($eventName . '.pre', $this, $args)); } @@ -457,15 +504,15 @@ protected function triggerPre($eventName, \ArrayObject $args) /** * Triggers the PostEvent and return the result value. * - * @param string $eventName - * @param ArrayObject $args - * @param mixed $result + * @param string $eventName + * @param ArrayObject $args + * @param mixed $result * @return mixed */ - protected function triggerPost($eventName, \ArrayObject $args, &$result) + protected function triggerPost($eventName, ArrayObject $args, &$result) { $postEvent = new PostEvent($eventName . '.post', $this, $args, $result); - $eventRs = $this->events()->trigger($postEvent); + $eventRs = $this->events()->trigger($postEvent); if ($eventRs->stopped()) { return $eventRs->last(); } @@ -479,16 +526,16 @@ protected function triggerPost($eventName, \ArrayObject $args, &$result) * If the ExceptionEvent has the flag "throwException" enabled throw the * exception after trigger else return the result. * - * @param string $eventName - * @param ArrayObject $args - * @param Exception $exception + * @param string $eventName + * @param ArrayObject $args + * @param \Exception $exception * @throws Exception * @return mixed */ - protected function triggerException($eventName, \ArrayObject $args, \Exception $exception) + protected function triggerException($eventName, ArrayObject $args, \Exception $exception) { $exceptionEvent = new ExceptionEvent($eventName . '.exception', $this, $args, $exception); - $eventRs = $this->events()->trigger($exceptionEvent); + $eventRs = $this->events()->trigger($exceptionEvent); if ($exceptionEvent->getThrowException()) { throw $exceptionEvent->getException(); @@ -504,7 +551,7 @@ protected function triggerException($eventName, \ArrayObject $args, \Exception $ /** * Check if a plugin is registered * - * @param Plugin $plugin + * @param Plugin $plugin * @return boolean */ public function hasPlugin(Plugin $plugin) @@ -515,14 +562,14 @@ public function hasPlugin(Plugin $plugin) /** * Register a plugin * - * @param Plugin $plugin - * @return Adapter Fluent interface - * @throws LogicException + * @param Plugin $plugin + * @return AbstractAdapter Fluent interface + * @throws Exception\LogicException */ public function addPlugin(Plugin $plugin) { if (in_array($plugin, $this->pluginRegistry, true)) { - throw new LogicException('Plugin already registered'); + throw new Exception\LogicException('Plugin already registered'); } $plugin->attach($this->events()); @@ -534,15 +581,15 @@ public function addPlugin(Plugin $plugin) /** * Unregister an already registered plugin * - * @param Plugin $plugin - * @return Adapter Fluent interface - * @throws LogicException + * @param Plugin $plugin + * @return AbstractAdapter Fluent interface + * @throws Exception\LogicException */ public function removePlugin(Plugin $plugin) { $pluginRegistryIndex = array_search($plugin, $this->pluginRegistry, true); if ($pluginRegistryIndex === false) { - throw new LogicException('Plugin not registered'); + throw new Exception\LogicException('Plugin not registered'); } $plugin->detach($this->events()); @@ -566,8 +613,8 @@ public function getPlugins() /** * Get items * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return array */ public function getItems(array $keys, array $options = array()) @@ -583,7 +630,7 @@ public function getItems(array $keys, array $options = array()) if ($value !== false) { $ret[$key] = $value; } - } catch (ItemNotFoundException $e) { + } catch (Exception\ItemNotFoundException $e) { // ignore missing items } } @@ -594,8 +641,8 @@ public function getItems(array $keys, array $options = array()) /** * Checks if adapter has an item * - * @param string $key - * @param array $options + * @param string $key + * @param array $options * @return bool */ public function hasItem($key, array $options = array()) @@ -606,7 +653,7 @@ public function hasItem($key, array $options = array()) try { $ret = ($this->getItem($key, $options) !== false); - } catch (ItemNotFoundException $e) { + } catch (Exception\ItemNotFoundException $e) { $ret = false; } @@ -616,8 +663,8 @@ public function hasItem($key, array $options = array()) /** * Checks if adapter has items * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return array */ public function hasItems(array $keys, array $options = array()) @@ -639,8 +686,8 @@ public function hasItems(array $keys, array $options = array()) /** * Get Metadatas * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return array */ public function getMetadatas(array $keys, array $options = array()) @@ -656,7 +703,7 @@ public function getMetadatas(array $keys, array $options = array()) if ($meta !== false) { $ret[$key] = $meta; } - } catch (ItemNotFoundException $e) { + } catch (Exception\ItemNotFoundException $e) { // ignore missing items } } @@ -669,8 +716,8 @@ public function getMetadatas(array $keys, array $options = array()) /** * Set items * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return bool */ public function setItems(array $keyValuePairs, array $options = array()) @@ -690,16 +737,16 @@ public function setItems(array $keyValuePairs, array $options = array()) /** * Add an item * - * @param $key - * @param $value - * @param array $options + * @param string|int $key + * @param mixed $value + * @param array $options * @return bool - * @throws RuntimeException + * @throws Exception\RuntimeException */ public function addItem($key, $value, array $options = array()) { if ($this->hasItem($key, $options)) { - throw new RuntimeException("Key '{$key}' already exists"); + throw new Exception\RuntimeException("Key '{$key}' already exists"); } return $this->setItem($key, $value, $options); } @@ -707,8 +754,8 @@ public function addItem($key, $value, array $options = array()) /** * Add items * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return bool */ public function addItems(array $keyValuePairs, array $options = array()) @@ -728,16 +775,16 @@ public function addItems(array $keyValuePairs, array $options = array()) /** * Replace an item * - * @param $key - * @param $value - * @param array $options + * @param string|int $key + * @param mixed $value + * @param array $options * @return bool - * @throws ItemNotFoundException + * @throws Exception\ItemNotFoundException */ public function replaceItem($key, $value, array $options = array()) { if (!$this->hasItem($key, $options)) { - throw new ItemNotFoundException("Key '{$key}' doen't exists"); + throw new Exception\ItemNotFoundException("Key '{$key}' doen't exists"); } return $this->setItem($key, $value, $options); } @@ -745,8 +792,8 @@ public function replaceItem($key, $value, array $options = array()) /** * Replace items * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return bool */ public function replaceItems(array $keyValuePairs, array $options = array()) @@ -766,10 +813,10 @@ public function replaceItems(array $keyValuePairs, array $options = array()) /** * Check and set item * - * @param $token - * @param $key - * @param $value - * @param array $options + * @param string $token + * @param string|int $key + * @param mixed $value + * @param array $options * @return bool */ public function checkAndSetItem($token, $key, $value, array $options = array()) @@ -785,8 +832,8 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) /** * Touch an item * - * @param $key - * @param array $options + * @param string|int $key + * @param array $options * @return bool */ public function touchItem($key, array $options = array()) @@ -819,8 +866,8 @@ public function touchItem($key, array $options = array()) /** * Touch items * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return bool */ public function touchItems(array $keys, array $options = array()) @@ -840,8 +887,8 @@ public function touchItems(array $keys, array $options = array()) /** * Remove items * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return bool */ public function removeItems(array $keys, array $options = array()) @@ -861,9 +908,9 @@ public function removeItems(array $keys, array $options = array()) /** * Increment an item * - * @param $key - * @param $value - * @param array $options + * @param string|int $key + * @param int|float $value + * @param array $options * @return bool|int */ public function incrementItem($key, $value, array $options = array()) @@ -872,8 +919,8 @@ public function incrementItem($key, $value, array $options = array()) return false; } - $value = (int)$value; - $get = (int)$this->getItem($key, $options); + $value = (int) $value; + $get = (int) $this->getItem($key, $options); $this->setItem($key, $get + $value, $options); return $get + $value; } @@ -881,8 +928,8 @@ public function incrementItem($key, $value, array $options = array()) /** * Increment items * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return bool */ public function incrementItems(array $keyValuePairs, array $options = array()) @@ -902,9 +949,9 @@ public function incrementItems(array $keyValuePairs, array $options = array()) /** * Decrement an item * - * @param $key - * @param $value - * @param array $options + * @param string|int $key + * @param int|float $value + * @param array $options * @return bool|int */ public function decrementItem($key, $value, array $options = array()) @@ -913,8 +960,8 @@ public function decrementItem($key, $value, array $options = array()) return false; } - $value = (int)$value; - $get = (int)$this->getItem($key, $options); + $value = (int) $value; + $get = (int) $this->getItem($key, $options); $this->setItem($key, $get - $value, $options); return $get - $value; } @@ -922,8 +969,8 @@ public function decrementItem($key, $value, array $options = array()) /** * Decrement items * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return bool */ public function decrementItems(array $keyValuePairs, array $options = array()) @@ -945,15 +992,15 @@ public function decrementItems(array $keyValuePairs, array $options = array()) /** * Get delayed * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return bool - * @throws InvalidArgumentException|RuntimeException + * @throws Exception\InvalidArgumentException|Exception\RuntimeException */ public function getDelayed(array $keys, array $options = array()) { if ($this->stmtActive) { - throw new RuntimeException('Statement already in use'); + throw new Exception\RuntimeException('Statement already in use'); } if (!$this->getReadable()) { @@ -976,7 +1023,7 @@ public function getDelayed(array $keys, array $options = array()) if (isset($options['callback'])) { $callback = $options['callback']; if (!is_callable($callback, false)) { - throw new InvalidArgumentException('Invalid callback'); + throw new Exception\InvalidArgumentException('Invalid callback'); } while ( ($item = $this->fetch()) !== false) { @@ -990,13 +1037,13 @@ public function getDelayed(array $keys, array $options = array()) /** * Find * - * @param int $mode - * @param array $options - * @throws UnsupportedMethodCallException + * @param int $mode + * @param array $options + * @throws Exception\UnsupportedMethodCallException */ public function find($mode = self::MATCH_ACTIVE, array $options = array()) { - throw new UnsupportedMethodCallException('find isn\'t supported by this adapter'); + throw new Exception\UnsupportedMethodCallException('find isn\'t supported by this adapter'); } /** @@ -1045,8 +1092,8 @@ public function fetch() } // goto next if not exists - if ( $exist === false - || ($exist === null && !$this->hasItem($key, $options)) + if ($exist === false + || ($exist === null && !$this->hasItem($key, $options)) ) { continue; } @@ -1070,7 +1117,7 @@ public function fetch() public function fetchAll() { $rs = array(); - while ( ($item = $this->fetch()) !== false ) { + while (($item = $this->fetch()) !== false) { $rs[] = $item; } return $rs; @@ -1081,13 +1128,13 @@ public function fetchAll() /** * Clear * - * @param int $mode - * @param array $options - * @throws RuntimeException + * @param int $mode + * @param array $options + * @throws Exception\RuntimeException */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { - throw new RuntimeException( + throw new Exception\RuntimeException( "This adapter doesn't support to clear items off all namespaces" ); } @@ -1095,13 +1142,13 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) /** * Clear by namespace * - * @param int $mode - * @param array $options - * @throws RuntimeException + * @param int $mode + * @param array $options + * @throws Exception\RuntimeException */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { - throw new RuntimeException( + throw new Exception\RuntimeException( "This adapter doesn't support to clear items by namespace" ); } @@ -1109,7 +1156,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a /** * Optimize * - * @param array $options + * @param array $options * @return bool */ public function optimize(array $options = array()) @@ -1127,8 +1174,8 @@ public function optimize(array $options = array()) public function getCapabilities() { if ($this->capabilities === null) { - $this->capabilityMarker = new \stdClass(); - $this->capabilities = new Capabilities($this->capabilityMarker); + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities($this->capabilityMarker); } return $this->capabilities; } @@ -1158,7 +1205,7 @@ protected function normalizeOptions(array &$options) // ignore_missing_items if (isset($options['ignore_missing_items'])) { - $options['ignore_missing_items'] = (bool)$options['ignore_missing_items']; + $options['ignore_missing_items'] = (bool) $options['ignore_missing_items']; } else { $options['ignore_missing_items'] = $this->getIgnoreMissingItems(); } @@ -1181,40 +1228,40 @@ protected function normalizeOptions(array &$options) /** * Validates and normalize a TTL. * - * @param int|float $ttl - * @throws InvalidArgumentException + * @param int|float $ttl + * @throws Exception\InvalidArgumentException */ protected function normalizeTtl(&$ttl) { if (!is_int($ttl)) { - $ttl = (float)$ttl; + $ttl = (float) $ttl; // convert to int if possible - if ($ttl === (float)(int)$ttl) { - $ttl = (int)$ttl; + if ($ttl === (float) (int) $ttl) { + $ttl = (int) $ttl; } } if ($ttl < 0) { - throw new InvalidArgumentException("TTL can't be negative"); + throw new Exception\InvalidArgumentException("TTL can't be negative"); } } /** * Validates and normalize a namespace. * - * @param string $namespace - * @throws InvalidArgumentException + * @param string $namespace + * @throws Exception\InvalidArgumentException */ protected function normalizeNamespace(&$namespace) { $namespace = (string)$namespace; if ($namespace === '') { - throw new InvalidArgumentException('Empty namespaces are nor allowed'); + throw new Exception\InvalidArgumentException('Empty namespaces are not allowed'); } elseif (($p = $this->getNamespacePattern()) && !preg_match($p, $namespace)) { - throw new InvalidArgumentException( - "The namespace '{$namespace}' doesn't match agains pattern '{$p}'" + throw new Exception\InvalidArgumentException( + "The namespace '{$namespace}' doesn't match against pattern '{$p}'" ); } } @@ -1222,19 +1269,19 @@ protected function normalizeNamespace(&$namespace) /** * Validates and normalize tags array * - * @param array $tags - * @throws Zend\Cache\InvalidArgumentException + * @param array $tags + * @throws Exception\InvalidArgumentException */ protected function normalizeTags(&$tags) { if (!is_array($tags)) { - throw new InvalidArgumentException('Tags have to be an array'); + throw new Exception\InvalidArgumentException('Tags have to be an array'); } foreach ($tags as &$tag) { - $tag = (string)$tag; + $tag = (string) $tag; if ($tag === '') { - throw new InvalidArgumentException('Empty tags are not allowed'); + throw new Exception\InvalidArgumentException('Empty tags are not allowed'); } } @@ -1249,7 +1296,7 @@ protected function normalizeTags(&$tags) protected function normalizeSelect(&$select) { if (!is_array($select)) { - $select = array((string)$select); + $select = array((string) $select); } else { $select = array_unique($select); } @@ -1258,34 +1305,35 @@ protected function normalizeSelect(&$select) /** * Normalize the matching mode needed on (clear and find) * + * @todo normalize matching mode with given tags * @param int $mode Matching mode to normalize * @param int $default Default matching mode */ protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOptions) { - $mode = (int)$mode; - if ( ($mode & self::MATCH_EXPIRED) != self::MATCH_EXPIRED - && ($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE) { - $mode = $mode | (int)$default; + $mode = (int) $mode; + if (($mode & self::MATCH_EXPIRED) != self::MATCH_EXPIRED + && ($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE + ) { + $mode = $mode | (int) $default; } - - // TODO: normalize matching mode with given tags } /** * Validates and normalizes a key * - * @param string $key + * @param string $key * @return string - * @throws InvalidArgumentException On an invalid key + * @throws Exception\InvalidArgumentException On an invalid key */ protected function normalizeKey(&$key) { - $key = (string)$key; + $key = (string) $key; if (($p = $this->getKeyPattern()) && !preg_match($p, $key)) { - throw new InvalidArgumentException("The key '{$key}' doesn't match agains pattern '{$p}'"); + throw new Exception\InvalidArgumentException( + "The key '{$key}' doesn't match agains pattern '{$p}'" + ); } } - } diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 2479c759d..ed28ed4da 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -14,33 +14,28 @@ * * @category Zend * @package Zend_Cache - * @subpackage Zend_Cache_Storage + * @subpackage Storage * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -/** - * @namespace - */ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Storage\Capabilities, - Zend\Cache\Exception\ExtensionNotLoadedException, - Zend\Cache\Exception\ItemNotFoundException, - Zend\Cache\Exception\RuntimeException, - APCIterator; + +use APCIterator, + ArrayObject, + stdClass, + Zend\Cache\Exception, + Zend\Cache\Storage\Capabilities; /** - * @uses \Zend\Cache\Cache - * @uses \Zend\Cache\Adapter - * @uses \Zend\Cache\Adapter\AbstractAdapter * @package Zend_Cache * @subpackage Zend_Cache_Storage + * @subpackage Storage * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Apc extends AbstractAdapter { - /** * Map selected properties on getDelayed & find * to APCIterator selector @@ -69,21 +64,22 @@ class Apc extends AbstractAdapter * Constructor * * @param array $options Option - * @throws \Zend\Cache\Exception + * @throws Exception * @return void */ public function __construct($options = array()) { if (version_compare('3.1.6', phpversion('apc')) > 0) { - throw new ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); + throw new Exception\ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); } $enabled = ini_get('apc.enabled'); if (PHP_SAPI == 'cli') { - $enabled = $enabled && (bool)ini_get('apc.enable_cli'); + $enabled = $enabled && (bool) ini_get('apc.enable_cli'); } + if (!$enabled) { - throw new ExtensionNotLoadedException( + throw new Exception\ExtensionNotLoadedException( "ext/apc is disabled - see 'apc.enabled' and 'apc.enable_cli'" ); } @@ -112,12 +108,23 @@ public function __construct($options = array()) /* options */ + /** + * Set namespace separator for keys + * + * @param string $separator + * @return Apc + */ public function setNamespaceSeparator($separator) { - $this->namespaceSeparator = (string)$separator; + $this->namespaceSeparator = (string) $separator; return $this; } + /** + * Get namespace separator for keys + * + * @return string + */ public function getNamespaceSeparator() { return $this->namespaceSeparator; @@ -125,6 +132,26 @@ public function getNamespaceSeparator() /* reading */ + /** + * Get an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return mixed Value on success and false on failure + * @throws Exception + * + * @triggers getItem.pre(PreEvent) + * @triggers getItem.post(PostEvent) + * @triggers getItem.exception(ExceptionEvent) + */ public function getItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -133,9 +160,9 @@ public function getItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -145,10 +172,10 @@ public function getItem($key, array $options = array()) } $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; - $result = apc_fetch($internalKey, $success); + $result = apc_fetch($internalKey, $success); if (!$success) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$internalKey}' not found"); + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } $result = false; } else { @@ -163,6 +190,24 @@ public function getItem($key, array $options = array()) } } + /** + * Get multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return array Assoziative array of existing keys and values or false on failure + * @throws Exception + * + * @triggers getItems.pre(PreEvent) + * @triggers getItems.post(PostEvent) + * @triggers getItems.exception(ExceptionEvent) + */ public function getItems(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -170,9 +215,9 @@ public function getItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -190,7 +235,7 @@ public function getItems(array $keys, array $options = array()) if (!$options['ignore_missing_items']) { if (count($keys) != count($fetch)) { $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); - throw new ItemNotFoundException('Keys not found: ' . $missing); + throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); } } @@ -207,6 +252,24 @@ public function getItems(array $keys, array $options = array()) } } + /** + * Test if an item exists. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers hasItem.pre(PreEvent) + * @triggers hasItem.post(PostEvent) + * @triggers hasItem.exception(ExceptionEvent) + */ public function hasItem($key, array $options = array()) { if (!$this->getReadable()) { @@ -215,9 +278,9 @@ public function hasItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -227,7 +290,7 @@ public function hasItem($key, array $options = array()) } $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; - $result = apc_exists($internalKey); + $result = apc_exists($internalKey); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { @@ -235,6 +298,24 @@ public function hasItem($key, array $options = array()) } } + /** + * Test if an item exists. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers hasItems.pre(PreEvent) + * @triggers hasItems.post(PostEvent) + * @triggers hasItems.exception(ExceptionEvent) + */ public function hasItems(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -242,9 +323,9 @@ public function hasItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -273,6 +354,22 @@ public function hasItems(array $keys, array $options = array()) } } + /** + * Get metadata of an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return array|boolean Metadata or false on failure + * @throws Exception + */ public function getMetadata($key, array $options = array()) { if (!$this->getReadable()) { @@ -283,9 +380,9 @@ public function getMetadata($key, array $options = array()) $this->normalizeKey($key); $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; - $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; - $regexp = '/^' . preg_quote($key, '/') . '$/'; - $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + $regexp = '/^' . preg_quote($key, '/') . '$/'; + $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); $metadata = $it->current(); // @see http://pecl.php.net/bugs/bug.php?id=22564 @@ -295,9 +392,7 @@ public function getMetadata($key, array $options = array()) if (!$metadata) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( - "Key '{$key}' nout found" - ); + throw new Exception\ItemNotFoundException("Key '{$key}' nout found"); } return false; @@ -307,6 +402,14 @@ public function getMetadata($key, array $options = array()) return $metadata; } + /** + * Get all metadata for an item + * + * @param array $keys + * @param array $options + * @return array + * @throws Exception\ItemNotFoundException + */ public function getMetadatas(array $keys, array $options = array()) { if (!$this->getReadable()) { @@ -333,14 +436,15 @@ public function getMetadatas(array $keys, array $options = array()) } $this->normalizeMetadata($metadata); - $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); + + $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); $ret[$key] = & $metadata; } if (!$options['ignore_missing_items']) { if (count($keys) != count($ret)) { $missing = implode("', '", array_diff($keys, array_keys($ret))); - throw new ItemNotFoundException('Keys not found: ' . $missing); + throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); } } @@ -349,6 +453,21 @@ public function getMetadatas(array $keys, array $options = array()) /* writing */ + /** + * Store an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + */ public function setItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -361,12 +480,26 @@ public function setItem($key, $value, array $options = array()) if (!apc_store($key, $value, $options['ttl'])) { $type = is_object($value) ? get_class($value) : gettype($value); - throw new RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); + throw new Exception\RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); } return true; } + /** + * Store multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Exception + */ public function setItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -383,7 +516,7 @@ public function setItems(array $keyValuePairs, array $options = array()) $errKeys = apc_store($keyValuePairs2, null, $options['ttl']); if ($errKeys) { - throw new RuntimeException( + throw new Exception\RuntimeException( "apc_store(, null, {$options['ttl']}) failed for keys: " . "'" . implode("','", $errKeys) . "'" ); @@ -392,6 +525,21 @@ public function setItems(array $keyValuePairs, array $options = array()) return true; } + /** + * Add an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + */ public function addItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -404,16 +552,30 @@ public function addItem($key, $value, array $options = array()) if (!apc_add($key, $value, $options['ttl'])) { if (apc_exists($key)) { - throw new RuntimeException("Key '{$key}' already exists"); + throw new Exception\RuntimeException("Key '{$key}' already exists"); } $type = is_object($value) ? get_class($value) : gettype($value); - throw new RuntimeException("apc_add('{$key}', <{$type}>, {$options['ttl']}) failed"); + throw new Exception\RuntimeException("apc_add('{$key}', <{$type}>, {$options['ttl']}) failed"); } return true; } + /** + * Add multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Exception + */ public function addItems(array $keyValuePairs, array $options = array()) { if (!$this->getWritable()) { @@ -430,7 +592,7 @@ public function addItems(array $keyValuePairs, array $options = array()) $errKeys = apc_add($keyValuePairs2, null, $options['ttl']); if ($errKeys) { - throw new RuntimeException( + throw new Exception\RuntimeException( "apc_add(, null, {$options['ttl']}) failed for keys: " . "'" . implode("','", $errKeys) . "'" ); @@ -439,6 +601,21 @@ public function addItems(array $keyValuePairs, array $options = array()) return true; } + /** + * Replace an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + */ public function replaceItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -450,17 +627,31 @@ public function replaceItem($key, $value, array $options = array()) $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; if (!apc_exists($key)) { - throw new ItemNotFoundException("Key '{$key}' doesn't exist"); + throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); } if (!apc_store($key, $value, $options['ttl'])) { $type = is_object($value) ? get_class($value) : gettype($value); - throw new RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); + throw new Exception\RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); } return true; } + /** + * Remove an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + */ public function removeItem($key, array $options = array()) { if (!$this->getWritable()) { @@ -473,13 +664,27 @@ public function removeItem($key, array $options = array()) if (!apc_delete($key)) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found"); + throw new Exception\ItemNotFoundException("Key '{$key}' not found"); } } return true; } + /** + * Remove multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + */ public function removeItems(array $keys, array $options = array()) { if (!$this->getWritable()) { @@ -494,13 +699,28 @@ public function removeItems(array $keys, array $options = array()) $errKeys = apc_delete($keys); if ($errKeys) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); + throw new Exception\ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); } } return true; } + /** + * Increment an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param int $value + * @param array $options + * @return int|boolean The new value of false on failure + * @throws Exception + */ public function incrementItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -519,18 +739,33 @@ public function incrementItem($key, $value, array $options = array()) $this->addItem($key, $value, $options); $newValue = $value; } else { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$internalKey}' not found" ); } } else { - throw new RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); } } return $newValue; } + /** + * Decrement an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param int $value + * @param array $options + * @return int|boolean The new value or false or failure + * @throws Exception + */ public function decrementItem($key, $value, array $options = array()) { if (!$this->getWritable()) { @@ -549,12 +784,12 @@ public function decrementItem($key, $value, array $options = array()) $this->addItem($key, -$value, $options); $newValue = -$value; } else { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$internalKey}' not found" ); } } else { - throw new RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); } } @@ -563,10 +798,18 @@ public function decrementItem($key, $value, array $options = array()) /* non-blocking */ + /** + * Get items that were marked to delay storage for purposes of removing blocking + * + * @param array $keys + * @param array $options + * @return bool + * @throws Exception + */ public function getDelayed(array $keys, array $options = array()) { if ($this->stmtActive) { - throw new RuntimeException('Statement already in use'); + throw new Exception\RuntimeException('Statement already in use'); } if (!$this->getReadable()) { @@ -605,10 +848,10 @@ public function getDelayed(array $keys, array $options = array()) $this->stmtActive = false; $this->stmtIterator = null; $this->stmtOptions = null; - throw new InvalidArgumentException('Invalid callback'); + throw new Exception\InvalidArgumentException('Invalid callback'); } - while ( ($item = $this->fetch()) !== false) { + while (($item = $this->fetch()) !== false) { call_user_func($callback, $item); } } @@ -616,10 +859,29 @@ public function getDelayed(array $keys, array $options = array()) return true; } + /** + * Find items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() + */ public function find($mode = self::MATCH_ACTIVE, array $options = array()) { if ($this->stmtActive) { - throw new RuntimeException('Statement already in use'); + throw new Exception\RuntimeException('Statement already in use'); } if (!$this->getReadable()) { @@ -650,6 +912,12 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) return true; } + /** + * Fetches the next item from result set + * + * @return array|boolean The next item or false + * @see fetchAll() + */ public function fetch() { if (!$this->stmtActive) { @@ -690,12 +958,46 @@ public function fetch() /* cleaning */ + /** + * Clear items off all namespaces. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Exception + * @see clearByNamespace() + */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { $this->normalizeOptions($options); return $this->clearByRegEx('/.*/', $mode, $options); } + /** + * Clear items by namespace. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * @see clear() + */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { $this->normalizeOptions($options); @@ -707,11 +1009,16 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a /* status */ + /** + * Get capabilities + * + * @return Capabilities + */ public function getCapabilities() { if ($this->capabilities === null) { - $this->capabilityMarker = new \stdClass(); - $this->capabilities = new Capabilities( + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( $this->capabilityMarker, array( 'supportedDatatypes' => array( @@ -722,16 +1029,23 @@ public function getCapabilities() 'string' => true, 'array' => true, 'object' => 'object', - 'resource' => false + 'resource' => false, ), 'supportedMetadata' => array( - 'mtime', 'ctime', 'atime', 'rtime', 'ttl', - 'num_hits', 'ref_count', 'mem_size', 'internal_key' + 'atime', + 'ctime', + 'internal_key', + 'mem_size', + 'mtime', + 'num_hits', + 'ref_count', + 'rtime', + 'ttl', ), 'maxTtl' => 0, 'staticTtl' => false, 'ttlPrecision' => 1, - 'useRequestTime' => (bool)ini_get('apc.use_request_time'), + 'useRequestTime' => (bool) ini_get('apc.use_request_time'), 'expiredRead' => false, 'maxKeyLength' => 5182, 'namespaceIsPrefix' => true, @@ -746,6 +1060,12 @@ public function getCapabilities() return $this->capabilities; } + /** + * Get storage capacity. + * + * @param array $options + * @return array|boolean Capacity as array or false on failure + */ public function getCapacity(array $options = array()) { $mem = apc_sma_info(true); @@ -758,6 +1078,14 @@ public function getCapacity(array $options = array()) /* internal */ + /** + * Clear cached items based on key regex + * + * @param string $regex + * @param int $mode + * @param array $options + * @return bool + */ protected function clearByRegEx($regex, $mode, array &$options) { if (!$this->getWritable()) { @@ -773,6 +1101,12 @@ protected function clearByRegEx($regex, $mode, array &$options) return apc_delete(new APCIterator('user', $regex, 0, 1, \APC_LIST_ACTIVE)); } + /** + * Normalize metadata to work with APC + * + * @param array $metadata + * @return void + */ protected function normalizeMetadata(array &$metadata) { // rename @@ -803,5 +1137,4 @@ protected function normalizeMetadata(array &$metadata) unset($metadata['key']); } } - } diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 345b88014..62bac5713 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1,18 +1,42 @@ namespaceSeparator = (string)$separator; + $this->namespaceSeparator = (string) $separator; $this->updateCapabilities(); return $this; } @@ -201,21 +225,21 @@ public function getNamespaceSeparator() * * @param string $dir * @return Filesystem - * @throws InvalidArgumentException + * @throws Exception\InvalidArgumentException */ public function setCacheDir($dir) { if ($dir !== null) { if (!is_dir($dir)) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Cache directory '{$dir}' not found or not a directoy" ); } elseif (!is_writable($dir)) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Cache directory '{$dir}' not writable" ); } elseif (!is_readable($dir)) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Cache directory '{$dir}' not readable" ); } @@ -252,7 +276,7 @@ public function setFilePerm($perm) if (is_string($perm)) { $perm = octdec($perm); } else { - $perm = (int)$perm; + $perm = (int) $perm; } // use umask @@ -272,26 +296,26 @@ public function getFilePerm() /** * Set file umask * - * @param $umask + * @param $umask * @return Filesystem - * @throws InvalidArgumentException + * @throws Exception\InvalidArgumentException */ public function setFileUmask($umask) { if (is_string($umask)) { $umask = octdec($umask); } else { - $umask = (int)$umask; + $umask = (int) $umask; } if ((~$umask & 0600) != 0600 ) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Invalid file umask or file permission: ' - . 'need permissions to read and write files by owner' + . 'need permissions to read and write files by owner' ); } elseif ((~$umask & 0111) > 0) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Invalid file umask or file permission: ' - . 'executable cache files are not allowed' + . 'executable cache files are not allowed' ); } @@ -312,7 +336,7 @@ public function getFileUmask() /** * Set file locking * - * @param bool $flag + * @param bool $flag * @return Filesystem */ public function setFileLocking($flag) @@ -334,12 +358,12 @@ public function getFileLocking() /** * Set file blocking * - * @param bool $flag + * @param bool $flag * @return Filesystem */ public function setFileBlocking($flag) { - $this->fileBlocking = (bool)$flag; + $this->fileBlocking = (bool) $flag; return $this; } @@ -356,12 +380,12 @@ public function getFileBlocking() /** * Set no atime * - * @param bool $flag + * @param bool $flag * @return Filesystem */ public function setNoAtime($flag) { - $this->noAtime = (bool)$flag; + $this->noAtime = (bool) $flag; $this->updateCapabilities(); return $this; } @@ -379,12 +403,12 @@ public function getNoAtime() /** * Set no ctime * - * @param bool $flag + * @param bool $flag * @return Filesystem */ public function setNoCtime($flag) { - $this->noCtime = (bool)$flag; + $this->noCtime = (bool) $flag; $this->updateCapabilities(); return $this; } @@ -410,7 +434,7 @@ public function setDirPerm($perm) if (is_string($perm)) { $perm = octdec($perm); } else { - $perm = (int)$perm; + $perm = (int) $perm; } // use umask @@ -432,20 +456,20 @@ public function getDirPerm() * * @param string|integer $umask * @return Filesystem - * @throws InvalidArgumentException + * @throws Exception\InvalidArgumentException */ public function setDirUmask($umask) { if (is_string($umask)) { $umask = octdec($umask); } else { - $umask = (int)$umask; + $umask = (int) $umask; } if ((~$umask & 0700) != 0700 ) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Invalid directory umask or directory permissions: ' - . 'need permissions to execute, read and write directories by owner' + . 'need permissions to execute, read and write directories by owner' ); } @@ -466,15 +490,15 @@ public function getDirUmask() /** * Set dir level * - * @param integer $level + * @param integer $level * @return Filesystem - * @throws InvalidArgumentException + * @throws Exception\InvalidArgumentException */ public function setDirLevel($level) { $level = (int)$level; if ($level < 0 || $level > 16) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "Directory level '{$level}' have to be between 0 and 16" ); } @@ -500,7 +524,7 @@ public function getDirLevel() */ public function setReadControl($flag) { - $this->readControl = (bool)$flag; + $this->readControl = (bool) $flag; return $this; } @@ -517,16 +541,16 @@ public function getReadControl() /** * Set real control algo * - * @param string $algo + * @param string $algo * @return Filesystem - * @throws InvalidArgumentException + * @throws Exception\InvalidArgumentException */ public function setReadControlAlgo($algo) { $algo = strtolower($algo); if (!in_array($algo, Utils::getHashAlgos())) { - throw new InvalidArgumentException("Unsupported hash algorithm '{$algo}"); + throw new Exception\InvalidArgumentException("Unsupported hash algorithm '{$algo}"); } $this->readControlAlgo = $algo; @@ -546,12 +570,12 @@ public function getReadControlAlgo() /** * Set clear stat cache * - * @param bool $flag + * @param bool $flag * @return Filesystem */ public function setClearStatCache($flag) { - $this->clearStatCache = (bool)$flag; + $this->clearStatCache = (bool) $flag; return $this; } @@ -570,8 +594,8 @@ public function getClearStatCache() /** * Get item * - * @param $key - * @param array $options + * @param $key + * @param array $options * @return bool|mixed */ public function getItem($key, array $options = array()) @@ -582,9 +606,9 @@ public function getItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -605,7 +629,7 @@ public function getItem($key, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -613,8 +637,8 @@ public function getItem($key, array $options = array()) /** * Get items * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return array|mixed */ public function getItems(array $keys, array $options = array()) @@ -627,9 +651,9 @@ public function getItems(array $keys, array $options = array()) // don't throw ItemNotFoundException on getItems $options['ignore_missing_items'] = true; - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -650,7 +674,7 @@ public function getItems(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -658,8 +682,8 @@ public function getItems(array $keys, array $options = array()) /** * Check for an item * - * @param $key - * @param array $options + * @param $key + * @param array $options * @return bool|mixed */ public function hasItem($key, array $options = array()) @@ -670,9 +694,9 @@ public function hasItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -687,7 +711,7 @@ public function hasItem($key, array $options = array()) $result = $this->internalHasItem($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -695,8 +719,8 @@ public function hasItem($key, array $options = array()) /** * Check for items * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return array|mixed */ public function hasItems(array $keys, array $options = array()) @@ -706,9 +730,9 @@ public function hasItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -729,7 +753,7 @@ public function hasItems(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -749,9 +773,9 @@ public function getMetadata($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -772,7 +796,7 @@ public function getMetadata($key, array $options = array()) $this->lastInfoAll = $result = $this->internalGetMetadata($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -794,9 +818,9 @@ public function getMetadatas(array $keys, array $options = array()) // don't throw ItemNotFoundException on getMetadatas $options['ignore_missing_items'] = true; - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -818,7 +842,7 @@ public function getMetadatas(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -841,10 +865,10 @@ public function setItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, - 'options' => & $options + 'options' => & $options, )); try { @@ -859,7 +883,7 @@ public function setItem($key, $value, array $options = array()) $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -878,9 +902,9 @@ public function setItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options + 'options' => & $options, )); try { @@ -899,7 +923,7 @@ public function setItems(array $keyValuePairs, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -921,10 +945,10 @@ public function replaceItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, - 'options' => & $options + 'options' => & $options, )); try { @@ -938,12 +962,12 @@ public function replaceItem($key, $value, array $options = array()) } if ( !$this->internalHasItem($key, $options) ) { - throw new ItemNotFoundException("Key '{$key}' doesn't exist"); + throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); } $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -963,9 +987,9 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options + 'options' => & $options, )); try { @@ -981,13 +1005,13 @@ public function replaceItems(array $keyValuePairs, array $options = array()) $result = true; foreach ($keyValuePairs as $key => $value) { if ( !$this->internalHasItem($key, $options) ) { - throw new ItemNotFoundException("Key '{$key}' doesn't exist"); + throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); } $result = $this->internalSetItem($key, $value, $options) && $result; } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1009,10 +1033,10 @@ public function addItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, - 'options' => & $options + 'options' => & $options, )); try { @@ -1026,12 +1050,12 @@ public function addItem($key, $value, array $options = array()) } if ( $this->internalHasItem($key, $options) ) { - throw new RuntimeException("Key '{$key}' already exist"); + throw new Exception\RuntimeException("Key '{$key}' already exist"); } $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1051,9 +1075,9 @@ public function addItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options + 'options' => & $options, )); try { @@ -1069,14 +1093,14 @@ public function addItems(array $keyValuePairs, array $options = array()) $result = true; foreach ($keyValuePairs as $key => $value) { if ( $this->internalHasItem($key, $options) ) { - throw new RuntimeException("Key '{$key}' already exist"); + throw new Exception\RuntimeException("Key '{$key}' already exist"); } $result = $this->internalSetItem($key, $value, $options) && $result; } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1099,11 +1123,11 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'token' => & $token, 'key' => & $key, 'value' => & $value, - 'options' => & $options + 'options' => & $options, )); try { @@ -1120,7 +1144,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) if ($options['ignore_missing_items']) { $result = false; } else { - throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + throw new Exception\ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); } } else { // use filemtime + filesize as CAS token @@ -1133,7 +1157,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1153,9 +1177,9 @@ public function touchItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -1173,7 +1197,7 @@ public function touchItem($key, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1192,9 +1216,9 @@ public function touchItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -1210,7 +1234,7 @@ public function touchItems(array $keys, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1230,9 +1254,9 @@ public function removeItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -1246,7 +1270,7 @@ public function removeItem($key, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1265,9 +1289,9 @@ public function removeItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -1283,7 +1307,7 @@ public function removeItems(array $keys, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1301,7 +1325,7 @@ public function removeItems(array $keys, array $options = array()) public function find($mode = self::MATCH_ACTIVE, array $options = array()) { if ($this->stmtActive) { - throw new RuntimeException('Statement already in use'); + throw new Exception\RuntimeException('Statement already in use'); } if (!$this->getReadable()) { @@ -1311,9 +1335,9 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); $options = array_merge($this->getOptions(), $options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'mode' => & $mode, - 'options' => & $options + 'options' => & $options, )); try { @@ -1338,12 +1362,12 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) $this->stmtMatch = $mode; $this->stmtOptions = $options; } catch (\Exception $e) { - throw new RuntimeException('Instantiating glob iterator failed', 0, $e); + throw new Exception\RuntimeException('Instantiating glob iterator failed', 0, $e); } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1359,7 +1383,7 @@ public function fetch() return false; } - $args = new \ArrayObject(); + $args = new ArrayObject(); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); @@ -1382,7 +1406,7 @@ public function fetch() } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1400,9 +1424,9 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'mode' => & $mode, - 'options' => & $options + 'options' => & $options, )); try { @@ -1413,7 +1437,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $result = $this->clearByPrefix('', $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1429,9 +1453,9 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a { $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'mode' => & $mode, - 'options' => & $options + 'options' => & $options, )); try { @@ -1443,7 +1467,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $prefix = $options['namespace'] . $this->getNamespaceSeparator(); $result = $this->clearByPrefix($prefix, $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1461,8 +1485,8 @@ public function optimize(array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( - 'options' => & $options + $args = new ArrayObject(array( + 'options' => & $options, )); try { @@ -1478,7 +1502,7 @@ public function optimize(array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1492,7 +1516,7 @@ public function optimize(array $options = array()) */ public function getCapabilities() { - $args = new \ArrayObject(); + $args = new ArrayObject(); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); @@ -1535,7 +1559,7 @@ public function getCapabilities() $result = $this->capabilities; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1548,7 +1572,7 @@ public function getCapabilities() */ public function getCapacity(array $options = array()) { - $args = new \ArrayObject(); + $args = new ArrayObject(); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); @@ -1558,7 +1582,7 @@ public function getCapacity(array $options = array()) $result = Utils::getDiskCapacity($this->getCacheDir()); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1594,7 +1618,7 @@ protected function internalSetItem($key, $value, array &$options) // throw exception with last error message $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } } } @@ -1654,7 +1678,7 @@ protected function internalRemoveItem($key, array &$options) $filespec = $this->getFileSpec($key, $options['namespace']); if (!$options['ignore_missing_items'] && !file_exists($filespec . '.dat')) { - throw new ItemNotFoundException("Key '{$key}' with file '{$filespec}.dat' not found"); + throw new Exception\ItemNotFoundException("Key '{$key}' with file '{$filespec}.dat' not found"); } $this->unlink($filespec . '.dat'); @@ -1678,7 +1702,7 @@ protected function internalGetItem($key, array &$options) if ($options['ignore_missing_items']) { return false; } else { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$key}' not found within namespace '{$options['namespace']}'" ); } @@ -1693,7 +1717,7 @@ protected function internalGetItem($key, array &$options) ) { $hashData = Utils::generateHash($info['algo'], $data, true); if ($hashData != $info['hash']) { - throw new UnexpectedValueException( + throw new Exception\UnexpectedValueException( 'ReadControl: Stored hash and computed hash don\'t match' ); } @@ -1749,7 +1773,7 @@ protected function internalGetMetadata($key, array &$options) { if ($options['ignore_missing_items']) { return false; } else { - throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + throw new Exception\ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); } } @@ -1775,13 +1799,13 @@ protected function internalTouchItem($key, array &$options) if ($options['ignore_missing_items']) { return false; } else { - throw new ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + throw new Exception\ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); } } if ( !@touch($keyInfo['filespec'] . '.dat') ) { $err = error_get_last(); - throw new RuntimeException($err['message']); + throw new Exception\RuntimeException($err['message']); } } @@ -1918,7 +1942,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; $glob = new \GlobIterator($find); } catch (\Exception $e) { - throw new RuntimeException('Instantiating GlobIterator failed', 0, $e); + throw new Exception\RuntimeException('Instantiating GlobIterator failed', 0, $e); } $time = time(); @@ -1956,22 +1980,27 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { - if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0) { + if (!isset($info['tags']) + || count(array_diff($opts['tags'], $info['tags'])) > 0 + ) { continue; } // if MATCH_NO_TAGS mode -> check if no given tag available in current cache - } elseif( ($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS ) { - if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags'])) { + } elseif(($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS) { + if (isset($info['tags']) + && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags']) + ) { continue; } // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { - if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags'])) { + if (!isset($info['tags']) + || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags']) + ) { continue; } - } } @@ -1989,8 +2018,8 @@ protected function clearByPrefix($prefix, $mode, array &$opts) /** * Removes directories recursive by namespace * - * @param string $dir Directory to delete - * @param string $prefix Namespace + Separator + * @param string $dir Directory to delete + * @param string $prefix Namespace + Separator * @return bool */ protected function rmDir($dir, $prefix) @@ -2017,8 +2046,8 @@ protected function rmDir($dir, $prefix) * Get an array of information about the cache key. * NOTE: returns false if cache doesn't hit. * - * @param string $key - * @param string $ns + * @param string $key + * @param string $ns * @return array|boolean */ protected function getKeyInfo($key, $ns) @@ -2038,7 +2067,7 @@ protected function getKeyInfo($key, $ns) $this->lastInfoAll = null; $this->lastInfo = array( 'filespec' => $filespec, - 'mtime' => $filemtime + 'mtime' => $filemtime, ); if (!$this->getNoCtime()) { @@ -2055,13 +2084,13 @@ protected function getKeyInfo($key, $ns) /** * Get file spec of the given key and namespace * - * @param string $key - * @param string $ns + * @param string $key + * @param string $ns * @return string */ protected function getFileSpec($key, $ns) { - $prefix = $ns . $this->getNamespaceSeparator(); + $prefix = $ns . $this->getNamespaceSeparator(); $lastInfoId = $prefix . $key; if ($this->lastInfoId == $lastInfoId) { return $this->lastInfo['filespec']; @@ -2073,7 +2102,7 @@ protected function getFileSpec($key, $ns) // create up to 256 directories per directory level $hash = md5($key); for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { - $path.= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; + $path .= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; } } @@ -2085,7 +2114,7 @@ protected function getFileSpec($key, $ns) * * @param string $file * @return array|boolean The info array or false if file wasn't found - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function readInfoFile($file) { if (!file_exists($file)) { @@ -2095,7 +2124,7 @@ protected function readInfoFile($file) { $info = @unserialize($this->getFileContent($file)); if (!is_array($info)) { $err = error_get_last(); - throw new RuntimeException("Corrupted info file '{$file}': {$err['message']}"); + throw new Exception\RuntimeException("Corrupted info file '{$file}': {$err['message']}"); } return $info; @@ -2106,7 +2135,7 @@ protected function readInfoFile($file) { * * @param string $file File complete path * @return string - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function getFileContent($file) { @@ -2115,12 +2144,12 @@ protected function getFileContent($file) $fp = @fopen($file, 'rb'); if ($fp === false) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } if (!flock($fp, \LOCK_SH)) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } $result = @stream_get_contents($fp); @@ -2128,7 +2157,7 @@ protected function getFileContent($file) $lastErr = error_get_last(); @flock($fp, \LOCK_UN); @fclose($fp); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } flock($fp, \LOCK_UN); @@ -2139,7 +2168,7 @@ protected function getFileContent($file) $result = @file_get_contents($file, false); if ($result === false) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } } @@ -2152,7 +2181,7 @@ protected function getFileContent($file) * @param string $file File complete path * @param string $data Data to write * @return bool - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function putFileContent($file, $data) { @@ -2163,7 +2192,7 @@ protected function putFileContent($file, $data) $fp = @fopen($file, 'cb'); if (!$fp) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } if(!flock($fp, \LOCK_EX | \LOCK_NB)) { @@ -2174,12 +2203,12 @@ protected function putFileContent($file, $data) if (!ftruncate($fp, 0)) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } if (!fwrite($fp, $data)) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } flock($fp, \LOCK_UN); @@ -2192,7 +2221,7 @@ protected function putFileContent($file, $data) if ( @file_put_contents($file, $data, $flags) === false ) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } } @@ -2211,7 +2240,7 @@ protected function unlink($file) { // only throw exception if file still exists after deleting if (file_exists($file)) { $lastErr = error_get_last(); - throw new RuntimeException($lastErr['message']); + throw new Exception\RuntimeException($lastErr['message']); } } } @@ -2248,5 +2277,4 @@ protected function updateCapabilities() ); } } - } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index ff68548d4..f3c9f6782 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -1,15 +1,41 @@ optional * - Throw exception on missing item or return false * - * @param string $key - * @param array $options + * @param string $key + * @param array $options * @return mixed Value on success and false on failure - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers getItem.pre(PreEvent) * @triggers getItem.post(PostEvent) @@ -58,9 +84,9 @@ public function getItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, - 'options' => & $options + 'options' => & $options, )); try { @@ -79,7 +105,7 @@ public function getItem($key, array $options = array()) if (!$exist) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); + throw new Exception\ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); } $result = false; } else { @@ -90,7 +116,7 @@ public function getItem($key, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -104,10 +130,10 @@ public function getItem($key, array $options = array()) * - namespace optional * - The namespace to use (Default: namespace of object) * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return array Assoziative array of existing keys and values or false on failure - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers getItems.pre(PreEvent) * @triggers getItems.post(PostEvent) @@ -120,9 +146,9 @@ public function getItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, - 'options' => & $options + 'options' => & $options, )); try { @@ -150,7 +176,7 @@ public function getItems(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -164,10 +190,10 @@ public function getItems(array $keys, array $options = array()) * - namespace optional * - The namespace to use (Default: namespace of object) * - * @param string $key - * @param array $options + * @param string $key + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers hasItem.pre(PreEvent) * @triggers hasItem.post(PostEvent) @@ -181,7 +207,7 @@ public function hasItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'options' => & $options, )); @@ -195,7 +221,7 @@ public function hasItem($key, array $options = array()) $result = $this->checkItem($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -211,10 +237,10 @@ public function hasItem($key, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param array $options + * @param string $key + * @param array $options * @return array|boolean Metadata or false on failure - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers getMetadata.pre(PreEvent) * @triggers getMetadata.post(PostEvent) @@ -228,7 +254,7 @@ public function getMetadata($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'options' => & $options, )); @@ -241,7 +267,7 @@ public function getMetadata($key, array $options = array()) if (!$this->checkItem($key, $options)) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$key}' not found on namespace '{$options['namespace']}'" ); } @@ -255,7 +281,7 @@ public function getMetadata($key, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -271,11 +297,11 @@ public function getMetadata($key, array $options = array()) * - tags optional * - An array of tags * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $key + * @param mixed $value + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers setItem.pre(PreEvent) * @triggers setItem.post(PostEvent) @@ -289,7 +315,7 @@ public function setItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, 'options' => & $options, @@ -306,7 +332,7 @@ public function setItem($key, $value, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -320,10 +346,10 @@ public function setItem($key, $value, array $options = array()) * - tags optional * - An array of tags * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers setItems.pre(PreEvent) * @triggers setItems.post(PostEvent) @@ -336,7 +362,7 @@ public function setItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, )); @@ -359,7 +385,7 @@ public function setItems(array $keyValuePairs, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -373,11 +399,11 @@ public function setItems(array $keyValuePairs, array $options = array()) * - tags optional * - An array of tags * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $key + * @param mixed $value + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers addItem.pre(PreEvent) * @triggers addItem.post(PostEvent) @@ -391,7 +417,7 @@ public function addItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, 'options' => & $options, @@ -405,13 +431,13 @@ public function addItem($key, $value, array $options = array()) $ns = $options['namespace']; if (isset($this->data[$ns][$key])) { - throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); + throw new Exception\RuntimeException("Key '{$key}' already exists within namespace '$ns'"); } $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -425,10 +451,10 @@ public function addItem($key, $value, array $options = array()) * - tags optional * - An array of tags * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers addItems.pre(PreEvent) * @triggers addItems.post(PostEvent) @@ -441,7 +467,7 @@ public function addItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, )); @@ -460,14 +486,14 @@ public function addItems(array $keyValuePairs, array $options = array()) $data = & $this->data[$ns]; foreach ($keyValuePairs as $key => $value) { if (isset($data[$key])) { - throw new RuntimeException("Key '{$key}' already exists within namespace '$ns'"); + throw new Exception\RuntimeException("Key '{$key}' already exists within namespace '$ns'"); } $data[$key] = array($value, microtime(true), $options['tags']); } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -481,11 +507,11 @@ public function addItems(array $keyValuePairs, array $options = array()) * - tags optional * - An array of tags * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $key + * @param mixed $value + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers replaceItem.pre(PreEvent) * @triggers replaceItem.post(PostEvent) @@ -499,7 +525,7 @@ public function replaceItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, 'options' => & $options, @@ -513,13 +539,13 @@ public function replaceItem($key, $value, array $options = array()) $ns = $options['namespace']; if (!isset($this->data[$ns][$key])) { - throw new ItemNotFoundException("Key '{$key}' doen't exists within namespace '$ns'"); + throw new Exception\ItemNotFoundException("Key '{$key}' doen't exists within namespace '$ns'"); } $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -533,10 +559,10 @@ public function replaceItem($key, $value, array $options = array()) * - tags optional * - An array of tags * - * @param array $keyValuePairs - * @param array $options + * @param array $keyValuePairs + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers replaceItems.pre(PreEvent) * @triggers replaceItems.post(PostEvent) @@ -549,7 +575,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = \ArrayObject(array( + $args = ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, )); @@ -562,13 +588,13 @@ public function replaceItems(array $keyValuePairs, array $options = array()) $ns = $options['namespace']; if (!isset($this->data[$ns])) { - throw new ItemNotFoundException("Namespace '$ns' doesn't exist"); + throw new Exception\ItemNotFoundException("Namespace '$ns' doesn't exist"); } $data = & $this->data[$ns]; foreach ($keyValuePairs as $key => $value) { if (!isset($data[$key])) { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$key}' doen't exists within namespace '$ns'" ); } @@ -577,7 +603,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -591,10 +617,10 @@ public function replaceItems(array $keyValuePairs, array $options = array()) * - namespace optional * - The namespace to use (Default: namespace of object) * - * @param string $key - * @param array $options + * @param string $key + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers touchItem.pre(PreEvent) * @triggers touchItem.post(PostEvent) @@ -608,7 +634,7 @@ public function touchItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'options' => & $options, )); @@ -625,7 +651,7 @@ public function touchItem($key, array $options = array()) $this->data[$ns][$key][1] = microtime(true); } else { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$key}' not found within namespace '{$ns}'" ); } @@ -636,7 +662,7 @@ public function touchItem($key, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -650,10 +676,10 @@ public function touchItem($key, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param array $options + * @param string $key + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers removeItem.pre(PreEvent) * @triggers removeItem.post(PostEvent) @@ -667,7 +693,7 @@ public function removeItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'options' => & $options, )); @@ -689,13 +715,13 @@ public function removeItem($key, array $options = array()) } else { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); + throw new Exception\ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); } } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -709,10 +735,10 @@ public function removeItem($key, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param array $keys - * @param array $options + * @param array $keys + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers removeItems.pre(PreEvent) * @triggers removeItems.post(PostEvent) @@ -725,7 +751,7 @@ public function removeItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'keys' => & $keys, 'options' => & $options, )); @@ -739,7 +765,7 @@ public function removeItems(array $keys, array $options = array()) $ns = $options['namespace']; if ($options['ignore_missing_items'] === false) { if (!isset($this->data[$ns])) { - throw new ItemNotFoundException("Namespace '{$ns}' is empty"); + throw new Exception\ItemNotFoundException("Namespace '{$ns}' is empty"); } $data = &$this->data[$ns]; @@ -754,7 +780,7 @@ public function removeItems(array $keys, array $options = array()) } if ($missingItems) { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Keys '" . implode("','", $missingItems) . "' not found on namespace '{$ns}'" ); } @@ -772,7 +798,7 @@ public function removeItems(array $keys, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -786,11 +812,11 @@ public function removeItems(array $keys, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param int $value - * @param array $options + * @param string $key + * @param int $value + * @param array $options * @return int|boolean The new value of false on failure - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers incrementItem.pre(PreEvent) * @triggers incrementItem.post(PostEvent) @@ -804,8 +830,8 @@ public function incrementItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $value = (int)$value; - $args = new \ArrayObject(array( + $value = (int) $value; + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, 'options' => & $options, @@ -825,7 +851,7 @@ public function incrementItem($key, $value, array $options = array()) $result = $data[$key][0]; } else { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$key}' not found within namespace '{$ns}'" ); } @@ -836,7 +862,7 @@ public function incrementItem($key, $value, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -850,11 +876,11 @@ public function incrementItem($key, $value, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param int $value - * @param array $options + * @param string $key + * @param int $value + * @param array $options * @return int|boolean The new value or false or failure - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers decrementItem.pre(PreEvent) * @triggers decrementItem.post(PostEvent) @@ -868,8 +894,8 @@ public function decrementItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $value = (int)$value; - $args = new \ArrayObject(array( + $value = (int) $value; + $args = new\ArrayObject(array( 'key' => & $key, 'value' => & $value, 'options' => & $options, @@ -889,7 +915,7 @@ public function decrementItem($key, $value, array $options = array()) $result = $data[$key][0]; } else { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException( + throw new Exception\ItemNotFoundException( "Key '{$key}' not found within namespace '{$ns}'" ); } @@ -900,7 +926,7 @@ public function decrementItem($key, $value, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -919,10 +945,10 @@ public function decrementItem($key, $value, array $options = array()) * - Tags to search for used with matching modes of * Zend\Cache\Storage\Adapter::MATCH_TAGS_* * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * @see fetch() * @see fetchAll() * @@ -937,12 +963,12 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) } if ($this->stmtActive) { - throw new RuntimeException('Statement already in use'); + throw new Exception\RuntimeException('Statement already in use'); } $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'mode' => & $mode, 'options' => & $options, )); @@ -953,7 +979,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) return $eventRs->last(); } - $tags = & $options['tags']; + $tags = & $options['tags']; $emptyTags = $keys = array(); foreach ($this->data[ $options['namespace'] ] as $key => &$item) { @@ -1006,7 +1032,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1015,7 +1041,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) * Fetches the next item from result set * * @return array|boolean The next item or false - * @throws Zend\Cache\Exception + * @throws Exception * @see fetchAll() * * @triggers fetch.pre(PreEvent) @@ -1029,7 +1055,7 @@ public function fetch() } try { - $args = new \ArrayObject(); + $args = new ArrayObject(); $eventRs = $this->triggerPre(__FUNCTION__, $args); if ($eventRs->stopped()) { return $eventRs->last(); @@ -1079,7 +1105,7 @@ public function fetch() } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1096,10 +1122,10 @@ public function fetch() * - Tags to search for used with matching modes of * Zend\Cache\Storage\Adapter::MATCH_TAGS_* * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options * @return boolean - * @throws Zend\Cache\Exception + * @throws Exception * @see clearByNamespace() * * @triggers clear.pre(PreEvent) @@ -1114,7 +1140,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'mode' => & $mode, 'options' => & $options, )); @@ -1135,7 +1161,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1152,8 +1178,8 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) * - Tags to search for used with matching modes of * Zend\Cache\Storage\Adapter::MATCH_TAGS_* * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options * @return boolean * @throws Zend\Cache\Exception * @see clear() @@ -1170,7 +1196,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new \ArrayObject(array( + $args = new ArrayObject(array( 'mode' => & $mode, 'options' => & $options, )); @@ -1191,7 +1217,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { + } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1209,7 +1235,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a */ public function getCapabilities() { - $args = new \ArrayObject(); + $args = new ArrayObject(); $eventRs = $this->triggerPre(__FUNCTION__, $args); if ($eventRs->stopped()) { @@ -1217,7 +1243,7 @@ public function getCapabilities() } if ($this->capabilities === null) { - $this->capabilityMarker = new \stdClass(); + $this->capabilityMarker = new stdClass(); $this->capabilities = new Capabilities( $this->capabilityMarker, array( @@ -1229,10 +1255,11 @@ public function getCapabilities() 'string' => true, 'array' => true, 'object' => true, - 'resource' => true + 'resource' => true, ), 'supportedMetadata' => array( - 'mtime', 'tags' + 'mtime', + 'tags', ), 'maxTtl' => PHP_INT_MAX, 'staticTtl' => false, @@ -1254,9 +1281,9 @@ public function getCapabilities() /** * Get storage capacity. * - * @param array $options + * @param array $options * @return array|boolean Capacity as array or false on failure - * @throws Zend\Cache\Exception + * @throws Exception * * @triggers getCapacity.pre(PreEvent) * @triggers getCapacity.post(PostEvent) @@ -1264,8 +1291,8 @@ public function getCapabilities() */ public function getCapacity(array $options = array()) { - $args = new \ArrayObject(array( - 'options' => & $options + $args = new ArrayObject(array( + 'options' => & $options, )); $eventRs = $this->triggerPre(__FUNCTION__, $args); diff --git a/src/Storage/AdapterBroker.php b/src/Storage/AdapterBroker.php index c81a6f91f..bcfe8c64f 100644 --- a/src/Storage/AdapterBroker.php +++ b/src/Storage/AdapterBroker.php @@ -14,20 +14,23 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache\Storage; -use Zend\Loader\PluginBroker, - Zend\Cache\Exception\RuntimeException; + +use Zend\Cache\Exception, + Zend\Loader\PluginBroker; /** * Broker for cache storage adapter instances * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class AdapterBroker extends PluginBroker @@ -42,12 +45,12 @@ class AdapterBroker extends PluginBroker * * @param mixed $plugin * @return true - * @throws RuntimeException + * @throws Exception\RuntimeException */ protected function validatePlugin($plugin) { if (!$plugin instanceof Adapter) { - throw new RuntimeException('Cache storage adapters must implement Zend\Cache\Storage\Adapter'); + throw new Exception\RuntimeException('Cache storage adapters must implement Zend\Cache\Storage\Adapter'); } return true; } diff --git a/src/Storage/AdapterLoader.php b/src/Storage/AdapterLoader.php index 6b511de97..8122a1f42 100644 --- a/src/Storage/AdapterLoader.php +++ b/src/Storage/AdapterLoader.php @@ -14,7 +14,8 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +28,8 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class AdapterLoader extends PluginClassLoader diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 05a262264..7555cbce6 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -1,13 +1,39 @@ eventManager === null) { - if (!class_exists('Zend\EventManager\EventManager')) { - throw new MissingDependencyException('Zend\EventManager not found'); - } + if ($this->eventManager instanceof EventManager) { + return $this->eventManager; + } - // create a new event manager object - $eventManager = new EventManager(); + if (!class_exists('Zend\EventManager\EventManager')) { + throw new Exception\MissingDependencyException('Zend\EventManager\EventManager not found'); + } - // trigger change event on change of a base capability - if ($this->baseCapabilities && $this->baseCapabilities->hasEventManager()) { - $onChange = function ($event) use ($eventManager) { - $eventManager->trigger('change', $event->getTarget(), $event->getParams()); - }; - $this->baseCapabilities->getEventManager()->attach('change', $onChange); - } + // create a new event manager object + $eventManager = new EventManager(); - // register event manager - $this->eventManager = $eventManager; + // trigger change event on change of a base capability + if ($this->baseCapabilities && $this->baseCapabilities->hasEventManager()) { + $onChange = function ($event) use ($eventManager) { + $eventManager->trigger('change', $event->getTarget(), $event->getParams()); + }; + $this->baseCapabilities->getEventManager()->attach('change', $onChange); } + + // register event manager + $this->eventManager = $eventManager; + return $this->eventManager; } @@ -173,37 +202,43 @@ public function getSupportedDatatypes() 'string' => true, 'array' => false, 'object' => false, - 'resource' => false + 'resource' => false, )); } /** * Set supported datatypes * - * @param \stdClass $marker - * @param array $datatypes - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param array $datatypes + * @return Capabilities Fluent interface */ - public function setSupportedDatatypes(\stdClass $marker, array $datatypes) + public function setSupportedDatatypes(stdClass $marker, array $datatypes) { $allTypes = array( - 'NULL', 'boolean', 'integer', 'double', - 'string', 'array', 'object', 'resource' + 'array', + 'boolean', + 'double', + 'integer', + 'NULL', + 'object', + 'resource', + 'string', ); // check/normalize datatype values foreach ($datatypes as $type => &$toType) { if (!in_array($type, $allTypes)) { - throw new InvalidArgumentException("Unknown datatype '{$type}'"); + throw new Exception\InvalidArgumentException("Unknown datatype '{$type}'"); } if (is_string($toType)) { $toType = strtolower($toType); if (!in_array($toType, $allTypes)) { - throw new InvalidArgumentException("Unknown datatype '{$toType}'"); + throw new Exception\InvalidArgumentException("Unknown datatype '{$toType}'"); } } else { - $toType = (bool)$toType; + $toType = (bool) $toType; } } @@ -229,15 +264,15 @@ public function getSupportedMetadata() /** * Set supported metadata * - * @param \stdClass $marker - * @param string[] $metadata - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param string[] $metadata + * @return Capabilities Fluent interface */ - public function setSupportedMetadata(\stdClass $marker, array $metadata) + public function setSupportedMetadata(stdClass $marker, array $metadata) { foreach ($metadata as $name) { if (!is_string($name)) { - throw new InvalidArgumentException('$metadata must be an array of strings'); + throw new Exception\InvalidArgumentException('$metadata must be an array of strings'); } } return $this->setCapability($marker, 'supportedMetadata', $metadata); @@ -256,15 +291,15 @@ public function getMaxTtl() /** * Set maximum supported time-to-live * - * @param \stdClass $marker - * @param int $maxTtl - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param int $maxTtl + * @return Capabilities Fluent interface */ - public function setMaxTtl(\stdClass $marker, $maxTtl) + public function setMaxTtl(stdClass $marker, $maxTtl) { $maxTtl = (int)$maxTtl; if ($maxTtl < 0) { - throw new InvalidArgumentException('$maxTtl must be greater or equal 0'); + throw new Exception\InvalidArgumentException('$maxTtl must be greater or equal 0'); } return $this->setCapability($marker, 'maxTtl', $maxTtl); } @@ -281,14 +316,13 @@ public function getStaticTtl() } /** - * Set if the time-to-live handled static (on write) - * or dynamic (on read) + * Set if the time-to-live handled static (on write) or dynamic (on read) * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setStaticTtl(\stdClass $marker, $flag) + public function setStaticTtl(stdClass $marker, $flag) { return $this->setCapability($marker, 'staticTtl', (bool)$flag); } @@ -306,15 +340,15 @@ public function getTtlPrecision() /** * Set time-to-live precision * - * @param \stdClass $marker - * @param float $ttlPrecision - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param float $ttlPrecision + * @return Capabilities Fluent interface */ - public function setTtlPrecision(\stdClass $marker, $ttlPrecision) + public function setTtlPrecision(stdClass $marker, $ttlPrecision) { - $ttlPrecision = (float)$ttlPrecision; + $ttlPrecision = (float) $ttlPrecision; if ($ttlPrecision <= 0) { - throw new InvalidArgumentException('$ttlPrecision must be greater than 0'); + throw new Exception\InvalidArgumentException('$ttlPrecision must be greater than 0'); } return $this->setCapability($marker, 'ttlPrecision', $ttlPrecision); } @@ -332,11 +366,11 @@ public function getUseRequestTime() /** * Set use request time * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setUseRequestTime(\stdClass $marker, $flag) + public function setUseRequestTime(stdClass $marker, $flag) { return $this->setCapability($marker, 'useRequestTime', (bool)$flag); } @@ -354,11 +388,11 @@ public function getExpiredRead() /** * Set if expired items are readable * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setExpiredRead(\stdClass $marker, $flag) + public function setExpiredRead(stdClass $marker, $flag) { return $this->setCapability($marker, 'expiredRead', (bool)$flag); } @@ -376,15 +410,15 @@ public function getMaxKeyLength() /** * Set maximum key lenth * - * @param \stdClass $marker - * @param int $maxKeyLength - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param int $maxKeyLength + * @return Capabilities Fluent interface */ - public function setMaxKeyLength(\stdClass $marker, $maxKeyLength) + public function setMaxKeyLength(stdClass $marker, $maxKeyLength) { - $maxKeyLength = (int)$maxKeyLength; + $maxKeyLength = (int) $maxKeyLength; if ($maxKeyLength < -1) { - throw new InvalidArgumentException('$maxKeyLength must be greater or equal than -1'); + throw new Exception\InvalidArgumentException('$maxKeyLength must be greater or equal than -1'); } return $this->setCapability($marker, 'maxKeyLength', $maxKeyLength); } @@ -402,11 +436,11 @@ public function getNamespaceIsPrefix() /** * Set if namespace support is implemented as prefix * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setNamespaceIsPrefix(\stdClass $marker, $flag) + public function setNamespaceIsPrefix(stdClass $marker, $flag) { return $this->setCapability($marker, 'namespaceIsPrefix', (bool)$flag); } @@ -424,13 +458,13 @@ public function getNamespaceSeparator() /** * Set the namespace separator if namespace is implemented as prefix * - * @param \stdClass $marker - * @param string $separator - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param string $separator + * @return Capabilities Fluent interface */ - public function setNamespaceSeparator(\stdClass $marker, $separator) + public function setNamespaceSeparator(stdClass $marker, $separator) { - return $this->setCapability($marker, 'namespaceSeparator', (string)$separator); + return $this->setCapability($marker, 'namespaceSeparator', (string) $separator); } /** @@ -446,11 +480,11 @@ public function getIterable() /** * Set if items are iterable * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setIterable(\stdClass $marker, $flag) + public function setIterable(stdClass $marker, $flag) { return $this->setCapability($marker, 'iterable', (bool)$flag); } @@ -468,11 +502,11 @@ public function getClearAllNamespaces() /** * Set support to clear items of all namespaces * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setClearAllNamespaces(\stdClass $marker, $flag) + public function setClearAllNamespaces(stdClass $marker, $flag) { return $this->setCapability($marker, 'clearAllNamespaces', (bool)$flag); } @@ -490,11 +524,11 @@ public function getClearByNamespace() /** * Set support to clear items by namespace * - * @param \stdClass $marker - * @param boolean $flag - * @return Zend\Cache\Storage\Capabilities Fluent interface + * @param stdClass $marker + * @param boolean $flag + * @return Capabilities Fluent interface */ - public function setClearByNamespace(\stdClass $marker, $flag) + public function setClearByNamespace(stdClass $marker, $flag) { return $this->setCapability($marker, 'clearByNamespace', (bool)$flag); } @@ -502,8 +536,8 @@ public function setClearByNamespace(\stdClass $marker, $flag) /** * Get a capability * - * @param string $name - * @param mixed $default + * @param string $name + * @param mixed $default * @return mixed */ protected function getCapability($name, $default = null) @@ -521,16 +555,16 @@ protected function getCapability($name, $default = null) /** * Change a capability * - * @param \stdClass $marker - * @param string $name - * @param mixed $value - * @return Zend\Cache\Storage\Capabilities Fluent interface - * @throws InvalidArgumentException + * @param stdClass $marker + * @param string $name + * @param mixed $value + * @return Capabilities Fluent interface + * @throws Exception\InvalidArgumentException */ - protected function setCapability(\stdClass $marker, $name, $value) + protected function setCapability(stdClass $marker, $name, $value) { if ($this->marker !== $marker) { - throw new InvalidArgumentException('Invalid marker'); + throw new Exception\InvalidArgumentException('Invalid marker'); } $property = '_' . $name; @@ -543,5 +577,4 @@ protected function setCapability(\stdClass $marker, $name, $value) return $this; } - } diff --git a/src/Storage/Event.php b/src/Storage/Event.php index 43d5045f3..4ec07c27e 100644 --- a/src/Storage/Event.php +++ b/src/Storage/Event.php @@ -1,21 +1,46 @@ getTarget(); } - } - diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index 50883344c..61668414e 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -1,14 +1,40 @@ throwException = (bool)$flag; + $this->throwException = (bool) $flag; return $this; } @@ -93,7 +119,7 @@ public function getThrowException() /** * Set the result/return value * - * @param mixed $value + * @param mixed $value * @return ExceptionEvent */ public function setResult(&$value) @@ -111,6 +137,4 @@ public function & getResult() { return $this->result; } - } - diff --git a/src/Storage/Plugin.php b/src/Storage/Plugin.php index f1bd266a2..68b2f3361 100644 --- a/src/Storage/Plugin.php +++ b/src/Storage/Plugin.php @@ -1,12 +1,48 @@ $value) { $m = 'set' . str_replace('_', '', $name); + if (!method_exists($this, $m)) { + continue; + } $this->$m($value); } return $this; @@ -84,15 +121,17 @@ public function getClearingFactor() /** * Set automatic clearing factor * - * @param int $factor - * @return Zend\Cache\Storage\Plugin\ClearByFactor Fluent interface - * @throws InvalidArgumentException + * @param int $factor + * @return ClearByFactor Fluent interface + * @throws Exception\InvalidArgumentException */ public function setClearingFactor($factor) { - $factor = (int)$factor; + $factor = (int) $factor; if ($factor < 0) { - throw new InvalidArgumentAxception("Invalid clearing factor '{$factor}': must be greater or equal 0"); + throw new Exception\InvalidArgumentAxception( + "Invalid clearing factor '{$factor}': must be greater or equal 0" + ); } $this->clearingFactor = $factor; @@ -112,27 +151,27 @@ public function getClearByNamespace() /** * Set flag to clear items by namespace * - * @param boolean $flag - * @return Zend\Cache\Storage\Plugin\ClearByFactor Fluent interface + * @param boolean $flag + * @return ClearByFactor Fluent interface */ public function setClearByNamespace($flag) { - $this->clearByNamespace = $flag; + $this->clearByNamespace = (bool) $flag; return $this; } /** * Attach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return ClearByFactor - * @throws LogicException + * @throws Exception\LogicException */ public function attach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (isset($this->handles[$index])) { - throw new LogicException('Plugin already attached'); + throw new Exception\LogicException('Plugin already attached'); } $handles = array(); @@ -149,15 +188,15 @@ public function attach(EventCollection $eventCollection) /** * Detach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return ClearByFactor - * @throws LogicException + * @throws Exception\LogicException */ public function detach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (!isset($this->handles[$index])) { - throw new LogicException('Plugin not attached'); + throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index @@ -174,7 +213,7 @@ public function detach(EventCollection $eventCollection) /** * Clear storage by factor on a success _RESULT_ * - * @param Zend\Cache\Storage\PostEvent $event + * @param PostEvent $event * @return void */ public function clearByFactor(PostEvent $event) @@ -189,5 +228,4 @@ public function clearByFactor(PostEvent $event) } } } - } diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 9bc5fde6c..481b48e9f 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -1,14 +1,40 @@ $value) { $m = 'set' . str_replace('_', '', $name); + if (!method_exists($this, $m)) { + continue; + } $this->$m($value); } return $this; @@ -70,14 +107,14 @@ public function getOptions() /** * Set callback * - * @param null|callback $callback + * @param null|callable $callback * @return ExceptionHandler - * @throws InvalidArgumentException + * @throws ExceptionHandler\InvalidArgumentException */ public function setCallback($callback) { if ($callback !== null && !is_callable($callback, true)) { - throw new InvalidArgumentException('Not a valid callback'); + throw new ExceptionHandler\InvalidArgumentException('Not a valid callback'); } $this->callback = $callback; return $this; @@ -85,6 +122,8 @@ public function setCallback($callback) /** * Get callback + * + * @return null|callable */ public function getCallback() { @@ -94,13 +133,12 @@ public function getCallback() /** * Set throw exceptions * - * @param bool $flag + * @param bool $flag * @return ExceptionHandler - * @return void */ public function setThrowExceptions($flag) { - $this->throwExceptions = (bool)$flag; + $this->throwExceptions = (bool) $flag; return $this; } @@ -117,15 +155,15 @@ public function getThrowExceptions() /** * Attach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return ExceptionHandler - * @throws LogicException + * @throws Exception\LogicException */ public function attach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (isset($this->handles[$index])) { - throw new LogicException('Plugin already attached'); + throw new Exception\LogicException('Plugin already attached'); } $callback = array($this, 'onException'); @@ -188,15 +226,15 @@ public function attach(EventCollection $eventCollection) /** * Detach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return ExceptionHandler - * @throws LogicException + * @throws Exception\LogicException */ public function detach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (!isset($this->handles[$index])) { - throw new LogicException('Plugin not attached'); + throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index @@ -213,16 +251,15 @@ public function detach(EventCollection $eventCollection) /** * On exception * - * @param \ExceptionEvent $event + * @param ExceptionEvent $event * @return void */ public function onException(ExceptionEvent $event) { - if ( ($callback = $this->getCallback()) ) { - $callback($event->getException()); + if (($callback = $this->getCallback())) { + call_user_func($callback, $event->getException()); } - $event->setThrowException( $this->getThrowExceptions() ); + $event->setThrowException($this->getThrowExceptions()); } - } diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index 7e12d7960..9726c2511 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -1,16 +1,41 @@ $value) { $m = 'set' . str_replace('_', '', $name); + if (!method_exists($this, $m)) { + continue; + } $this->$m($value); } return $this; @@ -59,7 +95,7 @@ public function setOptions($options) public function getOptions() { return array( - 'optimizing_factor' => $this->getOptimizingFactor() + 'optimizing_factor' => $this->getOptimizingFactor(), ); } @@ -76,15 +112,17 @@ public function getOptimizingFactor() /** * Set automatic optimizing factor * - * @param int $factor + * @param int $factor * @return OptimizeByFactor - * @throws InvalidArgumentAxception + * @throws Exception\InvalidArgumentAxception */ public function setOptimizingFactor($factor) { - $factor = (int)$factor; + $factor = (int) $factor; if ($factor < 0) { - throw new InvalidArgumentAxception("Invalid optimizing factor '{$factor}': must be greater or equal 0"); + throw new Exception\InvalidArgumentAxception( + "Invalid optimizing factor '{$factor}': must be greater or equal 0" + ); } $this->optimizingFactor = $factor; @@ -94,15 +132,15 @@ public function setOptimizingFactor($factor) /** * Attach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return OptimizeByFactor - * @throws LogicException + * @throws Exception\LogicException */ public function attach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (isset($this->handles[$index])) { - throw new LogicException('Plugin already attached'); + throw new Exception\LogicException('Plugin already attached'); } $handles = array(); @@ -119,15 +157,15 @@ public function attach(EventCollection $eventCollection) /** * Detach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return OptimizeByFactor - * @throws LogicException + * @throws Exception\LogicException */ public function detach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (!isset($this->handles[$index])) { - throw new LogicException('Plugin not attached'); + throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index @@ -144,7 +182,7 @@ public function detach(EventCollection $eventCollection) /** * Optimize by factor on a success _RESULT_ * - * @param PostEvent $event + * @param PostEvent $event * @return void */ public function optimizeByFactor(PostEvent $event) @@ -155,5 +193,4 @@ public function optimizeByFactor(PostEvent $event) $event->getStorage()->optimize($params['options']); } } - } diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 43bc1ce10..c2ab444ae 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -1,18 +1,46 @@ $value) { - $m = 'set' . $name; + $m = 'set' . str_replace('_', '', $name); + if (!method_exists($this, $m)) { + continue; + } $this->$m($value); } return $this; @@ -75,7 +114,7 @@ public function getOptions() /** * Set serializer * - * @param SerializerAdapter $serializer + * @param SerializerAdapter $serializer * @return Serializer */ public function setSerializer(SerializerAdapter $serializer) @@ -100,15 +139,15 @@ public function getSerializer() /** * Attach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return Serializer - * @throws LogicException + * @throws Exception\LogicException */ public function attach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (isset($this->handles[$index])) { - throw new LogicException('Plugin already attached'); + throw new Exception\LogicException('Plugin already attached'); } $handles = array(); @@ -150,15 +189,15 @@ public function attach(EventCollection $eventCollection) /** * Detach * - * @param EventCollection $eventCollection + * @param EventCollection $eventCollection * @return Serializer - * @throws LogicException + * @throws Exception\LogicException */ public function detach(EventCollection $eventCollection) { - $index = \spl_object_hash($eventCollection); + $index = spl_object_hash($eventCollection); if (!isset($this->handles[$index])) { - throw new LogicException('Plugin not attached'); + throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index @@ -175,21 +214,21 @@ public function detach(EventCollection $eventCollection) /** * On read item post * - * @param PostEvent $event + * @param PostEvent $event * @return void */ public function onReadItemPost(PostEvent $event) { $serializer = $this->getSerializer(); - $result = $event->getResult(); - $result = $serializer->unserialize($result); + $result = $event->getResult(); + $result = $serializer->unserialize($result); $event->setResult($result); } /** * On read items post * - * @param PostEvent $event + * @param PostEvent $event * @return void */ public function onReadItemsPost(PostEvent $event) @@ -205,7 +244,7 @@ public function onReadItemsPost(PostEvent $event) /** * On fetch post * - * @param PostEvent $event + * @param PostEvent $event * @return void */ public function onFetchPost(PostEvent $event) @@ -220,7 +259,7 @@ public function onFetchPost(PostEvent $event) /** * On fetch all post * - * @param PostEvent $event + * @param PostEvent $event * @return void */ public function onFetchAllPost(PostEvent $event) @@ -238,7 +277,7 @@ public function onFetchAllPost(PostEvent $event) /** * On write item pre * - * @param Event $event + * @param Event $event * @return void */ public function onWriteItemPre(Event $event) @@ -251,7 +290,7 @@ public function onWriteItemPre(Event $event) /** * On write items pre * - * @param Event $event + * @param Event $event * @return void */ public function onWriteItemsPre(Event $event) @@ -266,24 +305,32 @@ public function onWriteItemsPre(Event $event) /** * On increment item pre * - * @param Event $event + * @param Event $event * @return mixed */ public function onIncrementItemPre(Event $event) { $event->stopPropagation(true); - $cache = $event->getTarget(); - $params = $event->getParams(); - $token = null; - $oldValue = $cache->getItem($params['key'], array('token' => &$token) + $params['options']); - return $cache->checkAndSetItem($token, $oldValue + $params['value'], $params['key'], $params['options']); + $cache = $event->getTarget(); + $params = $event->getParams(); + $token = null; + $oldValue = $cache->getItem( + $params['key'], + array('token' => &$token) + $params['options'] + ); + return $cache->checkAndSetItem( + $token, + $oldValue + $params['value'], + $params['key'], + $params['options'] + ); } /** * On increment items pre * - * @param Event $event + * @param Event $event * @return mixed */ public function onIncrementItemsPre(Event $event) @@ -306,32 +353,40 @@ public function onIncrementItemsPre(Event $event) /** * On decrement item pre * - * @param Event $event + * @param Event $event * @return mixed */ public function onDecrementItemPre(Event $event) { $event->stopPropagation(true); - $cache = $event->getTarget(); - $params = $event->getParams(); - $token = null; - $oldValue = $cache->getItem($params['key'], array('token' => &$token) + $params['options']); - return $cache->checkAndSetItem($token, $oldValue - $params['value'], $params['key'], $params['options']); + $cache = $event->getTarget(); + $params = $event->getParams(); + $token = null; + $oldValue = $cache->getItem( + $params['key'], + array('token' => &$token) + $params['options'] + ); + return $cache->checkAndSetItem( + $token, + $oldValue - $params['value'], + $params['key'], + $params['options'] + ); } /** * On decrement items pre * - * @param Event $event + * @param Event $event * @return mixed */ public function onDecrementItemsPre(Event $event) { $event->stopPropagation(true); - $cache = $event->getTarget(); - $params = $event->getParams(); + $cache = $event->getTarget(); + $params = $event->getParams(); $keyValuePairs = $cache->getItems(array_keys($params['keyValuePairs']), $params['options']); foreach ($params['keyValuePairs'] as $key => &$value) { if (isset($keyValuePairs[$key])) { @@ -346,17 +401,17 @@ public function onDecrementItemsPre(Event $event) /** * On get capabilities * - * @param PostEvent $event + * @param PostEvent $event * @return void */ public function onGetCapabilitiesPost(PostEvent $event) { $baseCapabilities = $event->getResult(); - $index = \spl_object_hash($baseCapabilities); + $index = spl_object_hash($baseCapabilities); if (!isset($this->capabilities[$index])) { $this->capabilities[$index] = new Capabilities( - new \stdClass(), // marker + new stdClass(), // marker array('supportedDatatypes' => array( 'NULL' => true, 'boolean' => true, @@ -373,5 +428,4 @@ public function onGetCapabilitiesPost(PostEvent $event) $event->setResult($this->capabilities[$index]); } - } diff --git a/src/Storage/PluginBroker.php b/src/Storage/PluginBroker.php index f9e4c6057..930c95e36 100644 --- a/src/Storage/PluginBroker.php +++ b/src/Storage/PluginBroker.php @@ -14,24 +14,26 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Cache\Storage; -use Zend\Loader, - Zend\Cache\Exception\RuntimeException; +use Zend\Cache\Exception, + Zend\Loader\PluginBroker as BasePluginBroker; /** * Broker for cache storage plugin instances * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class PluginBroker extends Loader\PluginBroker +class PluginBroker extends BasePluginBroker { /** * Default class loader @@ -50,7 +52,9 @@ class PluginBroker extends Loader\PluginBroker protected function validatePlugin($plugin) { if (!$plugin instanceof Plugin) { - throw new RuntimeException('Cache storage plugins must implement Zend\Cache\Storage\Plugin'); + throw new Exception\RuntimeException( + 'Cache storage plugins must implement Zend\Cache\Storage\Plugin' + ); } return true; } diff --git a/src/Storage/PluginLoader.php b/src/Storage/PluginLoader.php index d7edd74c9..6a3c01519 100644 --- a/src/Storage/PluginLoader.php +++ b/src/Storage/PluginLoader.php @@ -14,7 +14,8 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +28,8 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * @subpackage Storage + * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PluginLoader extends PluginClassLoader diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index 1a17e1f5f..ff48e7a4f 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -1,11 +1,37 @@ result; } - } - diff --git a/src/StorageFactory.php b/src/StorageFactory.php index b61dc7a86..bb83c943b 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -1,24 +1,50 @@ toArray(); - } elseif (!is_array($cfg)) { - throw new InvalidArgumentException( - 'The factory needs an instance of \Zend\Config\Config ' - . 'or an associative array as argument' + if ($cfg instanceof Traversable) { + $cfg = IteratorToArray::convert($cfg); + } + + if (!is_array($cfg)) { + throw new Exception\InvalidArgumentException( + 'The factory needs an associative array ' + . 'or a Traversable object as an argument' ); } // instantiate the adapter if (!isset($cfg['adapter'])) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Missing "adapter"' ); } elseif (is_array($cfg['adapter'])) { if (!isset($cfg['adapter']['name'])) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Missing "adapter.name"' ); } @@ -56,15 +84,15 @@ public static function factory($cfg) $name = $cfg['adapter']['name']; $options = isset($cfg['adapter']['options']) ? $cfg['adapter']['options'] : array(); - $adapter = self::adapterFactory($name, $options); + $adapter = static::adapterFactory($name, $options); } else { - $adapter = self::adapterFactory($cfg['adapter']); + $adapter = static::adapterFactory($cfg['adapter']); } // add plugins if (isset($cfg['plugins'])) { if (!is_array($cfg['plugins'])) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Plugins needs to be an array' ); } @@ -73,14 +101,14 @@ public static function factory($cfg) if (is_string($k)) { $name = $k; if (!is_array($v)) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( "'plugins.{$k}' needs to be an array" ); } $options = $v; } elseif (is_array($v)) { if (!isset($v['name'])) { - throw new InvalidArgumentException("Invalid plugins[{$k}] or missing plugins[{$k}].name"); + throw new Exception\InvalidArgumentException("Invalid plugins[{$k}] or missing plugins[{$k}].name"); } $name = (string)$v['name']; if (isset($v['options'])) { @@ -93,7 +121,7 @@ public static function factory($cfg) $options = array(); } - $plugin = self::pluginFactory($name, $options); + $plugin = static::pluginFactory($name, $options); $adapter->addPlugin($plugin); } } @@ -101,7 +129,7 @@ public static function factory($cfg) // set adapter or plugin options if (isset($cfg['options'])) { if (!is_array($cfg['options'])) { - throw new InvalidArgumentException( + throw new Exception\InvalidArgumentException( 'Options needs to be an array' ); } @@ -115,10 +143,10 @@ public static function factory($cfg) /** * Instantiate a storage adapter * - * @param string|Zend\Cache\Storage\Adapter $adapterName - * @param array|Zend\Config $options - * @return Zend\Cache\Storage\Adapter - * @throws Zend\Cache\RuntimeException + * @param string|Storage\Adapter $adapterName + * @param array|Traversable $options + * @return Storage\Adapter + * @throws Exception\RuntimeException */ public static function adapterFactory($adapterName, $options = array()) { @@ -128,31 +156,31 @@ public static function adapterFactory($adapterName, $options = array()) return $adapterName; } - return self::getAdapterBroker()->load($adapterName, $options); + return static::getAdapterBroker()->load($adapterName, $options); } /** * Get the adapter broker * - * @return Zend\Loader\Broker + * @return Broker */ public static function getAdapterBroker() { - if (self::$adapterBroker === null) { - self::$adapterBroker = new Storage\AdapterBroker(); + if (static::$adapterBroker === null) { + static::$adapterBroker = new Storage\AdapterBroker(); } - return self::$adapterBroker; + return static::$adapterBroker; } /** * Change the adapter broker * - * @param Zend\Loader\Broker $broker + * @param Broker $broker * @return void */ public static function setAdapterBroker(Broker $broker) { - self::$adapterBroker = $broker; + static::$adapterBroker = $broker; } /** @@ -162,16 +190,16 @@ public static function setAdapterBroker(Broker $broker) */ public static function resetAdapterBroker() { - self::$adapterBroker = new Storage\AdapterBroker(); + static::$adapterBroker = new Storage\AdapterBroker(); } /** * Instantiate a storage plugin * - * @param string|Zend\Cache\Storage\Plugin $pluginName - * @param array|Zend\Config $options - * @return Zend\Cache\Storage\Plugin - * @throws Zend\Cache\RuntimeException + * @param string|Storage\Plugin $pluginName + * @param array|Traversable $options + * @return Storage\Plugin + * @throws Exception\RuntimeException */ public static function pluginFactory($pluginName, $options = array()) { @@ -181,31 +209,31 @@ public static function pluginFactory($pluginName, $options = array()) return $pluginName; } - return self::getPluginBroker()->load($pluginName, $options); + return static::getPluginBroker()->load($pluginName, $options); } /** * Get the plugin broker * - * @return Zend\Loader\Broker + * @return Broker */ public static function getPluginBroker() { - if (self::$pluginBroker === null) { - self::$pluginBroker = new Storage\PluginBroker(); + if (static::$pluginBroker === null) { + static::$pluginBroker = new Storage\PluginBroker(); } - return self::$pluginBroker; + return static::$pluginBroker; } /** * Change the plugin broker * - * @param Zend\Loader\Broker $broker + * @param Broker $broker * @return void */ public static function setPluginBroker(Broker $broker) { - self::$pluginBroker = $broker; + static::$pluginBroker = $broker; } /** @@ -215,7 +243,6 @@ public static function setPluginBroker(Broker $broker) */ public static function resetPluginBroker() { - self::$pluginBroker = new Storage\PluginBroker(); + static::$pluginBroker = new Storage\PluginBroker(); } - } diff --git a/src/Utils.php b/src/Utils.php index 3b29231b2..1d08165b9 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -1,30 +1,52 @@ $memSize, - 'free' => $memFree + 'free' => $memFree, ); } @@ -59,21 +81,21 @@ static public function getPhpMemoryCapacity() * Get system memory capacity * * @return array - * @throws RuntimeException + * @throws Exception\RuntimeException */ static public function getSystemMemoryCapacity() { // Windows if (substr(\PHP_OS, 0, 3) == 'WIN') { - return self::_getSystemMemoryCapacityWin(); + return self::getSystemMemoryCapacityWin(); } // *nix - if ( !($meminfo = @file_get_contents('/proc/meminfo')) ) { + if (false === ($meminfo = @file_get_contents('/proc/meminfo'))) { $lastErr = error_get_last(); - throw new RuntimeException("Can't read '/proc/meminfo': {$lastErr['messagae']}"); + throw new Exception\RuntimeException("Can't read '/proc/meminfo': {$lastErr['messagae']}"); } elseif (!preg_match_all('/(\w+):\s*(\d+\s*\w*)[\r|\n]/i', $meminfo, $matches, PREG_PATTERN_ORDER)) { - throw new RuntimeException("Can't parse '/proc/meminfo'"); + throw new Exception\RuntimeException("Can't parse '/proc/meminfo'"); } $meminfoIndex = array_flip($matches[1]); @@ -97,7 +119,7 @@ static public function getSystemMemoryCapacity() return array( 'total' => $memTotal, - 'free' => $memFree + 'free' => $memFree, ); } @@ -105,14 +127,14 @@ static public function getSystemMemoryCapacity() * Get system memory capacity on windows systems * * @return array - * @throws RuntimeException + * @throws Exception\RuntimeException */ - static protected function _getSystemMemoryCapacityWin() + static protected function getSystemMemoryCapacityWin() { if (function_exists('win32_ps_stat_mem')) { $memstat = win32_ps_stat_mem(); } elseif (!function_exists('exec')) { - throw new RuntimeException( + throw new Exception\RuntimeException( "Missing php extension 'win32ps' and the build-in function 'exec' is disabled" ); } else { @@ -126,41 +148,42 @@ static protected function _getSystemMemoryCapacityWin() $line = exec($cmd, $out, $ret); if ($ret) { $out = implode("\n", $out); - throw new RuntimeException( + throw new Exception\RuntimeException( "Command '{$cmd}' failed" - . ", return: '{$ret}'" - . ", output: '{$out}'" + . ", return: '{$ret}'" + . ", output: '{$out}'" ); } elseif (!($memstat = @unserialize($line)) ) { $err = error_get_last(); $out = implode("\n", $out); - throw new RuntimeException( + throw new Exception\RuntimeException( "Can't parse output of command '{$cmd}'" - . ": {$err['message']}" - . ", output: '{$out}'" + . ": {$err['message']}" + . ", output: '{$out}'" ); } } if (!isset($memstat['total_phys'], $memstat['avail_phys'])) { - throw new RuntimeException("Can't detect memory status"); + throw new Exception\RuntimeException("Can't detect memory status"); } return array( 'total' => $memstat['total_phys'], - 'free' => $memstat['avail_phys'] + 'free' => $memstat['avail_phys'], ); } /** * Generate a hash value. + * * This helper adds the virtual hash algo "strlen". * * @param string $data Name of selected hashing algorithm * @param string $data Message to be hashed. * @param bool $raw When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits. * @return string Hash value - * @throws RuntimeException + * @throws Exception\RuntimeException */ static public function generateHash($algo, $data, $raw = false) { @@ -174,7 +197,7 @@ static public function generateHash($algo, $data, $raw = false) } else { $hash = hash($algo, $data, $raw); if ($hash === false) { - throw new RuntimeException("Hash generation failed for algo '{$algo}'"); + throw new Exception\RuntimeException("Hash generation failed for algo '{$algo}'"); } } @@ -189,7 +212,7 @@ static public function generateHash($algo, $data, $raw = false) */ static public function getHashAlgos() { - $algos = hash_algos(); + $algos = hash_algos(); $algos[] = 'strlen'; return $algos; } @@ -199,12 +222,12 @@ static public function getHashAlgos() * * @param string $memStr * @return float - * @throws RuntimeException + * @throws Exception\RuntimeException */ static protected function bytesFromString($memStr) { if (!preg_match('/\s*([\-\+]?\d+)\s*(\w*)\s*/', $memStr, $matches)) { - throw new RuntimeException("Can't detect bytes of string '{$memStr}'"); + throw new Exception\RuntimeException("Can't detect bytes of string '{$memStr}'"); } $value = (float)$matches[1]; @@ -231,10 +254,9 @@ static protected function bytesFromString($memStr) break; default: - throw new RuntimeException("Unknown unit '{$unit}'"); + throw new Exception\RuntimeException("Unknown unit '{$unit}'"); } return $value; } - } From d35fa3b9f1564f939f8b2b27ebf5e2ed28832067 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 13 Dec 2011 00:03:51 +0100 Subject: [PATCH 138/311] implemented all missing events of apc adapter --- src/Storage/Adapter/Apc.php | 868 ++++++++++++++++++++++++------------ 1 file changed, 595 insertions(+), 273 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index ed28ed4da..8a29b66ad 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -110,8 +110,8 @@ public function __construct($options = array()) /** * Set namespace separator for keys - * - * @param string $separator + * + * @param string $separator * @return Apc */ public function setNamespaceSeparator($separator) @@ -122,7 +122,7 @@ public function setNamespaceSeparator($separator) /** * Get namespace separator for keys - * + * * @return string */ public function getNamespaceSeparator() @@ -369,6 +369,10 @@ public function hasItems(array $keys, array $options = array()) * @param array $options * @return array|boolean Metadata or false on failure * @throws Exception + * + * @triggers getMetadata.pre(PreEvent) + * @triggers getMetadata.post(PostEvent) + * @triggers getMetadata.exception(ExceptionEvent) */ public function getMetadata($key, array $options = array()) { @@ -378,37 +382,54 @@ public function getMetadata($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; - $regexp = '/^' . preg_quote($key, '/') . '$/'; - $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); - $metadata = $it->current(); + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; - // @see http://pecl.php.net/bugs/bug.php?id=22564 - if (!apc_exists($key)) { - $metadata = false; - } + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + $regexp = '/^' . preg_quote($internalKey, '/') . '$/'; + $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $metadata = $it->current(); - if (!$metadata) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$key}' nout found"); + // @see http://pecl.php.net/bugs/bug.php?id=22564 + if (!apc_exists($internalKey)) { + $metadata = false; } - return false; - } + if (!$metadata) { + if (!$options['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + } + } else { + $this->normalizeMetadata($metadata); + } - $this->normalizeMetadata($metadata); - return $metadata; + return $this->triggerPost(__FUNCTION__, $args, $metadata); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** * Get all metadata for an item - * - * @param array $keys - * @param array $options + * + * @param array $keys + * @param array $options * @return array * @throws Exception\ItemNotFoundException + * + * @triggers getMetadatas.pre(PreEvent) + * @triggers getMetadatas.post(PostEvent) + * @triggers getMetadatas.exception(ExceptionEvent) */ public function getMetadatas(array $keys, array $options = array()) { @@ -417,38 +438,51 @@ public function getMetadatas(array $keys, array $options = array()) } $this->normalizeOptions($options); - $nsl = strlen($options['namespace']); - - $keysRegExp = array(); - foreach ($keys as &$key) { - $keysRegExp[] = preg_quote($options['namespace'] . $this->getNamespaceSeparator() . $key, '/'); - } - $regexp = '/^(' . implode('|', $keysRegExp) . ')$/'; + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); - $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); - $ret = array(); - foreach ($it as $internalKey => $metadata) { - // @see http://pecl.php.net/bugs/bug.php?id=22564 - if (!apc_exists($internalKey)) { - continue; + $keysRegExp = array(); + foreach ($keys as $key) { + $keysRegExp[] = preg_quote($key, '/'); } + $regexp = '/^' + . preg_quote($options['namespace'] . $this->getNamespaceSeparator(), '/') + . '(' . implode('|', $keysRegExp) . ')' + . '$/'; + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; - $this->normalizeMetadata($metadata); + $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $result = array(); + $prefixL = strlen($options['namespace'] . $this->getNamespaceSeparator()); + foreach ($it as $internalKey => $metadata) { + // @see http://pecl.php.net/bugs/bug.php?id=22564 + if (!apc_exists($internalKey)) { + continue; + } - $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); - $ret[$key] = & $metadata; - } + $this->normalizeMetadata($metadata); + $result[ substr($internalKey, $prefixL) ] = & $metadata; + } - if (!$options['ignore_missing_items']) { - if (count($keys) != count($ret)) { - $missing = implode("', '", array_diff($keys, array_keys($ret))); - throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); + if (!$options['ignore_missing_items']) { + if (count($keys) != count($result)) { + $missing = implode("', '", array_diff($keys, array_keys($result))); + throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); + } } - } - return $ret; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* writing */ @@ -467,6 +501,10 @@ public function getMetadatas(array $keys, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers setItem.pre(PreEvent) + * @triggers setItem.post(PostEvent) + * @triggers setItem.exception(ExceptionEvent) */ public function setItem($key, $value, array $options = array()) { @@ -476,14 +514,31 @@ public function setItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); - if (!apc_store($key, $value, $options['ttl'])) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - return true; + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + if (!apc_store($internalKey, $value, $options['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "apc_store('{$internalKey}', <{$type}>, {$options['ttl']}) failed" + ); + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -499,6 +554,10 @@ public function setItem($key, $value, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers setItems.pre(PreEvent) + * @triggers setItems.post(PostEvent) + * @triggers setItems.exception(ExceptionEvent) */ public function setItems(array $keyValuePairs, array $options = array()) { @@ -507,22 +566,37 @@ public function setItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); - $keyValuePairs2 = array(); - foreach ($keyValuePairs as $key => &$value) { - $keyValuePairs2[ $options['namespace'] . $this->getNamespaceSeparator() . $key ] = &$value; - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $errKeys = apc_store($keyValuePairs2, null, $options['ttl']); + $internalKeyValuePairs = array(); + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + foreach ($keyValuePairs as $key => &$value) { + $internalKey = $prefix . $key; + $internalKeyValuePairs[$internalKey] = &$value; + } - if ($errKeys) { - throw new Exception\RuntimeException( - "apc_store(, null, {$options['ttl']}) failed for keys: " - . "'" . implode("','", $errKeys) . "'" - ); - } + $errKeys = apc_store($internalKeyValuePairs, null, $options['ttl']); + if ($errKeys) { + throw new Exception\RuntimeException( + "apc_store(, null, {$options['ttl']}) failed for keys: " + . "'" . implode("','", $errKeys) . "'" + ); + } - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -539,6 +613,10 @@ public function setItems(array $keyValuePairs, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers addItem.pre(PreEvent) + * @triggers addItem.post(PostEvent) + * @triggers addItem.exception(ExceptionEvent) */ public function addItem($key, $value, array $options = array()) { @@ -548,18 +626,35 @@ public function addItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); - if (!apc_add($key, $value, $options['ttl'])) { - if (apc_exists($key)) { - throw new Exception\RuntimeException("Key '{$key}' already exists"); + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException("apc_add('{$key}', <{$type}>, {$options['ttl']}) failed"); - } + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + if (!apc_add($internalKey, $value, $options['ttl'])) { + if (apc_exists($internalKey)) { + throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); + } + + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "apc_add('{$internalKey}', <{$type}>, {$options['ttl']}) failed" + ); + } - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -575,6 +670,10 @@ public function addItem($key, $value, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers addItems.pre(PreEvent) + * @triggers addItems.post(PostEvent) + * @triggers addItems.exception(ExceptionEvent) */ public function addItems(array $keyValuePairs, array $options = array()) { @@ -583,22 +682,37 @@ public function addItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); - $keyValuePairs2 = array(); - foreach ($keyValuePairs as $key => &$value) { - $keyValuePairs2[ $options['namespace'] . $this->getNamespaceSeparator() . $key ] = &$value; - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $errKeys = apc_add($keyValuePairs2, null, $options['ttl']); + $internalKeyValuePairs = array(); + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + foreach ($keyValuePairs as $key => &$value) { + $internalKey = $prefix . $key; + $internalKeyValuePairs[$internalKey] = &$value; + } - if ($errKeys) { - throw new Exception\RuntimeException( - "apc_add(, null, {$options['ttl']}) failed for keys: " - . "'" . implode("','", $errKeys) . "'" - ); - } + $errKeys = apc_add($internalKeyValuePairs, null, $options['ttl']); + if ($errKeys) { + throw new Exception\RuntimeException( + "apc_add(, null, {$options['ttl']}) failed for keys: " + . "'" . implode("','", $errKeys) . "'" + ); + } - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -615,6 +729,10 @@ public function addItems(array $keyValuePairs, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers replaceItem.pre(PreEvent) + * @triggers replaceItem.post(PostEvent) + * @triggers replaceItem.exception(ExceptionEvent) */ public function replaceItem($key, $value, array $options = array()) { @@ -624,18 +742,37 @@ public function replaceItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); - if (!apc_exists($key)) { - throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - if (!apc_store($key, $value, $options['ttl'])) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException("apc_store('{$key}', <{$type}>, {$options['ttl']}) failed"); - } + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + if (!apc_exists($internalKey)) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' doesn't exist" + ); + } - return true; + if (!apc_store($internalKey, $value, $options['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "apc_store('{$internalKey}', <{$type}>, {$options['ttl']}) failed" + ); + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -651,6 +788,10 @@ public function replaceItem($key, $value, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers removeItem.pre(PreEvent) + * @triggers removeItem.post(PostEvent) + * @triggers removeItem.exception(ExceptionEvent) */ public function removeItem($key, array $options = array()) { @@ -660,15 +801,30 @@ public function removeItem($key, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); - if (!apc_delete($key)) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$key}' not found"); + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - } - return true; + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + if (!apc_delete($internalKey)) { + if (!$options['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + } + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -684,6 +840,10 @@ public function removeItem($key, array $options = array()) * @param array $options * @return boolean * @throws Exception + * + * @triggers removeItems.pre(PreEvent) + * @triggers removeItems.post(PostEvent) + * @triggers removeItems.exception(ExceptionEvent) */ public function removeItems(array $keys, array $options = array()) { @@ -692,18 +852,35 @@ public function removeItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - foreach ($keys as &$key) { - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; - } + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); - $errKeys = apc_delete($keys); - if ($errKeys) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $internalKeys = array(); + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + foreach ($keys as $key) { + $internalKeys[] = $prefix . $key; + } + + $errKeys = apc_delete($internalKeys); + if ($errKeys) { + if (!$options['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); + } } - } - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -718,8 +895,12 @@ public function removeItems(array $keys, array $options = array()) * @param string $key * @param int $value * @param array $options - * @return int|boolean The new value of false on failure + * @return int|boolean The new value or false on failure * @throws Exception + * + * @triggers incrementItem.pre(PreEvent) + * @triggers incrementItem.post(PostEvent) + * @triggers incrementItem.exception(ExceptionEvent) */ public function incrementItem($key, $value, array $options = array()) { @@ -729,26 +910,37 @@ public function incrementItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); - $value = (int)$value; - $newValue = apc_inc($internalKey, $value); - if ($newValue === false) { - if (!apc_exists($internalKey)) { - if ($options['ignore_missing_items']) { - $this->addItem($key, $value, $options); - $newValue = $value; - } else { + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $value = (int)$value; + $newValue = apc_inc($internalKey, $value); + if ($newValue === false) { + if (apc_exists($internalKey)) { + throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + } elseif (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$internalKey}' not found" ); } - } else { - throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + + $this->addItem($key, $value, $options); + $newValue = $value; } - } - return $newValue; + return $this->triggerPost(__FUNCTION__, $args, $newValue); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -765,6 +957,10 @@ public function incrementItem($key, $value, array $options = array()) * @param array $options * @return int|boolean The new value or false or failure * @throws Exception + * + * @triggers decrementItem.pre(PreEvent) + * @triggers decrementItem.post(PostEvent) + * @triggers decrementItem.exception(ExceptionEvent) */ public function decrementItem($key, $value, array $options = array()) { @@ -774,89 +970,111 @@ public function decrementItem($key, $value, array $options = array()) $this->normalizeOptions($options); $this->normalizeKey($key); - $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); - $value = (int)$value; - $newValue = apc_dec($internalKey, $value); - if ($newValue === false) { - if (!apc_exists($internalKey)) { - if ($options['ignore_missing_items']) { - $this->addItem($key, -$value, $options); - $newValue = -$value; - } else { + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $value = (int)$value; + $newValue = apc_dec($internalKey, $value); + if ($newValue === false) { + if (apc_exists($internalKey)) { + throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + } elseif (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$internalKey}' not found" ); } - } else { - throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + + $this->addItem($key, -$value, $options); + $newValue = -$value; } - } - return $newValue; + return $this->triggerPost(__FUNCTION__, $args, $newValue); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* non-blocking */ /** * Get items that were marked to delay storage for purposes of removing blocking - * - * @param array $keys - * @param array $options + * + * @param array $keys + * @param array $options * @return bool * @throws Exception + * + * @triggers getDelayed.pre(PreEvent) + * @triggers getDelayed.post(PostEvent) + * @triggers getDelayed.exception(ExceptionEvent) */ public function getDelayed(array $keys, array $options = array()) { if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); - } - - if (!$this->getReadable()) { + } elseif (!$this->getReadable()) { return false; - } - - if (!$keys) { + } elseif (!$keys) { return true; } $this->normalizeOptions($options); + if (isset($options['callback']) && !is_callable($options['callback'], false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); - $prefix = preg_quote($prefix, '/'); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); - $format = 0; - foreach ($options['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - } - $search = array(); - foreach ($keys as $key) { - $search[] = preg_quote($key, '/'); - } - $search = '/^' . $prefix . '(' . implode('|', $search) . ')$/'; - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = &$options; - - if (isset($options['callback'])) { - $callback = $options['callback']; - if (!is_callable($callback, false)) { - $this->stmtActive = false; - $this->stmtIterator = null; - $this->stmtOptions = null; - throw new Exception\InvalidArgumentException('Invalid callback'); + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = preg_quote($prefix, '/'); + + $format = 0; + foreach ($options['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; + } } - while (($item = $this->fetch()) !== false) { - call_user_func($callback, $item); + $search = array(); + foreach ($keys as $key) { + $search[] = preg_quote($key, '/'); } - } + $search = '/^' . $prefix . '(' . implode('|', $search) . ')$/'; - return true; + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = &$options; + + if (isset($options['callback'])) { + $callback = $options['callback']; + while (($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -877,39 +1095,54 @@ public function getDelayed(array $keys, array $options = array()) * @throws Exception * @see fetch() * @see fetchAll() + * + * @triggers find.pre(PreEvent) + * @triggers find.post(PostEvent) + * @triggers find.exception(ExceptionEvent) */ public function find($mode = self::MATCH_ACTIVE, array $options = array()) { if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); - } - - if (!$this->getReadable()) { + } elseif (!$this->getReadable()) { return false; } $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - if (($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE) { - // This adapter doen't support to read expired items - return true; - } - - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); - $search = '/^' . preg_quote($prefix, '/') . '+/'; + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); - $format = 0; - foreach ($options['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - } - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = &$options; + // This adapter doesn't support to read expired items + if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $search = '/^' . preg_quote($prefix, '/') . '+/'; + + $format = 0; + foreach ($options['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; + } + } + + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = &$options; + } - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -917,6 +1150,10 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) * * @return array|boolean The next item or false * @see fetchAll() + * + * @triggers fetch.pre(PreEvent) + * @triggers fetch.post(PostEvent) + * @triggers fetch.exception(ExceptionEvent) */ public function fetch() { @@ -924,36 +1161,47 @@ public function fetch() return false; } - do { - if (!$this->stmtIterator->valid()) { - // clear stmt - $this->stmtActive = false; - $this->stmtIterator = null; - $this->stmtOptions = null; + $args = new ArrayObject(); - return false; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - // @see http://pecl.php.net/bugs/bug.php?id=22564 - $exist = apc_exists($this->stmtIterator->key()); + $prefixL = strlen($this->stmtOptions['namespace'] . $this->getNamespaceSeparator()); - if ($exist) { - $metadata = $this->stmtIterator->current(); - $this->normalizeMetadata($metadata); + do { + if (!$this->stmtIterator->valid()) { + // clear stmt + $this->stmtActive = false; + $this->stmtIterator = null; + $this->stmtOptions = null; - $select = $this->stmtOptions['select']; - if (in_array('key', $select)) { - $internalKey = $this->stmtIterator->key(); - $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); - $metadata['key'] = $key; + $result = false; + break; } - } - $this->stmtIterator->next(); + // @see http://pecl.php.net/bugs/bug.php?id=22564 + $exist = apc_exists($this->stmtIterator->key()); + if ($exist) { + $result = $this->stmtIterator->current(); + $this->normalizeMetadata($result); + + $select = $this->stmtOptions['select']; + if (in_array('key', $select)) { + $internalKey = $this->stmtIterator->key(); + $result['key'] = substr($internalKey, $prefixL); + } + } - } while (!$exist); + $this->stmtIterator->next(); + } while (!$exist); - return $metadata; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* cleaning */ @@ -973,11 +1221,35 @@ public function fetch() * @return boolean * @throws Exception * @see clearByNamespace() + * + * @triggers clear.pre(PreEvent) + * @triggers clear.post(PostEvent) + * @triggers clear.exception(ExceptionEvent) */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { + if (!$this->getWritable()) { + return false; + } + $this->normalizeOptions($options); - return $this->clearByRegEx('/.*/', $mode, $options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->clearByRegEx('/.*/', $mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -997,14 +1269,37 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) * @return boolean * @throws Zend\Cache\Exception * @see clear() + * + * @triggers clearByNamespace.pre(PreEvent) + * @triggers clearByNamespace.post(PostEvent) + * @triggers clearByNamespace.exception(ExceptionEvent) */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { + if (!$this->getWritable()) { + return false; + } + $this->normalizeOptions($options); - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); - $regex = '/^' . preg_quote($prefix, '/') . '+/'; + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); - return $this->clearByRegEx($regex, $mode, $options); + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $regex = '/^' . preg_quote($prefix, '/') . '+/'; + $result = $this->clearByRegEx($regex, $mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* status */ @@ -1013,51 +1308,66 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a * Get capabilities * * @return Capabilities + * + * @triggers getCapabilities.pre(PreEvent) + * @triggers getCapabilities.post(PostEvent) + * @triggers getCapabilities.exception(ExceptionEvent) */ public function getCapabilities() { - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array( - 'atime', - 'ctime', - 'internal_key', - 'mem_size', - 'mtime', - 'num_hits', - 'ref_count', - 'rtime', - 'ttl', - ), - 'maxTtl' => 0, - 'staticTtl' => false, - 'ttlPrecision' => 1, - 'useRequestTime' => (bool) ini_get('apc.use_request_time'), - 'expiredRead' => false, - 'maxKeyLength' => 5182, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getNamespaceSeparator(), - 'iterable' => true, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, - ) - ); - } + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array( + 'atime', + 'ctime', + 'internal_key', + 'mem_size', + 'mtime', + 'num_hits', + 'ref_count', + 'rtime', + 'ttl', + ), + 'maxTtl' => 0, + 'staticTtl' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => (bool) ini_get('apc.use_request_time'), + 'expiredRead' => false, + 'maxKeyLength' => 5182, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getNamespaceSeparator(), + 'iterable' => true, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); + } - return $this->capabilities; + return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** @@ -1065,34 +1375,46 @@ public function getCapabilities() * * @param array $options * @return array|boolean Capacity as array or false on failure + * + * @triggers getCapacity.pre(PreEvent) + * @triggers getCapacity.post(PostEvent) + * @triggers getCapacity.exception(ExceptionEvent) */ public function getCapacity(array $options = array()) { - $mem = apc_sma_info(true); + $args = new ArrayObject(array( + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - return array( - 'free' => $mem['avail_mem'], - 'total' => $mem['num_seg'] * $mem['seg_size'], - ); + $mem = apc_sma_info(true); + $result = array( + 'free' => $mem['avail_mem'], + 'total' => $mem['num_seg'] * $mem['seg_size'], + ); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* internal */ /** * Clear cached items based on key regex - * - * @param string $regex - * @param int $mode - * @param array $options + * + * @param string $regex + * @param int $mode + * @param array $options * @return bool */ protected function clearByRegEx($regex, $mode, array &$options) { - if (!$this->getWritable()) { - return false; - } - - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); if (($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE) { // no need to clear expired items return true; @@ -1103,8 +1425,8 @@ protected function clearByRegEx($regex, $mode, array &$options) /** * Normalize metadata to work with APC - * - * @param array $metadata + * + * @param array $metadata * @return void */ protected function normalizeMetadata(array &$metadata) From b061c675fe790d7bbf0b372a15d3dcfc578515da Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 13 Dec 2011 15:09:42 -0600 Subject: [PATCH 139/311] Refactored Pattern subcomponent to use Options class - Created PatternOptions class - Seeded it with options from all available Pattern implementations - Updated Pattern interface - no constructor - setOptions() expects a PatternOptions instance - getOptiosn() lazy-loads a PatternOptions instance - Updated all Pattern implementations to use PatternOptions - Removed setters/getters related to options - Use options instance to get options --- src/Pattern.php | 11 +- src/Pattern/AbstractPattern.php | 40 +- src/Pattern/CallbackCache.php | 110 +-- src/Pattern/CaptureCache.php | 392 +---------- src/Pattern/ClassCache.php | 181 +---- src/Pattern/ObjectCache.php | 284 +------- src/Pattern/OutputCache.php | 70 +- src/Pattern/PatternOptions.php | 880 ++++++++++++++++++++++++ src/PatternFactory.php | 25 +- src/Storage/Adapter/AbstractAdapter.php | 2 +- test/Pattern/CallbackCacheTest.php | 12 +- test/Pattern/CaptureCacheTest.php | 4 +- test/Pattern/ClassCacheTest.php | 12 +- test/Pattern/CommonPatternTest.php | 31 +- test/Pattern/ObjectCacheTest.php | 18 +- test/Pattern/OutputCacheTest.php | 6 +- 16 files changed, 1044 insertions(+), 1034 deletions(-) create mode 100644 src/Pattern/PatternOptions.php diff --git a/src/Pattern.php b/src/Pattern.php index 2e2eef7b3..c52341b10 100644 --- a/src/Pattern.php +++ b/src/Pattern.php @@ -28,20 +28,13 @@ */ interface Pattern { - /** - * Constructor - * - * @param array|Traversable $options - */ - public function __construct($options = array()); - /** * Set pattern options * - * @param array|Traversable $options + * @param Pattern\PatternOptions $options * @return Pattern */ - public function setOptions($options); + public function setOptions(Pattern\PatternOptions $options); /** * Get all pattern options diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index 5eb75d58e..3adf98d83 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -21,8 +21,7 @@ namespace Zend\Cache\Pattern; -use Traversable, - Zend\Cache\Exception, +use Zend\Cache\Exception, Zend\Cache\Pattern; /** @@ -35,49 +34,32 @@ abstract class AbstractPattern implements Pattern { /** - * Constructor - * - * @param array|Traversable $options + * @var PatternOptions */ - public function __construct($options = array()) - { - $this->setOptions($options); - } + protected $options; /** * Set pattern options * - * @param array|Traversable $options + * @param PatternOptions $options * @return AbstractPattern * @throws Exception\InvalidArgumentException */ - public function setOptions($options) + public function setOptions(PatternOptions $options) { - if (!($options instanceof Traversable) && !is_array($options)) { - throw new Exception\InvalidArgumentException( - 'Options must be an array or an instance of Traversable' - ); - } - - foreach ($options as $option => $value) { - $method = 'set' - . str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($option)))); - if (!method_exists($this, $method)) { - continue; - } - $this->{$method}($value); - } - - return $this; + $this->options = $options; } /** * Get all pattern options * - * @return array + * @return PatternOptions */ public function getOptions() { - return array(); + if (null === $this->options) { + $this->setOptions(new PatternOptions()); + } + return $this->options; } } diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index ae13d5044..62eed3458 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -35,102 +35,21 @@ class CallbackCache extends AbstractPattern { /** - * The storage adapter - * - * @var StorageAdapter - */ - protected $storage; - - /** - * Caching output stream - * - * @var boolean - */ - protected $cacheOutput = true; - - /** - * Constructor - * - * @param array|\Traversable $options - * @throws Exception\InvalidArgumentException - */ - public function __construct($options = array()) - { - parent::__construct($options); - - if (!$this->getStorage()) { - throw new Exception\InvalidArgumentException("Missing option 'storage'"); - } - } - - /** - * Get all pattern options - * - * @return array - */ - public function getOptions() - { - $options = parent::getOptions(); - $options['storage'] = $this->getStorage(); - $options['cache_output'] = $this->getCacheOutput(); - return $options; - } - - /** - * Get cache storage - * - * return StorageAdapter - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Set cache storage - * - * @param StorageAdapter|array|string $storage + * Set options + * + * @param PatternOptions $options * @return CallbackCache + * @throws Exception\InvalidArgumentException if missing storage option */ - public function setStorage($storage) + public function setOptions(PatternOptions $options) { - if (is_array($storage)) { - $storage = StorageFactory::factory($storage); - } elseif (is_string($storage)) { - $storage = StorageFactory::adapterFactory($storage); - } elseif ( !($storage instanceof StorageAdapter) ) { - throw new Exception\InvalidArgumentException( - 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' - . 'or an array passed to Zend\Cache\Storage::factory ' - . 'or simply the name of the storage adapter' - ); + parent::setOptions($options); + if (!$options->getStorage()) { + throw new Exception\InvalidArgumentException("Missing option 'storage'"); } - - $this->storage = $storage; return $this; } - /** - * Enable/Disable caching output stream - * - * @param boolean $flag - */ - public function setCacheOutput($flag) - { - $this->cacheOutput = (bool) $flag; - return $this; - } - - /** - * Get caching output stream - * - * return boolean - */ - public function getCacheOutput() - { - return $this->cacheOutput; - } - /** * Call the specified callback or get the result from cache * @@ -142,8 +61,9 @@ public function getCacheOutput() */ public function call($callback, array $args = array(), array $options = array()) { + $classOptions = $this->getOptions(); $key = $this->_generateKey($callback, $args, $options); - if ( ($rs = $this->getStorage()->getItem($key, $options)) !== false ) { + if ( ($rs = $classOptions->getStorage()->getItem($key, $options)) !== false ) { if (!isset($rs[0])) { throw new Exception\RuntimeException("Invalid cached data for key '{$key}'"); } @@ -152,7 +72,7 @@ public function call($callback, array $args = array(), array $options = array()) return $rs[0]; } - if ( ($cacheOutput = $this->getCacheOutput()) ) { + if ( ($cacheOutput = $classOptions->getCacheOutput()) ) { ob_start(); ob_implicit_flush(false); } @@ -178,7 +98,7 @@ public function call($callback, array $args = array(), array $options = array()) $data = array($ret); } - $this->getStorage()->setItem($key, $data, $options); + $classOptions->getStorage()->setItem($key, $data, $options); return $ret; } @@ -230,12 +150,12 @@ public function generateKey($callback, array $args = array(), array $options = a */ protected function _generateKey($callback, array $args, array $options) { - $callbackKey = ''; - $argumentKey = ''; + $callbackKey = ''; + $argumentKey = ''; // generate callback key part if (isset($options['callback_key'])) { - $callbackKey = (string)$options['callback_key']; + $callbackKey = (string) $options['callback_key']; if (!is_callable($callback, false)) { throw new Exception\InvalidArgumentException('Invalid callback'); diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 5d3e95235..d43f9907a 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -33,41 +33,6 @@ */ class CaptureCache extends AbstractPattern { - /** - * Public directory - * - * @var string - */ - protected $publicDir = null; - - /** - * Used umask on creating a cache directory - * - * @var int - */ - protected $dirUmask = 0007; - - /** - * Used umask on creating a cache file - * - * @var int - */ - protected $fileUmask = 0117; - - /** - * Lock files on writing - * - * @var boolean - */ - protected $fileLocking = true; - - /** - * The index filename - * - * @var string - */ - protected $indexFilename = 'index.html'; - /** * Page identifier * @@ -75,322 +40,6 @@ class CaptureCache extends AbstractPattern */ protected $pageId = null; - /** - * Storage for tagging - * - * @var null|StorageAdapter - */ - protected $tagStorage = null; - - /** - * Cache item key to store tags - * - * @var string - */ - protected $tagKey = 'ZendCachePatternCaptureCache_Tags'; - - /** - * Tags - * - * @var array - */ - protected $tags = array(); - - /** - * Constructor - * - * @param array|\Traversable $options - */ - public function __construct($options = array()) - { - parent::__construct($options); - } - - /** - * Get all pattern options - * - * @return array - */ - public function getOptions() - { - return array( - 'public_dir' => $this->getPublicDir(), - 'dir_perm' => $this->getDirPerm(), - 'dir_umask' => $this->getDirUmask(), - 'file_perm' => $this->getFilePerm(), - 'file_umask' => $this->getFileUmask(), - 'file_locking' => $this->getFileLocking(), - 'tag_storage' => $this->getTagStorage(), - 'tag_key' => $this->getTagKey(), - ); - } - - /** - * Set public directory - * - * @param null|string $dir - * @return CaptureCache - */ - public function setPublicDir($dir) - { - $this->publicDir = $dir; - return $this; - } - - /** - * Get public directory - * - * @return null|string - */ - public function getPublicDir() - { - return $this->publicDir; - } - - /** - * Set directory permissions - * - * @param int|string $perm Permissions as octal number - * @return CaptureCache - */ - public function setDirPerm($perm) - { - if (is_string($perm)) { - $perm = octdec($perm); - } else { - $perm = (int) $perm; - } - - // use umask - return $this->setDirUmask(~$perm); - } - - /** - * Get directory permissions - * - * @return int - */ - public function getDirPerm() - { - return ~$this->getDirUmask(); - } - - /** - * Set directory umask - * - * @param int|string $umask Umask as octal number - * @return CaptureCache - */ - public function setDirUmask($umask) - { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int)$umask; - } - - if ((~$umask & 0700) != 0700 ) { - throw new Exception\InvalidArgumentException( - 'Invalid directory umask or directory permissions: ' - . 'need permissions to execute, read and write directories by owner' - ); - } - - $this->dirUmask = $umask; - return $this; - } - - /** - * Get directory umask - * - * @return int - */ - public function getDirUmask() - { - return $this->dirUmask; - } - - /** - * Set file permissions - * - * @param int|string $perm Permissions as octal number - * @return CaptureCache - */ - public function setFilePerm($perm) - { - if (is_string($perm)) { - $perm = octdec($perm); - } else { - $perm = (int) $perm; - } - - // use umask - return $this->setFileUmask(~$perm); - } - - /** - * Get file permissions - * - * @return int - */ - public function getFilePerm() - { - return ~$this->getFileUmask(); - } - - /** - * Set file umask - * - * @param int|string $umask Umask as octal number - * @return CaptureCache - */ - public function setFileUmask($umask) - { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int) $umask; - } - if ((~$umask & 0600) != 0600 ) { - throw new Exception\InvalidArgumentException( - 'Invalid file umask or file permission: ' - . 'need permissions to read and write files by owner' - ); - } elseif ((~$umask & 0111) > 0) { - throw new Exception\InvalidArgumentException( - 'Invalid file umask or file permission: ' - . 'executable cache files are not allowed' - ); - } - - $this->fileUmask = $umask; - return $this; - } - - /** - * Get file umask - * - * @return int - */ - public function getFileUmask() - { - return $this->fileUmask; - } - - /** - * Set file locking - * - * @param bool $flag - * @return CaptureCache - */ - public function setFileLocking($flag) - { - $this->fileLocking = (bool) $flag; - return $this; - } - - /** - * Get file locking - * - * @return bool - */ - public function getFileLocking() - { - return $this->fileLocking; - } - - /** - * Set index filename - * - * @param string $filename - * @return CaptureCache - */ - public function setIndexFilename($filename) - { - $this->indexFilename = (string) $filename; - return $this; - } - - /** - * Get index filename - * - * @return string - */ - public function getIndexFilename() - { - return $this->indexFilename; - } - - /** - * Set a storage for tagging or remove the storage - * - * @param null|StorageAdapter $storage - * @return CaptureCache - */ - public function setTagStorage(StorageAdapter $storage = null) - { - $this->tagStorage = $storage; - return $this; - } - - /** - * Get the storage for tagging - * - * @return null|StorageAdapter - */ - public function getTagStorage() - { - return $this->tagStorage; - } - - /** - * Set cache item key to store tags - * - * @param $tagKey string - * @return CaptureCache - */ - public function setTagKey($tagKey) - { - if (($tagKey = (string)$tagKey) === '') { - throw new Exception\InvalidArgumentException("Missing tag key '{$tagKey}'"); - } - - $this->tagKey = $tagKey; - return $this; - } - - /** - * Get cache item key to store tags - * - * @return string - */ - public function getTagKey() - { - return $this->tagKey; - } - - /** - * Set tags to store - * - * @param array $tags - * @return CaptureCache - */ - public function setTags(array $tags) - { - $this->tags = $tags; - return $this; - } - - /** - * Get tags to store - * - * @return array - */ - public function getTags() - { - return $this->tags; - } - /** * Start the cache * @@ -404,16 +53,18 @@ public function start($pageId = null, array $options = array()) throw new Exception\RuntimeException("Capturing already stated with page id '{$this->pageId}'"); } + $classOptions = $this->getOptions(); + if (isset($options['tags'])) { - $this->setTags($options['tags']); + $classOptions->setTags($options['tags']); unset($options['tags']); } - if ($this->getTags() && !$this->getTagStorage()) { + if ($classOptions->getTags() && !$classOptions->getTagStorage()) { throw new Exception\RuntimeException('Tags are defined but missing a tag storage'); } - if (($pageId = (string)$pageId) === '') { + if (($pageId = (string) $pageId) === '') { $pageId = $this->detectPageId(); } @@ -434,11 +85,11 @@ public function start($pageId = null, array $options = array()) */ public function get($pageId = null, array $options = array()) { - if (($pageId = (string)$pageId) === '') { + if (($pageId = (string) $pageId) === '') { $pageId = $this->detectPageId(); } - $file = $this->getPublicDir() + $file = $this->getOptions()->getPublicDir() . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); @@ -462,11 +113,11 @@ public function get($pageId = null, array $options = array()) */ public function exists($pageId = null, array $options = array()) { - if (($pageId = (string)$pageId) === '') { + if (($pageId = (string) $pageId) === '') { $pageId = $this->detectPageId(); } - $file = $this->getPublicDir() + $file = $this->getOptions()->getPublicDir() . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); @@ -487,7 +138,7 @@ public function remove($pageId = null, array $options = array()) $pageId = $this->detectPageId(); } - $file = $this->getPublicDir() + $file = $this->getOptions()->getPublicDir() . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); @@ -528,7 +179,7 @@ protected function pageId2Filename($pageId) $filename = basename($pageId); if ($filename === '') { - $filename = $this->getIndexFilename(); + $filename = $this->getOptions()->getIndexFilename(); } return $filename; @@ -575,10 +226,11 @@ protected function flush($output) */ protected function save($output) { + $options = $this->getOptions(); $path = $this->pageId2Path($this->pageId); - $fullPath = $this->getPublicDir() . DIRECTORY_SEPARATOR . $path; + $fullPath = $options->getPublicDir() . DIRECTORY_SEPARATOR . $path; if (!file_exists($fullPath)) { - $oldUmask = umask($this->getDirUmask()); + $oldUmask = umask($options->getDirUmask()); if (!@mkdir($fullPath, 0777, true)) { $lastErr = error_get_last(); throw new Exception\RuntimeException( @@ -588,17 +240,17 @@ protected function save($output) } if ($oldUmask !== null) { // $oldUmask could be set on create directory - umask($this->getFileUmask()); + umask($options->getFileUmask()); } else { - $oldUmask = umask($this->getFileUmask()); + $oldUmask = umask($options->getFileUmask()); } - $file = $path . DIRECTORY_SEPARATOR . $this->pageId2Filename($this->pageId); - $fullFile = $this->getPublicDir() . DIRECTORY_SEPARATOR . $file; + $file = $path . DIRECTORY_SEPARATOR . $this->pageId2Filename($this->pageId); + $fullFile = $options->getPublicDir() . DIRECTORY_SEPARATOR . $file; $this->putFileContent($fullFile, $output); - $tagStorage = $this->getTagStorage(); + $tagStorage = $options->getTagStorage(); if ($tagStorage) { - $tagKey = $this->getTagKey(); + $tagKey = $options->getTagKey(); $tagIndex = $tagStorage->getTagStorage()->getItem($tagKey); if (!$tagIndex) { $tagIndex = null; @@ -611,7 +263,7 @@ protected function save($output) } if ($tagIndex !== null) { - $this->getTagStorage()->setItem($tagKey, $tagIndex); + $tagStorage->setItem($tagKey, $tagIndex); } } } @@ -626,7 +278,7 @@ protected function save($output) protected function putFileContent($file, $data) { $flags = FILE_BINARY; // since PHP 6 but defined as 0 in PHP 5.3 - if ($this->getFileLocking()) { + if ($this->getOptions()->getFileLocking()) { $flags = $flags | LOCK_EX; } diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index fc3651f72..93c599d5c 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -33,162 +33,23 @@ class ClassCache extends CallbackCache { /** - * The entity + * Set options * - * @var null|string + * @param PatternOptions $options + * @throws Exception\InvalidArgumentException if missing 'class' or 'storage' options */ - protected $entity = null; - - /** - * Cache by default - * - * @var bool - */ - protected $cacheByDefault = true; - - /** - * Cache methods - * - * @var array - */ - protected $cacheMethods = array(); - - /** - * Non-cache methods - * - * @var array - */ - protected $nonCacheMethods = array(); - - /** - * Constructor - * - * @param array|\Traversable $options - * @throws Exception\InvalidArgumentException - */ - public function __construct($options = array()) + public function setOptions(PatternOptions $options) { - parent::__construct($options); + parent::setOptions($options); - if (!$this->getEntity()) { - throw new Exception\InvalidArgumentException("Missing option 'entity'"); - } elseif (!$this->getStorage()) { + if (!$options->getClass()) { + throw new Exception\InvalidArgumentException("Missing option 'class'"); + } elseif (!$options->getStorage()) { throw new Exception\InvalidArgumentException("Missing option 'storage'"); } - } - - /** - * Get all pattern options - * - * @return array - */ - public function getOptions() - { - $options = parent::getOptions(); - $options['entity'] = $this->getEntity(); - $options['cache_by_default'] = $this->getCacheByDefault(); - $options['cache_methods'] = $this->getCacheMethods(); - $options['non_cache_methods'] = $this->getNonCacheMethods(); - return $options; - } - - /** - * Set the entity to cache - * - * @param string $entity The entity as classname - * @return ClassCache - */ - public function setEntity($entity) - { - if (!is_string($entity)) { - throw new Exception\InvalidArgumentException('Invalid entity, must be a classname'); - } - $this->entity = $entity; - return $this; - } - - /** - * Get the entity to cache - * - * @return null|string The classname or NULL if no entity was set - */ - public function getEntity() - { - return $this->entity; - } - - /** - * Enable or disable caching of methods by default. - * - * @param boolean $flag - * @return ClassCache - */ - public function setCacheByDefault($flag) - { - $this->cacheByDefault = (bool) $flag; - return $this; - } - - /** - * Caching methods by default enabled. - * - * return boolean - */ - public function getCacheByDefault() - { - return $this->cacheByDefault; - } - - /** - * Enable cache methods - * - * @param string[] $methods - * @return ClassCache - */ - public function setCacheMethods(array $methods) - { - $this->cacheMethods = array_values(array_unique(array_map(function($method) { - return strtolower($method); - }, $methods))); - - return $this; - } - - /** - * Get enabled cache methods - * - * @return string[] - */ - public function getCacheMethods() - { - return $this->cacheMethods; - } - - /** - * Disable cache methods - * - * @param string[] $methods - * @return ClassCache - */ - public function setNonCacheMethods(array $methods) - { - $this->nonCacheMethods = array_values(array_unique(array_map(function($method) { - return strtolower($method); - }, $methods))); - return $this; } - /** - * Get disabled cache methods - * - * @return string[] - */ - public function getNonCacheMethods() - { - return $this->nonCacheMethods; - } - /** * Call and cache a class method * @@ -200,15 +61,16 @@ public function getNonCacheMethods() */ public function call($method, array $args = array(), array $options = array()) { - $classname = $this->getEntity(); - $method = strtolower($method); - $callback = $classname . '::' . $method; + $classOptions = $this->getOptions(); + $classname = $classOptions->getClass(); + $method = strtolower($method); + $callback = $classname . '::' . $method; - $cache = $this->getCacheByDefault(); + $cache = $classOptions->getCacheByDefault(); if ($cache) { - $cache = !in_array($method, $this->getNonCacheMethods()); + $cache = !in_array($method, $classOptions->getClassNonCacheMethods()); } else { - $cache = in_array($method, $this->getCacheMethods()); + $cache = in_array($method, $classOptions->getClassCacheMethods()); } if (!$cache) { @@ -238,11 +100,12 @@ public function call($method, array $args = array(), array $options = array()) public function generateKey($method, array $args = array(), array $options = array()) { // speed up key generation + $classOptions = $this->getOptions(); if (!isset($options['callback_key'])) { - $callback = $this->getEntity() . '::' . strtolower($method); + $callback = $classOptions->getClass() . '::' . strtolower($method); $options['callback_key'] = $callback; } else { - $callback = $this->getEntity() . '::' . $method; + $callback = $classOptions->getClass() . '::' . $method; } return parent::generateKey($callback, $args, $options); @@ -271,7 +134,7 @@ public function __call($method, array $args) */ public function __set($name, $value) { - $class = $this->getEntity(); + $class = $this->getOptions()->getClass(); $class::$name = $value; } @@ -284,7 +147,7 @@ public function __set($name, $value) */ public function __get($name) { - $class = $this->getEntity(); + $class = $this->getOptions()->getClass(); return $class::$name; } @@ -296,7 +159,7 @@ public function __get($name) */ public function __isset($name) { - $class = $this->getEntity(); + $class = $this->getOptions()->getClass(); return isset($class::$name); } @@ -308,7 +171,7 @@ public function __isset($name) */ public function __unset($name) { - $class = $this->getEntity(); + $class = $this->getOptions()->getClass(); unset($class::$name); } } diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index f4b24b260..dbcea9547 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -33,258 +33,22 @@ class ObjectCache extends CallbackCache { /** - * The entity + * Set options * - * @var null|object - */ - protected $entity = null; - - /** - * The entity key - * - * @var null|string - */ - protected $entityKey = null; - - /** - * Cache by default - * - * @var bool - */ - protected $cacheByDefault = true; - - /** - * Cache methods - * - * @var array - */ - protected $cacheMethods = array(); - - /** - * Non-cache methods - * - * @var array - */ - protected $nonCacheMethods = array('__tostring'); - - /** - * Cache magic properties - * - * @var bool - */ - protected $cacheMagicProperties = false; - - /** - * Constructor - * - * @param array|\Traversable $options + * @param PatternOptions $options * @throws Exception\InvalidArgumentException */ - public function __construct($options = array()) + public function setOptions(PatternOptions $options) { - parent::__construct($options); + parent::setOptions($options); - if (!$this->getEntity()) { - throw new Exception\InvalidArgumentException("Missing option 'entity'"); - } elseif (!$this->getStorage()) { + if (!$options->getObject()) { + throw new Exception\InvalidArgumentException("Missing option 'object'"); + } elseif (!$options->getStorage()) { throw new Exception\InvalidArgumentException("Missing option 'storage'"); } } - /** - * Get all pattern options - * - * @return array - */ - public function getOptions() - { - $options = parent::getOptions(); - $options['entity'] = $this->getEntity(); - $options['entity_key'] = $this->getEntityKey(); - $options['cache_by_default'] = $this->getCacheByDefault(); - $options['cache_methods'] = $this->getCacheMethods(); - $options['non_cache_methods'] = $this->getNonCacheMethods(); - $options['cache_magic_properties'] = $this->getCacheMagicProperties(); - return $options; - } - - /** - * Set the entity to cache - * - * @param object $entity - * @return ObjectCache - */ - public function setEntity($entity) - { - if (!is_object($entity)) { - throw new Exception\InvalidArgumentException('Invalid entity, must be an object'); - } - $this->entity = $entity; - return $this; - } - - /** - * Get the entity to cache - * - * @return object - */ - public function getEntity() - { - return $this->entity; - } - - /** - * Set the entity key part. - * - * This will be used to generate the callback key - * to speed up key generation. - * - * NOTE: This option has no effect if callback_key was given. - * - * @param null|string $key The key part as string or NULL to auto-generate - * @return ObjectCache - * @see generateKey() - */ - public function setEntityKey($key) - { - if ($key !== null) { - $this->entityKey = (string) $key; - } else { - $this->entityKey = null; - } - - return $this; - } - - /** - * Get the entity key part. - * - * @return null|string - * @see setEntityKey() - */ - public function getEntityKey() - { - return $this->entityKey; - } - - /** - * Enable or disable caching of methods by default. - * - * @param boolean $flag - * @return ObjectCache - */ - public function setCacheByDefault($flag) - { - $this->cacheByDefault = (bool) $flag; - return $this; - } - - /** - * Caching methods by default enabled. - * - * return boolean - */ - public function getCacheByDefault() - { - return $this->cacheByDefault; - } - - /** - * Enable cache methods - * - * @param string[] $methods - * @return ObjectCache - */ - public function setCacheMethods(array $methods) - { - $this->cacheMethods = array_values(array_unique(array_map(function($method) { - $method = strtolower($method); - - switch ($method) { - case '__set': - case '__get': - case '__unset': - case '__isset': - throw new Exception\InvalidArgumentException( - "Magic properties are handled by option 'cache_magic_properties'" - ); - } - - return $method; - }, $methods))); - - return $this; - } - - /** - * Get enabled cache methods - * - * @return string[] - */ - public function getCacheMethods() - { - return $this->cacheMethods; - } - - /** - * Disable cache methods - * - * @param string[] $methods - * @return ObjectCache - */ - public function setNonCacheMethods(array $methods) - { - $this->nonCacheMethods = array_values(array_unique(array_map(function($method) { - $method = strtolower($method); - - switch ($method) { - case '__set': - case '__get': - case '__unset': - case '__isset': - throw new Exception\InvalidArgumentException( - "Magic properties are handled by option 'cache_magic_properties'" - ); - } - - return $method; - }, $methods))); - - return $this; - } - - /** - * Get disabled cache methods - * - * @return string[] - */ - public function getNonCacheMethods() - { - return $this->nonCacheMethods; - } - - /** - * Enable or disable caching of magic property calls - * - * @param boolean $flag - * @return ObjectCache - */ - public function setCacheMagicProperties($flag) - { - $this->cacheMagicProperties = (bool) $flag; - return $this; - } - - /** - * If caching of magic properties enabled - * - * @return boolean - */ - public function getCacheMagicProperties() - { - return $this->cacheMagicProperties; - } - /** * Call and cache a class method * @@ -296,8 +60,9 @@ public function getCacheMagicProperties() */ public function call($method, array $args = array(), array $options = array()) { - $object = $this->getEntity(); - $method = strtolower($method); + $classOptions = $this->getOptions(); + $object = $classOptions->getObject(); + $method = strtolower($method); // handle magic methods switch ($method) { @@ -307,7 +72,7 @@ public function call($method, array $args = array(), array $options = array()) $object->{$property} = $value; - if (!$this->getCacheMagicProperties() + if (!$classOptions->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -324,14 +89,14 @@ public function call($method, array $args = array(), array $options = array()) $removeKeys[] = $this->generateKey('__isset', array($property), $options); } if ($removeKeys) { - $this->getStorage()->removeMulti($removeKeys); + $classOptions->getStorage()->removeMulti($removeKeys); } return; case '__get': $property = array_shift($args); - if (!$this->getCacheMagicProperties() + if (!$classOptions->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -344,7 +109,7 @@ public function call($method, array $args = array(), array $options = array()) if (!isset($options['callback_key'])) { if ((isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null) + || ($entityKey = $classOptions->getObjectKey() !== null) ) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); @@ -356,7 +121,7 @@ public function call($method, array $args = array(), array $options = array()) case '__isset': $property = array_shift($args); - if (!$this->getCacheMagicProperties() + if (!$classOptions->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -367,7 +132,7 @@ public function call($method, array $args = array(), array $options = array()) if (!isset($options['callback_key'])) { if ((isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null) + || ($entityKey = $classOptions->getObjectKey() !== null) ) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); @@ -381,7 +146,7 @@ public function call($method, array $args = array(), array $options = array()) unset($object->{$property}); - if (!$this->getCacheMagicProperties() + if (!$classOptions->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -398,16 +163,16 @@ public function call($method, array $args = array(), array $options = array()) $removeKeys[] = $this->generateKey('__isset', array($property), $options); } if ($removeKeys) { - $this->getStorage()->removeMulti($removeKeys); + $classOptions->getStorage()->removeMulti($removeKeys); } return; } - $cache = $this->getCacheByDefault(); + $cache = $classOptions->getCacheByDefault(); if ($cache) { - $cache = !in_array($method, $this->getNonCacheMethods()); + $cache = !in_array($method, $classOptions->getObjectNonCacheMethods()); } else { - $cache = in_array($method, $this->getCacheMethods()); + $cache = in_array($method, $classOptions->getObjectCacheMethods()); } if (!$cache) { @@ -419,7 +184,7 @@ public function call($method, array $args = array(), array $options = array()) if (!isset($options['callback_key'])) { if ((isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null) + || ($entityKey = $classOptions->getObjectKey() !== null) ) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); @@ -440,15 +205,16 @@ public function call($method, array $args = array(), array $options = array()) */ public function generateKey($method, array $args = array(), array $options = array()) { + $classOptions = $this->getOptions(); if (!isset($options['callback_key'])) { if ( (isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $this->getEntityKey() !== null)) { + || ($entityKey = $classOptions->getObjectKey() !== null)) { $options['callback_key'] = $entityKey . '::' . strtolower($method); unset($options['entity_key']); } } - return parent::generateKey(array($this->getEntity(), $method), $args, $options); + return parent::generateKey(array($classOptions->getObject(), $method), $args, $options); } /** diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index 965379b77..952a60c16 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -34,13 +34,6 @@ */ class OutputCache extends AbstractPattern { - /** - * The storage adapter - * - * @var StorageAdapter - */ - protected $storage; - /** * The key stack * @@ -49,63 +42,18 @@ class OutputCache extends AbstractPattern protected $keyStack = array(); /** - * Constructor + * Set options * - * @param array|\Traversable $options + * @param PatternOptions $options * @throws Exception\InvalidArgumentException */ - public function __construct($options = array()) + public function setOptions(PatternOptions $options) { - parent::__construct($options); + parent::setOptions($options); - if (!$this->getStorage()) { + if (!$options->getStorage()) { throw new Exception\InvalidArgumentException("Missing option 'storage'"); } - } - - /** - * Get all pattern options - * - * @return array - */ - public function getOptions() - { - $options = parent::getOptions(); - $options['storage'] = $this->getStorage(); - return $options; - } - - /** - * Get cache storage - * - * return StorageAdapter - */ - public function getStorage() - { - return $this->storage; - } - - /** - * Set cache storage - * - * @param StorageAdapter|array|string $storage - * @return OutputCache - */ - public function setStorage($storage) - { - if (is_array($storage)) { - $storage = StorageFactory::factory($storage); - } elseif (is_string($storage)) { - $storage = StorageFactory::adapterFactory($storage); - } elseif (!($storage instanceof StorageAdapter)) { - throw new Exception\InvalidArgumentException( - 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' - . 'or an array passed to Zend\Cache\Storage::factory ' - . 'or simply the name of the storage adapter' - ); - } - - $this->storage = $storage; return $this; } @@ -128,13 +76,15 @@ public function start($key, array $options = array()) throw new Exception\MissingKeyException('Missing key to read/write output from storage'); } + $classOptions = $this->getOptions(); + $optOutput = true; if (isset($options['output'])) { $optOutput = (bool) $options['output']; unset($options['output']); // don't forword this option to storage } - $data = $this->getStorage()->getItem($key, $options); + $data = $classOptions->getStorage()->getItem($key, $options); if ($data !== false) { if ($optOutput) { echo $data; @@ -170,7 +120,7 @@ public function end(array $options = array()) $optOutput = true; if (isset($options['output'])) { - $optOutput = (bool)$options['output']; + $optOutput = (bool) $options['output']; unset($options['output']); // don't forword this option to storage } @@ -184,6 +134,6 @@ public function end(array $options = array()) throw new Exception\RuntimeException('Output buffering not active'); } - return $this->getStorage()->setItem($key, $data, $options); + return $this->getOptions()->getStorage()->setItem($key, $data, $options); } } diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php new file mode 100644 index 000000000..0804a891f --- /dev/null +++ b/src/Pattern/PatternOptions.php @@ -0,0 +1,880 @@ +cacheByDefault = $cacheByDefault; + return $this; + } + + /** + * Do we cache by default? + * + * Used by: + * - ClassCache + * - ObjectCache + * + * @return bool + */ + public function getCacheByDefault() + { + return $this->cacheByDefault; + } + + /** + * Set whether or not to cache output + * + * Used by: + * - CallbackCache + * - ClassCache + * - ObjectCache + * + * @param bool $cacheOutput + * @return PatternOptions + */ + public function setCacheOutput($cacheOutput) + { + $this->cacheOutput = (bool) $cacheOutput; + return $this; + } + + /** + * Will we cache output? + * + * Used by: + * - CallbackCache + * - ClassCache + * - ObjectCache + * + * @return bool + */ + public function getCacheOutput() + { + return $this->cacheOutput; + } + + /** + * Set class name + * + * Used by: + * - ClassCache + * + * @param string $class + * @return PatternOptions + */ + public function setClass($class) + { + if (!is_string($class)) { + throw new Exception\InvalidArgumentException('Invalid classname provided; must be a string'); + } + $this->class = $class; + return $this; + } + + /** + * Get class name + * + * Used by: + * - ClassCache + * + * @return null|string + */ + public function getClass() + { + return $this->class; + } + + /** + * Set list of method return values to cache + * + * Used by: + * - ClassCache + * + * @param array $classCacheMethods + * @return PatternOptions + */ + public function setClassCacheMethods(array $classCacheMethods) + { + $this->classCacheMethods = $this->recursiveStrtolower($classCacheMethods); + return $this; + } + + /** + * Get list of methods from which to cache return values + * + * Used by: + * - ClassCache + * + * @return array + */ + public function getClassCacheMethods() + { + return $this->classCacheMethods; + } + + /** + * Set list of method return values NOT to cache + * + * Used by: + * - ClassCache + * + * @param array $classNonCacheMethods + * @return PatternOptions + */ + public function setClassNonCacheMethods(array $classNonCacheMethods) + { + $this->classNonCacheMethods = $this->recursiveStrtolower($classNonCacheMethods); + return $this; + } + + /** + * Get list of methods from which NOT to cache return values + * + * Used by: + * - ClassCache + * + * @return array + */ + public function getClassNonCacheMethods() + { + return $this->classNonCacheMethods; + } + + /** + * Set directory permissions + * + * Sets {@link $dirUmask} property to inverse of provided value. + * + * @param string $dirPerm + * @return PatternOptions + */ + public function setDirPerm($dirPerm) + { + if (is_string($dirPerm)) { + $dirPerm = octdec($dirPerm); + } else { + $dirPerm = (int) $dirPerm; + } + + // use umask + return $this->setDirUmask(~$dirPerm); + } + + /** + * Gets directory permissions + * + * Proxies to {@link $dirUmask} property, returning its inverse. + * + * @return int + */ + public function getDirPerm() + { + return ~$this->getDirUmask(); + } + + /** + * Set directory umask + * + * Used by: + * - CaptureCache + * + * @param int $dirUmask + * @return PatternOptions + */ + public function setDirUmask($dirUmask) + { + $dirUmask = $this->normalizeUmask($dirUmask, function($umask) { + if ((~$umask & 0700) != 0700 ) { + throw new Exception\InvalidArgumentException( + 'Invalid directory umask or directory permissions: ' + . 'need permissions to execute, read and write directories by owner' + ); + } + }); + $this->dirUmask = $dirUmask; + return $this; + } + + /** + * Get directory umask + * + * Used by: + * - CaptureCache + * + * @return int + */ + public function getDirUmask() + { + return $this->dirUmask; + } + + /** + * Set whether or not file locking should be used + * + * Used by: + * - CaptureCache + * + * @param bool $fileLocking + * @return PatternOptions + */ + public function setFileLocking($fileLocking) + { + $this->fileLocking = (bool) $fileLocking; + return $this; + } + + /** + * Is file locking enabled? + * + * Used by: + * - CaptureCache + * + * @return bool + */ + public function getFileLocking() + { + return $this->fileLocking; + } + + /** + * Set file permissions + * + * Sets {@link $fileUmask} property to inverse of provided value. + * + * @param string $filePerm + * @return PatternOptions + */ + public function setFilePerm($filePerm) + { + if (is_string($filePerm)) { + $filePerm = octdec($filePerm); + } else { + $filePerm = (int) $filePerm; + } + + // use umask + return $this->setFileUmask(~$filePerm); + } + + /** + * Gets file permissions + * + * Proxies to {@link $fileUmask} property, returning its inverse. + * + * @return int + */ + public function getFilePerm() + { + return ~$this->getFileUmask(); + } + + /** + * Set file umask + * + * Used by: + * - CaptureCache + * + * @param int $fileUmask + * @return PatternOptions + */ + public function setFileUmask($fileUmask) + { + $fileUmask = $this->normalizeUmask($fileUmask, function($umask) { + if ((~$umask & 0600) != 0600 ) { + throw new Exception\InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'need permissions to read and write files by owner' + ); + } elseif ((~$umask & 0111) > 0) { + throw new Exception\InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'executable cache files are not allowed' + ); + } + }); + $this->fileUmask = $fileUmask; + return $this; + } + + /** + * Get file umask + * + * Used by: + * - CaptureCache + * + * @return int + */ + public function getFileUmask() + { + return $this->fileUmask; + } + + /** + * Set value for index filename + * + * @param string $indexFilename + * @return PatternOptions + */ + public function setIndexFilename($indexFilename) + { + $this->indexFilename = (string) $indexFilename; + return $this; + } + + /** + * Get value for index filename + * + * @return string + */ + public function getIndexFilename() + { + return $this->indexFilename; + } + + /** + * Set object to cache + * + * @param mixed $value + * @return $this + */ + public function setObject($object) + { + if (!is_object($object)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an object; received "%s"', __METHOD__, gettype($object) + )); + } + $this->object = $object; + return $this; + } + + /** + * Get object to cache + * + * @return null|object + */ + public function getObject() + { + return $this->object; + } + + /** + * Set flag indicating whether or not to cache magic properties + * + * Used by: + * - ObjectCache + * + * @param bool $objectCacheMagicProperties + * @return PatternOptions + */ + public function setObjectCacheMagicProperties($objectCacheMagicProperties) + { + $this->objectCacheMagicProperties = (bool) $objectCacheMagicProperties; + return $this; + } + + /** + * Should we cache magic properties? + * + * Used by: + * - ObjectCache + * + * @return bool + */ + public function getObjectCacheMagicProperties() + { + return $this->objectCacheMagicProperties; + } + + /** + * Set list of object methods for which to cache return values + * + * @param array $objectCacheMethods + * @return PatternOptions + * @throws Exception\InvalidArgumentException + */ + public function setObjectCacheMethods(array $objectCacheMethods) + { + $this->objectCacheMethods = $this->normalizeObjectMethods($objectCacheMethods); + return $this; + } + + /** + * Get list of object methods for which to cache return values + * + * @return array + */ + public function getObjectCacheMethods() + { + return $this->objectCacheMethods; + } + + /** + * Set the object key part. + * + * Used to generate a callback key in order to speed up key generation. + * + * Used by: + * - ObjectCache + * + * @param mixed $value + * @return $this + */ + public function setObjectKey($objectKey) + { + if ($objectKey !== null) { + $this->objectKey = (string) $objectKey; + } else { + $this->objectKey = null; + } + return $this; + } + + /** + * Get object key + * + * Used by: + * - ObjectCache + * + * @return mixed + */ + public function getObjectKey() + { + return $this->objectKey; + } + + /** + * Set list of object methods for which NOT to cache return values + * + * @param array $objectNonCacheMethods + * @return PatternOptions + * @throws Exception\InvalidArgumentException + */ + public function setObjectNonCacheMethods(array $objectNonCacheMethods) + { + $this->objectNonCacheMethods = $this->normalizeObjectMethods($objectNonCacheMethods); + return $this; + } + + /** + * Get list of object methods for which NOT to cache return values + * + * @return array + */ + public function getObjectNonCacheMethods() + { + return $this->objectNonCacheMethods; + } + + /** + * Set location of public directory + * + * Used by: + * - CaptureCache + * + * @param string $publicDir + * @return PatternOptions + */ + public function setPublicDir($publicDir) + { + $this->publicDir = (string) $publicDir; + return $this; + } + + /** + * Get location of public directory + * + * Used by: + * - CaptureCache + * + * @return null|string + */ + public function getPublicDir() + { + return $this->publicDir; + } + + /** + * Set storage adapter + * + * Required for the following Pattern classes: + * - CallbackCache + * - ClassCache + * - ObjectCache + * - OutputCache + * + * @param string|array|StorageAdapter $storage + * @return PatternOptions + */ + public function setStorage($storage) + { + $storage = $this->storageFactory($storage); + $this->storage = $storage; + return $this; + } + + /** + * Get storage adapter + * + * Used by: + * - CallbackCache + * - ClassCache + * - ObjectCache + * - OutputCache + * + * @return null|StorageAdapter + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Set tag key + * + * @param string $tagKey + * @return PatternOptions + */ + public function setTagKey($tagKey) + { + if (($tagKey = (string)$tagKey) === '') { + throw new Exception\InvalidArgumentException("Missing tag key '{$tagKey}'"); + } + + $this->tagKey = $tagKey; + return $this; + } + + /** + * Get tag key + * + * @return string + */ + public function getTagKey() + { + return $this->tagKey; + } + + /** + * Set tags + * + * Used by: + * - CaptureCache + * + * @param array $tags + * @return PatternOptions + */ + public function setTags(array $tags) + { + $this->tags = $tags; + return $this; + } + + /** + * Get tags + * + * Used by: + * - CaptureCache + * + * @return array + */ + public function getTags() + { + return $this->tags; + } + + /** + * Set storage adapter for tags + * + * Used by: + * - CaptureCache + * + * @param string|array|StorageAdapter $tagStorage + * @return PatternOptions + */ + public function setTagStorage($tagStorage) + { + $tagStorage = $this->storageFactory($tagStorage); + $this->tagStorage = $tagStorage; + return $this; + } + + /** + * Get storage adapter for tags + * + * Used by: + * - CaptureCache + * + * @return null|StorageAdapter + */ + public function getTagStorage() + { + return $this->tagStorage; + } + + /** + * Recursively apply strtolower on all values of an array, and return as a + * list of unique values + * + * @param array $array + * @return array + */ + protected function recursiveStrtolower(array $array) + { + return array_values(array_unique(array_map(function($value) { + return strtolower($value); + }, $array))); + } + + /** + * Normalize object methods + * + * Recursively casts values to lowercase, then determines if any are in a + * list of methods not handled, raising an exception if so. + * + * @param array $methods + * @return array + * @throws Exception\InvalidArgumentException + */ + protected function normalizeObjectMethods(array $methods) + { + $methods = $this->recursiveStrtolower($methods); + $intersect = array_intersect(array('__set', '__get', '__unset', '__isset'), $methods); + if (!empty($intersect)) { + throw new Exception\InvalidArgumentException( + "Magic properties are handled by option 'cache_magic_properties'" + ); + } + return $methods; + } + + /** + * Normalize a umask + * + * Allows specifying a umask as either an octal or integer. If the umask + * fails required permissions, raises an exception. + * + * @param int|string $mask + * @param callable Callback used to verify the umask is acceptable for the given purpose + * @return int + * @throws Exception\InvalidArgumentException + */ + protected function normalizeUmask($mask, $comparison) + { + if (is_string($umask)) { + $umask = octdec($umask); + } else { + $umask = (int)$umask; + } + + $comparison($umask); + + return $umask; + } + + /** + * Create a storage object from a given specification + * + * @param array|string|StorageAdapter $storage + * @return StorageAdapter + */ + protected function storageFactory($storage) + { + if (is_array($storage)) { + $storage = StorageFactory::factory($storage); + } elseif (is_string($storage)) { + $storage = StorageFactory::adapterFactory($storage); + } elseif ( !($storage instanceof StorageAdapter) ) { + throw new Exception\InvalidArgumentException( + 'The storage must be an instanceof Zend\Cache\Storage\Adapter ' + . 'or an array passed to Zend\Cache\Storage::factory ' + . 'or simply the name of the storage adapter' + ); + } + + return $storage; + } +} diff --git a/src/PatternFactory.php b/src/PatternFactory.php index 5efb95f93..adf01f084 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -20,7 +20,9 @@ namespace Zend\Cache; -use Zend\Loader\Broker; +use Traversable, + Zend\Loader\Broker, + Zend\Stdlib\IteratorToArray; /** * @category Zend @@ -41,18 +43,35 @@ class PatternFactory * Instantiate a cache pattern * * @param string|Pattern $patternName - * @param array|Traversable $options + * @param array|Traversable|Pattern\PatternOptions $options * @return Pattern * @throws Exception\RuntimeException */ public static function factory($patternName, $options = array()) { + if ($options instanceof Traversable) { + $options = IteratorToArray::convert($options); + } + if (is_array($options)) { + $options = new Pattern\PatternOptions($options); + } + if (!$options instanceof Pattern\PatternOptions) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array, Traversable object, or %s\Pattern\PatternOptions object; received "%s"', + __METHOD__, + __NAMESPACE__, + (is_object($options) ? get_class($options) : gettype($options)) + )); + } + if ($patternName instanceof Pattern) { $patternName->setOptions($options); return $patternName; } - return static::getBroker()->load($patternName, $options); + $pattern = static::getBroker()->load($patternName); + $pattern->setOptions($options); + return $pattern; } /** diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 2e5230e51..2ff99247c 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -483,7 +483,7 @@ public function events() if ($this->events === null) { $this->setEventManager(new EventManager(array( __CLASS__, - get_class($this), + get_called_class(), ))); } return $this->events; diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index 42a5af947..9788f2c54 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -74,9 +74,11 @@ class CallbackCacheTest extends CommonPatternTest public function setUp() { $this->_storage = new Cache\Storage\Adapter\Memory(); - $this->_pattern = new Cache\Pattern\CallbackCache(array( - 'storage' => $this->_storage + $this->_options = new Cache\Pattern\PatternOptions(array( + 'storage' => $this->_storage, )); + $this->_pattern = new Cache\Pattern\CallbackCache(); + $this->_pattern->setOptions($this->_options); parent::setUp(); } @@ -96,7 +98,8 @@ public function testCallEnabledCacheOutputByDefault() public function testCallDisabledCacheOutput() { - $this->_pattern->setCacheOutput(false); + $options = $this->_pattern->getOptions(); + $options->setCacheOutput(false); $this->_testCall( __NAMESPACE__ . '\TestCallbackCache::bar', array('testCallDisabledCacheOutput', 'arg2') @@ -201,7 +204,8 @@ protected function _testCall($callback, array $args) $data = ob_get_clean(); $this->assertEquals($returnSpec . $firstCounter, $return); - if ($this->_pattern->getCacheOutput()) { + $options = $this->_pattern->getOptions(); + if ($options->getCacheOutput()) { $this->assertEquals($outputSpec . $firstCounter, $data); } else { $this->assertEquals('', $data); diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php index 9c583c822..f48a9b785 100644 --- a/test/Pattern/CaptureCacheTest.php +++ b/test/Pattern/CaptureCacheTest.php @@ -36,9 +36,11 @@ class CaptureCacheTest extends CommonPatternTest public function setUp() { - $this->_pattern = new Cache\Pattern\CaptureCache(array( + $this->_options = new Cache\Pattern\PatternOptions(array( // TODO )); + $this->_pattern = new Cache\Pattern\CaptureCache(); + $this->_pattern->setOptions($this->_options); parent::setUp(); } diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 16f1d4e3b..109ebcf24 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -65,10 +65,12 @@ class ClassCacheTest extends CommonPatternTest public function setUp() { $this->_storage = new Cache\Storage\Adapter\Memory(); - $this->_pattern = new Cache\Pattern\ClassCache(array( - 'entity' => __NAMESPACE__ . '\TestClassCache', - 'storage' => $this->_storage + $this->_options = new Cache\Pattern\PatternOptions(array( + 'class' => __NAMESPACE__ . '\TestClassCache', + 'storage' => $this->_storage, )); + $this->_pattern = new Cache\Pattern\ClassCache(); + $this->_pattern->setOptions($this->_options); parent::setUp(); } @@ -88,7 +90,7 @@ public function testCallEnabledCacheOutputByDefault() public function testCallDisabledCacheOutput() { - $this->_pattern->setCacheOutput(false); + $this->_options->setCacheOutput(false); $this->_testCall( 'bar', array('testCallDisabledCacheOutput', 'arg2') @@ -136,7 +138,7 @@ protected function _testCall($method, array $args) $data = ob_get_clean(); $this->assertEquals($returnSpec . $firstCounter, $return); - if ($this->_pattern->getCacheOutput()) { + if ($this->_options->getCacheOutput()) { $this->assertEquals($outputSpec . $firstCounter, $data); } else { $this->assertEquals('', $data); diff --git a/test/Pattern/CommonPatternTest.php b/test/Pattern/CommonPatternTest.php index 4aa1c115a..6cf0d84db 100644 --- a/test/Pattern/CommonPatternTest.php +++ b/test/Pattern/CommonPatternTest.php @@ -57,40 +57,13 @@ public function tearDown() public function testOptionNamesValid() { $options = $this->_pattern->getOptions(); - foreach ($options as $name => $value) { - $this->assertRegExp( - '/^[a-z]*[a-z0-9_]*[a-z0-9]*$/', - $name, - "Invalid option name '{$name}'" - ); - } + $this->assertInstanceOf('Zend\Cache\Pattern\PatternOptions', $options); } public function testOptionsGetAndSetDefault() { $options = $this->_pattern->getOptions(); $this->_pattern->setOptions($options); - $this->assertEquals($options, $this->_pattern->getOptions()); + $this->assertSame($options, $this->_pattern->getOptions()); } - - public function testOptionsFluentInterface() - { - $options = $this->_pattern->getOptions(); - foreach ($options as $option => $value) { - $method = ucwords(str_replace('_', ' ', $option)); - $method = 'set' . str_replace(' ', '', $method); - $this->assertSame( - $this->_pattern, - $this->_pattern->{$method}($value), - "Method '{$method}' doesn't implement the fluent interface" - ); - } - - $this->assertSame( - $this->_pattern, - $this->_pattern->setOptions(array()), - "Method 'setOptions' doesn't implement the fluent interface" - ); - } - } diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index 7f4894a13..262723a2d 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -73,10 +73,12 @@ public function setUp() { $class = __NAMESPACE__ . '\TestObjectCache'; $this->_storage = new Cache\Storage\Adapter\Memory(); - $this->_pattern = new Cache\Pattern\ObjectCache(array( - 'entity' => new $class(), - 'storage' => $this->_storage + $this->_options = new Cache\Pattern\PatternOptions(array( + 'object' => new $class(), + 'storage' => $this->_storage, )); + $this->_pattern = new Cache\Pattern\ObjectCache(); + $this->_pattern->setOptions($this->_options); parent::setUp(); } @@ -96,7 +98,7 @@ public function testCallEnabledCacheOutputByDefault() public function testCallDisabledCacheOutput() { - $this->_pattern->setCacheOutput(false); + $this->_options->setCacheOutput(false); $this->_testCall( 'bar', array('testCallDisabledCacheOutput', 'arg2') @@ -105,7 +107,7 @@ public function testCallDisabledCacheOutput() public function testCallInvoke() { - $this->_pattern->setCacheOutput(false); + $this->_options->setCacheOutput(false); $this->_testCall('__invoke', array('arg1', 'arg2')); } @@ -163,12 +165,12 @@ public function testCallUnknownMethodException() public function testSetProperty() { $this->_pattern->property = 'testSetProperty'; - $this->assertEquals('testSetProperty', $this->_pattern->getEntity()->property); + $this->assertEquals('testSetProperty', $this->_options->getObject()->property); } public function testGetProperty() { - $this->assertEquals($this->_pattern->getEntity()->property, $this->_pattern->property); + $this->assertEquals($this->_options->getObject()->property, $this->_pattern->property); } public function testIssetProperty() @@ -209,7 +211,7 @@ protected function _testCall($method, array $args) ob_end_clean(); $this->assertEquals($returnSpec . $firstCounter, $return); - if ($this->_pattern->getCacheOutput()) { + if ($this->_options->getCacheOutput()) { $this->assertEquals($outputSpec . $firstCounter, $data); } else { $this->assertEquals('', $data); diff --git a/test/Pattern/OutputCacheTest.php b/test/Pattern/OutputCacheTest.php index d9173b2bd..2f931347a 100644 --- a/test/Pattern/OutputCacheTest.php +++ b/test/Pattern/OutputCacheTest.php @@ -43,9 +43,11 @@ class OutputCacheTest extends CommonPatternTest public function setUp() { $this->_storage = new Cache\Storage\Adapter\Memory(); - $this->_pattern = new Cache\Pattern\OutputCache(array( - 'storage' => $this->_storage + $this->_options = new Cache\Pattern\PatternOptions(array( + 'storage' => $this->_storage, )); + $this->_pattern = new Cache\Pattern\OutputCache(); + $this->_pattern->setOptions($this->_options); parent::setUp(); } From 24ab1c605840554a43a067f2cfa0d0af523d4180 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 13 Dec 2011 16:15:59 -0600 Subject: [PATCH 140/311] Refactored storage plugins to use options class - Created PluginOptions class - Moved all plugin options and discovery into this object - Created AbstractPlugin implementation - sets and gets Options class - Refactored various plugin implementations - extend AbstractPlugin - move options into PluginOptions - access options via PluginOptions --- src/Storage/Plugin.php | 13 +- src/Storage/Plugin/AbstractPlugin.php | 63 ++++ src/Storage/Plugin/ClearByFactor.php | 124 +------ src/Storage/Plugin/ExceptionHandler.php | 118 +------ src/Storage/Plugin/OptimizeByFactor.php | 91 +----- src/Storage/Plugin/PluginOptions.php | 320 +++++++++++++++++++ src/Storage/Plugin/Serializer.php | 155 +++------ test/Storage/Plugin/ClearByFactorTest.php | 12 +- test/Storage/Plugin/CommonPluginTest.php | 52 +-- test/Storage/Plugin/ExceptionHandlerTest.php | 6 +- test/Storage/Plugin/OptimizeByFactorTest.php | 6 +- test/Storage/Plugin/SerializerTest.php | 2 + 12 files changed, 454 insertions(+), 508 deletions(-) create mode 100644 src/Storage/Plugin/AbstractPlugin.php create mode 100644 src/Storage/Plugin/PluginOptions.php diff --git a/src/Storage/Plugin.php b/src/Storage/Plugin.php index 68b2f3361..3c79127ee 100644 --- a/src/Storage/Plugin.php +++ b/src/Storage/Plugin.php @@ -43,25 +43,18 @@ */ interface Plugin extends ListenerAggregate { - /** - * Constructor - * - * @param array|Traversable $options - */ - public function __construct($options = array()); - /** * Set options * - * @param array|Traversable $options + * @param Plugin\PluginOptions $options * @return Plugin */ - public function setOptions($options); + public function setOptions(Plugin\PluginOptions $options); /** * Get options * - * @return array + * @return PluginOptions */ public function getOptions(); } diff --git a/src/Storage/Plugin/AbstractPlugin.php b/src/Storage/Plugin/AbstractPlugin.php new file mode 100644 index 000000000..73e1b71ce --- /dev/null +++ b/src/Storage/Plugin/AbstractPlugin.php @@ -0,0 +1,63 @@ +options = $options; + } + + /** + * Get all pattern options + * + * @return PluginOptions + */ + public function getOptions() + { + if (null === $this->options) { + $this->setOptions(new PluginOptions()); + } + return $this->options; + } +} diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 5de1adec9..1471af3c0 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -25,7 +25,6 @@ Zend\EventManager\EventCollection, Zend\Cache\Exception, Zend\Cache\Storage\Adapter, - Zend\Cache\Storage\Plugin, Zend\Cache\Storage\PostEvent; /** @@ -35,22 +34,8 @@ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class ClearByFactor implements Plugin +class ClearByFactor extends AbstractPlugin { - /** - * Automatic clearing factor - * - * @var int - */ - protected $clearingFactor = 0; - - /** - * Flag to clear items by namespace - * - * @var boolean - */ - protected $clearByNamespace = true; - /** * Handles * @@ -58,108 +43,6 @@ class ClearByFactor implements Plugin */ protected $handles = array(); - /** - * Constructor - * - * @param array|Traversable $options - * @return void - */ - public function __construct($options = array()) - { - $this->setOptions($options); - } - - /** - * Set options - * - * @param array|Traversable $options - * @return ClearByFactor - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable object; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $name => $value) { - $m = 'set' . str_replace('_', '', $name); - if (!method_exists($this, $m)) { - continue; - } - $this->$m($value); - } - return $this; - } - - /** - * Get options - * - * @return array - */ - public function getOptions() - { - return array( - 'clearing_factor' => $this->getClearingFactor(), - 'clear_by_namespace' => $this->getClearByNamespace(), - ); - } - - /** - * Get automatic clearing factor - * - * @return int - */ - public function getClearingFactor() - { - return $this->clearingFactor; - } - - /** - * Set automatic clearing factor - * - * @param int $factor - * @return ClearByFactor Fluent interface - * @throws Exception\InvalidArgumentException - */ - public function setClearingFactor($factor) - { - $factor = (int) $factor; - if ($factor < 0) { - throw new Exception\InvalidArgumentAxception( - "Invalid clearing factor '{$factor}': must be greater or equal 0" - ); - } - $this->clearingFactor = $factor; - - return $this; - } - - /** - * Get flag to cleat items by namespace - * - * @return boolean - */ - public function getClearByNamespace() - { - return $this->clearByNamespace; - } - - /** - * Set flag to clear items by namespace - * - * @param boolean $flag - * @return ClearByFactor Fluent interface - */ - public function setClearByNamespace($flag) - { - $this->clearByNamespace = (bool) $flag; - return $this; - } - /** * Attach * @@ -218,10 +101,11 @@ public function detach(EventCollection $eventCollection) */ public function clearByFactor(PostEvent $event) { - $factor = $this->getClearingFactor(); + $options = $this->getOptions(); + $factor = $options->getClearingFactor(); if ($factor && $event->getResult() && mt_rand(1, $factor) == 1) { $params = $event->getParams(); - if ($this->getClearByNamespace()) { + if ($options->getClearByNamespace()) { $event->getStorage()->clearByNamespace(Adapter::MATCH_EXPIRED, $params['options']); } else { $event->getStorage()->clear(Adapter::MATCH_EXPIRED, $params['options']); diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 481b48e9f..6ec5630b6 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -24,7 +24,6 @@ use Traversable, Zend\Cache\Exception, Zend\Cache\Storage\ExceptionEvent, - Zend\Cache\Storage\Plugin, Zend\EventManager\EventCollection; /** @@ -33,20 +32,8 @@ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class ExceptionHandler implements Plugin +class ExceptionHandler extends AbstractPlugin { - /** - * Callback - */ - protected $callback = null; - - /** - * Throw exceptions - * - * @var bool - */ - protected $throwExceptions = true; - /** * Handles * @@ -54,104 +41,6 @@ class ExceptionHandler implements Plugin */ protected $handles = array(); - /** - * Constructor - * - * @param array|Traversable $options - * @return void - */ - public function __construct($options = array()) - { - $this->setOptions($options); - } - - /** - * Set options - * - * @param array|Traversable $options - * @return ExceptionHandler - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable object; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $name => $value) { - $m = 'set' . str_replace('_', '', $name); - if (!method_exists($this, $m)) { - continue; - } - $this->$m($value); - } - return $this; - } - - /** - * Get options - * - * @return array - */ - public function getOptions() - { - return array( - 'callback' => $this->getCallback(), - 'throw_exceptions' => $this->getThrowExceptions(), - ); - } - - /** - * Set callback - * - * @param null|callable $callback - * @return ExceptionHandler - * @throws ExceptionHandler\InvalidArgumentException - */ - public function setCallback($callback) - { - if ($callback !== null && !is_callable($callback, true)) { - throw new ExceptionHandler\InvalidArgumentException('Not a valid callback'); - } - $this->callback = $callback; - return $this; - } - - /** - * Get callback - * - * @return null|callable - */ - public function getCallback() - { - return $this->callback; - } - - /** - * Set throw exceptions - * - * @param bool $flag - * @return ExceptionHandler - */ - public function setThrowExceptions($flag) - { - $this->throwExceptions = (bool) $flag; - return $this; - } - - /** - * Get throw exceptions - * - * @return bool - */ - public function getThrowExceptions() - { - return $this->throwExceptions; - } - /** * Attach * @@ -256,10 +145,11 @@ public function detach(EventCollection $eventCollection) */ public function onException(ExceptionEvent $event) { - if (($callback = $this->getCallback())) { + $options = $this->getOptions(); + if (($callback = $options->getExceptionCallback())) { call_user_func($callback, $event->getException()); } - $event->setThrowException($this->getThrowExceptions()); + $event->setThrowException($options->getThrowExceptions()); } } diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index 9726c2511..d57227022 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -23,7 +23,6 @@ use Traversable, Zend\Cache\Exception, - Zend\Cache\Storage\Plugin, Zend\Cache\Storage\PostEvent, Zend\EventManager\EventCollection; @@ -34,7 +33,7 @@ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class OptimizeByFactor implements Plugin +class OptimizeByFactor extends AbstractPlugin { /** * Handles @@ -43,92 +42,6 @@ class OptimizeByFactor implements Plugin */ protected $handles = array(); - /** - * Automatic optimizing factor - * - * @var int - */ - protected $optimizingFactor = 0; - - /** - * Constructor - * - * @param array|Traversable $options - * @return void - */ - public function __construct($options = array()) - { - $this->setOptions($options); - } - - /** - * Set options - * - * @param array|Traversable $options - * @return OptimizeByFactor - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable object; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $name => $value) { - $m = 'set' . str_replace('_', '', $name); - if (!method_exists($this, $m)) { - continue; - } - $this->$m($value); - } - return $this; - } - - /** - * Get options - * - * @return array - */ - public function getOptions() - { - return array( - 'optimizing_factor' => $this->getOptimizingFactor(), - ); - } - - /** - * Get automatic optimizing factor - * - * @return int - */ - public function getOptimizingFactor() - { - return $this->optimizingFactor; - } - - /** - * Set automatic optimizing factor - * - * @param int $factor - * @return OptimizeByFactor - * @throws Exception\InvalidArgumentAxception - */ - public function setOptimizingFactor($factor) - { - $factor = (int) $factor; - if ($factor < 0) { - throw new Exception\InvalidArgumentAxception( - "Invalid optimizing factor '{$factor}': must be greater or equal 0" - ); - } - $this->optimizingFactor = $factor; - - return $this; - } - /** * Attach * @@ -187,7 +100,7 @@ public function detach(EventCollection $eventCollection) */ public function optimizeByFactor(PostEvent $event) { - $factor = $this->getOptimizingFactor(); + $factor = $this->getOptions()->getOptimizingFactor(); if ($factor && $event->getResult() && mt_rand(1, $factor) == 1) { $params = $event->getParams(); $event->getStorage()->optimize($params['options']); diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php new file mode 100644 index 000000000..85e064a46 --- /dev/null +++ b/src/Storage/Plugin/PluginOptions.php @@ -0,0 +1,320 @@ +clearingFactor = $this->normalizeFactor($clearingFactor); + return $this; + } + + /** + * Get automatic clearing factor + * + * Used by: + * - ClearByFactor + * + * @return int + */ + public function getClearingFactor() + { + return $this->clearingFactor; + } + + /** + * Set flag indicating whether or not to clear by namespace + * + * Used by: + * - ClearByFactor + * + * @param bool $clearByNamespace + * @return PluginOptions + */ + public function setClearByNamespace($clearByNamespace) + { + $this->clearByNamespace = $clearByNamespace; + return $this; + } + + /** + * Clear items by namespace? + * + * Used by: + * - ClearByFactor + * + * @return bool + */ + public function getClearByNamespace() + { + return $this->clearByNamespace; + } + + /** + * Set callback to call on intercepted exception + * + * Used by: + * - ExceptionHandler + * + * @param callable EexceptionCallback + * @return PluginOptions + */ + public function setExceptionCallback($exceptionCallback) + { + if ($exceptionCallback !== null && !is_callable($exceptionCallback, true)) { + throw new ExceptionHandler\InvalidArgumentException('Not a valid callback'); + } + $this->exceptionCallback = $exceptionCallback; + return $this; + } + + /** + * Get callback to call on intercepted exception + * + * Used by: + * - ExceptionHandler + * + * @return null|callable + */ + public function getExceptionCallback() + { + return $this->exceptionCallback; + } + + /** + * Set automatic optimizing factor + * + * Used by: + * - OptimizeByFactor + * + * @param int $optimizingFactor + * @return PluginOptions + */ + public function setOptimizingFactor($optimizingFactor) + { + $this->optimizingFactor = $this->normalizeFactor($optimizingFactor); + return $this; + } + + /** + * Set automatic optimizing factor + * + * Used by: + * - OptimizeByFactor + * + * @return int + */ + public function getOptimizingFactor() + { + return $this->optimizingFactor; + } + + /** + * Set serializer + * + * Used by: + * - Serializer + * + * @param string|SerializerAdapter $serializer + * @return Serializer + */ + public function setSerializer($serializer) + { + if (!is_string($serializer) && !$serializer instanceof SerializerAdapter) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects either a string serializer name or Zend\Serializer\Adapter instance; ' + . 'received "%s"', + __METHOD__, + (is_object($serializer) ? get_class($serializer) : gettype($serializer)) + )); + } + $this->serializer = $serializer; + return $this; + } + + /** + * Get serializer + * + * Used by: + * - Serializer + * + * @return SerializerAdapter + */ + public function getSerializer() + { + if (is_string($this->serializer)) { + $options = $this->getSerializerOptions(); + $this->setSerializer(SerializerFactory::factory($this->serializer, $options)); + } elseif (null === $this->serializer) { + $this->setSerializer(SerializerFactory::getDefaultAdapter()); + } + + return $this->serializer; + } + + /** + * Set configuration options for instantiating a serializer adapter + * + * Used by: + * - Serializer + * + * @param array $serializerOptions + * @return PluginOptions + */ + public function setSerializerOptions(array $serializerOptions) + { + $this->serializerOptions = $serializerOptions; + return $this; + } + + /** + * Get configuration options for instantiating a serializer adapter + * + * Used by: + * - Serializer + * + * @return array + */ + public function getSerializerOptions() + { + return $this->serializerOptions; + } + + /** + * Set flag indicating we should re-throw exceptions + * + * Used by: + * - ExceptionHandler + * + * @param bool $throwExceptions + * @return PluginOptions + */ + public function setThrowExceptions($throwExceptions) + { + $this->throwExceptions = (bool) $throwExceptions; + return $this; + } + + /** + * Should we re-throw exceptions? + * + * Used by: + * - ExceptionHandler + * + * @return bool + */ + public function getThrowExceptions() + { + return $this->throwExceptions; + } + + /** + * Normalize a factor + * + * Cast to int and ensure we have a value greater than zero. + * + * @param int $factor + * @return int + * @throws Exception\InvalidArgumentException + */ + protected function normalizeFactor($factor) + { + $factor = (int) $factor; + if ($factor < 0) { + throw new Exception\InvalidArgumentAxception( + "Invalid factor '{$factor}': must be greater or equal 0" + ); + } + return $factor; + } +} diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index c2ab444ae..135a439ab 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -26,11 +26,8 @@ Zend\Cache\Exception, Zend\Cache\Storage\Capabilities, Zend\Cache\Storage\Event, - Zend\Cache\Storage\Plugin, Zend\Cache\Storage\PostEvent, - Zend\EventManager\EventCollection, - Zend\Serializer\Adapter as SerializerAdapter, - Zend\Serializer\Serializer as SerializerFactory; + Zend\EventManager\EventCollection; /** * @category Zend @@ -39,18 +36,9 @@ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Serializer implements Plugin +class Serializer extends AbstractPlugin { /** - * Serializer adapter - * - * @var SerializerAdapter - */ - protected $serializer; - - /** - * Capabilities - * * @var array */ protected $capabilities = array(); @@ -62,80 +50,6 @@ class Serializer implements Plugin */ protected $handles = array(); - /** - * Constructor - * - * @param array|Traversable $options - * @return void - */ - public function __construct($options = array()) - { - $this->setOptions($options); - } - - /** - * Set options - * - * @param array|Traversable $options - * @return Serializer - */ - public function setOptions($options) - { - if (!is_array($options) && !$options instanceof Traversable) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array or Traversable object; received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - - foreach ($options as $name => $value) { - $m = 'set' . str_replace('_', '', $name); - if (!method_exists($this, $m)) { - continue; - } - $this->$m($value); - } - return $this; - } - - /** - * Get options - * - * @return array - */ - public function getOptions() - { - return array( - 'serializer' => $this->getSerializer(), - ); - } - - /** - * Set serializer - * - * @param SerializerAdapter $serializer - * @return Serializer - */ - public function setSerializer(SerializerAdapter $serializer) - { - $this->serializer = $serializer; - return $this; - } - - /** - * Get serializer - * - * @return SerializerAdapter - */ - public function getSerializer() - { - if (!$this->serializer) { - return SerializerFactory::getDefaultAdapter(); - } - return $this->serializer; - } - /** * Attach * @@ -143,9 +57,9 @@ public function getSerializer() * @return Serializer * @throws Exception\LogicException */ - public function attach(EventCollection $eventCollection) + public function attach(EventCollection $events) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (isset($this->handles[$index])) { throw new Exception\LogicException('Plugin already attached'); } @@ -154,34 +68,34 @@ public function attach(EventCollection $eventCollection) $this->handles[$index] = & $handles; // read - $handles[] = $eventCollection->attach('getItem.post', array($this, 'onReadItemPost')); - $handles[] = $eventCollection->attach('getItems.post', array($this, 'onReadItemsPost')); + $handles[] = $events->attach('getItem.post', array($this, 'onReadItemPost')); + $handles[] = $events->attach('getItems.post', array($this, 'onReadItemsPost')); // fetch / fetchAll - $handles[] = $eventCollection->attach('fetch.post', array($this, 'onFetchPost')); - $handles[] = $eventCollection->attach('fetchAll.post', array($this, 'onFetchAllPost')); + $handles[] = $events->attach('fetch.post', array($this, 'onFetchPost')); + $handles[] = $events->attach('fetchAll.post', array($this, 'onFetchAllPost')); // write - $handles[] = $eventCollection->attach('setItem.pre', array($this, 'onWriteItemPre')); - $handles[] = $eventCollection->attach('setItems.pre', array($this, 'onWriteItemsPre')); + $handles[] = $events->attach('setItem.pre', array($this, 'onWriteItemPre')); + $handles[] = $events->attach('setItems.pre', array($this, 'onWriteItemsPre')); - $handles[] = $eventCollection->attach('addItem.pre', array($this, 'onWriteItemPre')); - $handles[] = $eventCollection->attach('addItems.pre', array($this, 'onWriteItemsPre')); + $handles[] = $events->attach('addItem.pre', array($this, 'onWriteItemPre')); + $handles[] = $events->attach('addItems.pre', array($this, 'onWriteItemsPre')); - $handles[] = $eventCollection->attach('replaceItem.pre', array($this, 'onWriteItemPre')); - $handles[] = $eventCollection->attach('replaceItems.pre', array($this, 'onWriteItemsPre')); + $handles[] = $events->attach('replaceItem.pre', array($this, 'onWriteItemPre')); + $handles[] = $events->attach('replaceItems.pre', array($this, 'onWriteItemsPre')); - $handles[] = $eventCollection->attach('checkAndSetItem.pre', array($this, 'onWriteItemPre')); + $handles[] = $events->attach('checkAndSetItem.pre', array($this, 'onWriteItemPre')); // increment / decrement item(s) - $handles[] = $eventCollection->attach('incrementItem.pre', array($this, 'onIncrementItemPre')); - $handles[] = $eventCollection->attach('incrementItems.pre', array($this, 'onIncrementItemsPre')); + $handles[] = $events->attach('incrementItem.pre', array($this, 'onIncrementItemPre')); + $handles[] = $events->attach('incrementItems.pre', array($this, 'onIncrementItemsPre')); - $handles[] = $eventCollection->attach('decrementItem.pre', array($this, 'onDecrementItemPre')); - $handles[] = $eventCollection->attach('decrementItems.pre', array($this, 'onDecrementItemsPre')); + $handles[] = $events->attach('decrementItem.pre', array($this, 'onDecrementItemPre')); + $handles[] = $events->attach('decrementItems.pre', array($this, 'onDecrementItemsPre')); // overwrite capabilities - $handles[] = $eventCollection->attach('getCapabilities.post', array($this, 'onGetCapabilitiesPost')); + $handles[] = $events->attach('getCapabilities.post', array($this, 'onGetCapabilitiesPost')); return $this; } @@ -189,20 +103,20 @@ public function attach(EventCollection $eventCollection) /** * Detach * - * @param EventCollection $eventCollection + * @param EventCollection $events * @return Serializer * @throws Exception\LogicException */ - public function detach(EventCollection $eventCollection) + public function detach(EventCollection $events) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (!isset($this->handles[$index])) { throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index foreach ($this->handles[$index] as $handle) { - $eventCollection->detach($handle); + $events->detach($handle); } // remove all detached handles @@ -219,7 +133,8 @@ public function detach(EventCollection $eventCollection) */ public function onReadItemPost(PostEvent $event) { - $serializer = $this->getSerializer(); + $options = $this->getOptions(); + $serializer = $options->getSerializer(); $result = $event->getResult(); $result = $serializer->unserialize($result); $event->setResult($result); @@ -233,7 +148,8 @@ public function onReadItemPost(PostEvent $event) */ public function onReadItemsPost(PostEvent $event) { - $serializer = $this->getSerializer(); + $options = $this->getOptions(); + $serializer = $options->getSerializer(); $result = $event->getResult(); foreach ($result as &$value) { $value = $serializer->unserialize($value); @@ -249,9 +165,11 @@ public function onReadItemsPost(PostEvent $event) */ public function onFetchPost(PostEvent $event) { - $item = $event->getResult(); + $options = $this->getOptions(); + $serializer = $options->getSerializer(); + $item = $event->getResult(); if (isset($item['value'])) { - $item['value'] = $this->getSerializer()->unserialize($item['value']); + $item['value'] = $serializer->unserialize($item['value']); } $event->setResult($item); } @@ -264,7 +182,8 @@ public function onFetchPost(PostEvent $event) */ public function onFetchAllPost(PostEvent $event) { - $serializer = $this->getSerializer(); + $options = $this->getOptions(); + $serializer = $options->getSerializer(); $result = $event->getResult(); foreach ($result as &$item) { if (isset($item['value'])) { @@ -282,7 +201,8 @@ public function onFetchAllPost(PostEvent $event) */ public function onWriteItemPre(Event $event) { - $serializer = $this->getSerializer(); + $options = $this->getOptions(); + $serializer = $options->getSerializer(); $params = $event->getParams(); $params['value'] = $serializer->serialize($params['value']); } @@ -295,7 +215,8 @@ public function onWriteItemPre(Event $event) */ public function onWriteItemsPre(Event $event) { - $serializer = $this->getSerializer(); + $options = $this->getOptions(); + $serializer = $options->getSerializer(); $params = $event->getParams(); foreach ($params['keyValuePairs'] as &$value) { $value = $serializer->serialize($value); diff --git a/test/Storage/Plugin/ClearByFactorTest.php b/test/Storage/Plugin/ClearByFactorTest.php index 4912e630a..bf14fac56 100644 --- a/test/Storage/Plugin/ClearByFactorTest.php +++ b/test/Storage/Plugin/ClearByFactorTest.php @@ -19,9 +19,11 @@ class ClearByFactorTest extends CommonPluginTest public function setUp() { $this->_adapter = new MockAdapter(); - $this->_plugin = new Cache\Storage\Plugin\ClearByFactor(array( + $this->_options = new Cache\Storage\Plugin\PluginOptions(array( 'clearing_factor' => 1, )); + $this->_plugin = new Cache\Storage\Plugin\ClearByFactor(); + $this->_plugin->setOptions($this->_options); parent::setUp(); } @@ -64,8 +66,8 @@ public function testRemovePlugin() public function testClearByFactorUsingNamespace() { $adapter = $this->getMock(get_class($this->_adapter), array('clearByNamespace')); - $this->_plugin->setClearingFactor(1); - $this->_plugin->setClearByNamespace(true); + $this->_options->setClearingFactor(1); + $this->_options->setClearByNamespace(true); // test optimize will be called $adapter @@ -87,8 +89,8 @@ public function testClearByFactorUsingNamespace() public function testClearByFactorAllNamespaces() { $adapter = $this->getMock(get_class($this->_adapter), array('clear')); - $this->_plugin->setClearingFactor(1); - $this->_plugin->setClearByNamespace(false); + $this->_options->setClearingFactor(1); + $this->_options->setClearByNamespace(false); // test optimize will be called $adapter diff --git a/test/Storage/Plugin/CommonPluginTest.php b/test/Storage/Plugin/CommonPluginTest.php index 34c5f66d9..216ac846a 100644 --- a/test/Storage/Plugin/CommonPluginTest.php +++ b/test/Storage/Plugin/CommonPluginTest.php @@ -44,62 +44,16 @@ abstract class CommonPluginTest extends \PHPUnit_Framework_TestCase */ protected $_plugin; - public function testOptionNamesValid() + public function testOptionObjectAvailable() { $options = $this->_plugin->getOptions(); - foreach ($options as $name => $value) { - $this->assertRegExp( - '/^[a-z]+[a-z0-9_]*[a-z0-9]+$/', - $name, - "Invalid option name '{$name}'" - ); - } - } - - public function testGettersAndSettersOfOptionsExists() - { - $options = $this->_plugin->getOptions(); - foreach ($options as $option => $value) { - $method = ucwords(str_replace('_', ' ', $option)); - $method = str_replace(' ', '', $method); - - $this->assertTrue( - method_exists($this->_plugin, 'set' . $method), - "Missing method 'set'{$method}" - ); - - $this->assertTrue( - method_exists($this->_plugin, 'get' . $method), - "Missing method 'get'{$method}" - ); - } + $this->assertInstanceOf('Zend\Cache\Storage\Plugin\PluginOptions', $options); } public function testOptionsGetAndSetDefault() { $options = $this->_plugin->getOptions(); $this->_plugin->setOptions($options); - $this->assertEquals($options, $this->_plugin->getOptions()); + $this->assertSame($options, $this->_plugin->getOptions()); } - - public function testOptionsFluentInterface() - { - $options = $this->_plugin->getOptions(); - foreach ($options as $option => $value) { - $method = ucwords(str_replace('_', ' ', $option)); - $method = 'set' . str_replace(' ', '', $method); - $this->assertSame( - $this->_plugin, - $this->_plugin->{$method}($value), - "Method '{$method}' doesn't implement the fluent interface" - ); - } - - $this->assertSame( - $this->_plugin, - $this->_plugin->setOptions(array()), - "Method 'setOptions' doesn't implement the fluent interface" - ); - } - } diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php index 17b0cd182..0bfb700d9 100644 --- a/test/Storage/Plugin/ExceptionHandlerTest.php +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -19,7 +19,9 @@ class ExceptionHandlerTest extends CommonPluginTest public function setUp() { $this->_adapter = new MockAdapter(); + $this->_options = new Cache\Storage\Plugin\PluginOptions(); $this->_plugin = new Cache\Storage\Plugin\ExceptionHandler(); + $this->_plugin->setOptions($this->_options); parent::setUp(); } @@ -103,7 +105,7 @@ public function testOnExceptionCallCallback() $expectedException = new \Exception(); $callbackCalled = false; - $this->_plugin->setCallback(function ($exception) use ($expectedException, &$callbackCalled) { + $this->_options->setExceptionCallback(function ($exception) use ($expectedException, &$callbackCalled) { $callbackCalled = ($exception === $expectedException); }); @@ -122,7 +124,7 @@ public function testOnExceptionCallCallback() public function testDontThrowException() { - $this->_plugin->setThrowExceptions(false); + $this->_options->setThrowExceptions(false); // run onException $event = new ExceptionEvent('getItem.exception', $this->_adapter, new ArrayObject(array( diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index 4e90026f6..b011051d9 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -19,9 +19,11 @@ class OptimizeByFactorTest extends CommonPluginTest public function setUp() { $this->_adapter = new MockAdapter(); - $this->_plugin = new Cache\Storage\Plugin\OptimizeByFactor(array( - 'optimizing_factor' => 1 + $this->_options = new Cache\Storage\Plugin\PluginOptions(array( + 'optimizing_factor' => 1, )); + $this->_plugin = new Cache\Storage\Plugin\OptimizeByFactor(); + $this->_plugin->setOptions($this->_options); } public function testAddPlugin() diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index 20c044dfe..997c7b4f1 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -48,7 +48,9 @@ class SerializerTest extends CommonPluginTest public function setUp() { $this->_adapter = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); + $this->_options = new Cache\Storage\Plugin\PluginOptions(); $this->_plugin = new Cache\Storage\Plugin\Serializer(); + $this->_plugin->setOptions($this->_options); } public function testAddPlugin() From d140f04d3720814a92620403f27d3136ad510634 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 13 Dec 2011 23:27:51 +0100 Subject: [PATCH 141/311] fixed small bugs related on re-write PluginOptions --- src/Storage/Plugin/PluginOptions.php | 18 +++++++++--------- test/Storage/TestAsset/MockPlugin.php | 20 ++------------------ test/StorageFactoryTest.php | 5 ++++- 3 files changed, 15 insertions(+), 28 deletions(-) diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index 85e064a46..61ac53e5a 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -98,7 +98,7 @@ public function setClearingFactor($clearingFactor) $this->clearingFactor = $this->normalizeFactor($clearingFactor); return $this; } - + /** * Get automatic clearing factor * @@ -126,7 +126,7 @@ public function setClearByNamespace($clearByNamespace) $this->clearByNamespace = $clearByNamespace; return $this; } - + /** * Clear items by namespace? * @@ -152,12 +152,12 @@ public function getClearByNamespace() public function setExceptionCallback($exceptionCallback) { if ($exceptionCallback !== null && !is_callable($exceptionCallback, true)) { - throw new ExceptionHandler\InvalidArgumentException('Not a valid callback'); + throw new Exception\InvalidArgumentException('Not a valid callback'); } $this->exceptionCallback = $exceptionCallback; return $this; } - + /** * Get callback to call on intercepted exception * @@ -185,7 +185,7 @@ public function setOptimizingFactor($optimizingFactor) $this->optimizingFactor = $this->normalizeFactor($optimizingFactor); return $this; } - + /** * Set automatic optimizing factor * @@ -256,7 +256,7 @@ public function setSerializerOptions(array $serializerOptions) $this->serializerOptions = $serializerOptions; return $this; } - + /** * Get configuration options for instantiating a serializer adapter * @@ -284,7 +284,7 @@ public function setThrowExceptions($throwExceptions) $this->throwExceptions = (bool) $throwExceptions; return $this; } - + /** * Should we re-throw exceptions? * @@ -302,8 +302,8 @@ public function getThrowExceptions() * Normalize a factor * * Cast to int and ensure we have a value greater than zero. - * - * @param int $factor + * + * @param int $factor * @return int * @throws Exception\InvalidArgumentException */ diff --git a/test/Storage/TestAsset/MockPlugin.php b/test/Storage/TestAsset/MockPlugin.php index d6026f58c..47de4a9ec 100644 --- a/test/Storage/TestAsset/MockPlugin.php +++ b/test/Storage/TestAsset/MockPlugin.php @@ -3,13 +3,13 @@ namespace ZendTest\Cache\Storage\TestAsset; use Zend\Cache\Storage\Plugin, + Zend\Cache\Storage\Plugin\AbstractPlugin, Zend\EventManager\EventCollection, Zend\EventManager\Event; -class MockPlugin implements Plugin +class MockPlugin extends AbstractPlugin { - protected $options = array(); protected $handles = array(); protected $calledEvents = array(); protected $eventCallbacks = array( @@ -17,22 +17,6 @@ class MockPlugin implements Plugin 'setItem.post' => 'onSetItemPost' ); - public function __construct($options = array()) - { - $this->setOptions($options); - } - - public function setOptions($options) - { - $this->options = $options; - return $this; - } - - public function getOptions() - { - return $this->options; - } - public function attach(EventCollection $eventCollection) { $handles = array(); diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index dd1ef581a..a5bec51f9 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -154,7 +154,10 @@ public function testFactoryWithPluginsAndOptionsArray() $pluginClass = get_class($plugin); switch ($pluginClass) { case 'Zend\Cache\Storage\Plugin\ClearByFactor': - $this->assertSame($factory['plugins']['ClearByFactor']['clearing_factor'], $plugin->getClearingFactor()); + $this->assertSame( + $factory['plugins']['ClearByFactor']['clearing_factor'], + $plugin->getOptions()->getClearingFactor() + ); break; case 'Zend\Cache\Storage\Plugin\Serializer': break; From 540cf84d673ae14b16af907005a19cf043882011 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 13 Dec 2011 17:38:10 -0600 Subject: [PATCH 142/311] Began refactoring Adapters to use options objects - Created base AdapterOptions for options used with all adapters - Created FilesystemOptions implementation for Filesystem adapter - Currently untested --- src/Storage/Adapter/AbstractAdapter.php | 384 ++---------- src/Storage/Adapter/AdapterOptions.php | 336 +++++++++++ src/Storage/Adapter/Filesystem.php | 697 ++++------------------ src/Storage/Adapter/FilesystemOptions.php | 570 ++++++++++++++++++ 4 files changed, 1089 insertions(+), 898 deletions(-) create mode 100644 src/Storage/Adapter/AdapterOptions.php create mode 100644 src/Storage/Adapter/FilesystemOptions.php diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 2ff99247c..040745e41 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -72,53 +72,11 @@ abstract class AbstractAdapter implements Adapter protected $capabilityMarker; /** - * Writable option - * - * @var boolean - */ - protected $writable = true; - - /** - * Readable option - * - * @var boolean - */ - protected $readable = true; - - /** - * TTL option - * - * @var int|float 0 means infinite or maximum of adapter - */ - protected $ttl = 0; - - /** - * Namespace option - * - * @var string - */ - protected $namespace = 'zfcache'; - - /** - * Validate namespace against pattern - * - * @var string - */ - protected $namespacePattern = ''; - - /** - * Validate key against pattern - * - * @var string - */ - protected $keyPattern = ''; - - /** - * Ignore missing items - * - * @var boolean + * options + * + * @var mixed */ - protected $ignoreMissingItems = true; + protected $options; /** * Is a statement active @@ -141,18 +99,6 @@ abstract class AbstractAdapter implements Adapter */ protected $stmtOptions = null; - /** - * Constructor - * - * @param array|Traversable $options - * @see setOptions() - * @return void - */ - public function __construct($options = array()) - { - $this->setOptions($options); - } - /** * Destructor * @@ -174,92 +120,39 @@ public function __destruct() /** * Set options. * - * @param array|Traversable $options + * @param array|Traversable|AdapterOptions $options * @return AbstractAdapter * @see getOptions() */ public function setOptions($options) { - if (!($options instanceof Traversable) && !is_array($options)) { - throw new Exception\InvalidArgumentException( - 'Options must be an array or an instance of Traversable' - ); - } - - foreach ($options as $option => $value) { - $method = 'set' - . str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($option)))); - if (!method_exists($this, $method)) { - continue; - } - $this->{$method}($value); + if (!is_array($options) + && !$options instanceof Traversable + && !$options instanceof AdapterOptions + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array, a Traversable object, or an AdapterOptions instance; ' + . 'received "%s"', + __METHOD__, + (is_object($options) ? get_class($options) : gettype($options)) + )); } - + $this->options = $options; return $this; } /** * Get options. * - * @return array + * @return AdapterOptions * @see setOptions() */ public function getOptions() { - return array( - 'writable' => $this->getWritable(), - 'readable' => $this->getReadable(), - 'caching' => $this->getCaching(), - 'ttl' => $this->getTtl(), - 'namespace' => $this->getNamespace(), - 'namespace_pattern' => $this->getNamespacePattern(), - 'key_pattern' => $this->getKeyPattern(), - 'ignore_missing_items' => $this->getIgnoreMissingItems(), - ); - } - - /** - * Enable/Disable writing data to cache. - * - * @param boolean $flag - * @return AbstractAdapter - */ - public function setWritable($flag) - { - $this->writable = (bool) $flag; - return $this; - } - - /** - * If writing data to cache enabled. - * - * @return boolean - */ - public function getWritable() - { - return $this->writable; - } - - /** - * Enable/Disable reading data from cache. - * - * @param boolean $flag - * @return AbstractAdapter - */ - public function setReadable($flag) - { - $this->readable = (bool) $flag; - return $this; - } - - /** - * If reading data from cache enabled. - * - * @return boolean - */ - public function getReadable() - { - return $this->readable; + if (!$this->options) { + $this->setOptions(new AdapterOptions()); + } + return $this->options; } /** @@ -274,9 +167,10 @@ public function getReadable() */ public function setCaching($flag) { - $flag = (bool) $flag; - $this->setWritable($flag); - $this->setReadable($flag); + $flag = (bool) $flag; + $options = $this->getOptions(); + $options->setWritable($flag); + $options->setReadable($flag); return $this; } @@ -291,172 +185,8 @@ public function setCaching($flag) */ public function getCaching() { - return ($this->getWritable() && $this->getReadable()); - } - - /** - * Set time to live. - * - * @param int|float $ttl - * @return AbstractAdapter - */ - public function setTtl($ttl) - { - $this->normalizeTtl($ttl); - $this->ttl = $ttl; - return $this; - } - - /** - * Get time to live. - * - * @return float - */ - public function getTtl() - { - return $this->ttl; - } - - /** - * Set namespace. - * - * @param string $namespace - * @return AbstractAdapter - */ - public function setNamespace($namespace) - { - $nameapace = (string)$namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } - - if (($pattern = $this->getNamespacePattern()) - && !preg_match($pattern, $namespace) - ) { - throw new Exception\InvalidArgumentException( - "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" - ); - } - $this->namespace = (string) $namespace; - return $this; - } - - /** - * Get namespace - * - * @return string - */ - public function getNamespace() - { - return $this->namespace; - } - - /** - * Set namespace pattern - * - * @param null|string $pattern - * @return AbstractAdapter - */ - public function setNamespacePattern($pattern) - { - if (($pattern = (string) $pattern) === '') { - $this->namespacePattern = ''; - return $this; - } - - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - - // validate current namespace - } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { - throw new Exception\RuntimeException( - "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" - . " - please change the namespace first" - ); - } - - $this->namespacePattern = $pattern; - - return $this; - } - - /** - * Get namespace pattern - * - * @return string - */ - public function getNamespacePattern() - { - return $this->namespacePattern; - } - - /** - * Set key pattern - * - * @param null|string $pattern - * @return AbstractAdapter - */ - public function setKeyPattern($pattern) - { - if (($pattern = (string)$pattern) === '') { - $this->keyPattern = ''; - return $this; - } - - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - } - - $this->keyPattern = $pattern; - - return $this; - } - - /** - * Get key pattern - * - * @return string - */ - public function getKeyPattern() - { - return $this->keyPattern; - } - - /** - * Enables or disables ignoring of missing items. - * - * - If enabled and a missing item was requested: - * - getItem, getMetadata: return false - * - removeItem[s]: return true - * - incrementItem[s], decrementItem[s]: add a new item with 0 as base - * - touchItem[s]: add new empty item - * - * - If disabled and a missing item was requested: - * - getItem, getMetadata, incrementItem[s], decrementItem[s], touchItem[s] - * throws ItemNotFoundException - * - * @param boolean $flag - * @return Adapter - */ - public function setIgnoreMissingItems($flag) - { - $this->ignoreMissingItems = (bool) $flag; - return $this; - } - - /** - * Ignore missing items - * - * @return boolean - * @see setIgnoreMissingItems() - */ - public function getIgnoreMissingItems() - { - return $this->ignoreMissingItems; + $options = $this->getOptions(); + return ($options->getWritable() && $options->getReadable()); } /* Event/Plugin handling */ @@ -619,7 +349,8 @@ public function getPlugins() */ public function getItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $options = $this->getOptions(); + if (!$options->getReadable()) { return array(); } @@ -647,7 +378,7 @@ public function getItems(array $keys, array $options = array()) */ public function hasItem($key, array $options = array()) { - if (!$this->getReadable()) { + if (!$this->getOptions()->getReadable()) { return false; } @@ -669,7 +400,7 @@ public function hasItem($key, array $options = array()) */ public function hasItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + if (!$this->getOptions()->getReadable()) { return array(); } @@ -692,7 +423,7 @@ public function hasItems(array $keys, array $options = array()) */ public function getMetadatas(array $keys, array $options = array()) { - if (!$this->getReadable()) { + if (!$this->getOptions()->getReadable()) { return array(); } @@ -722,7 +453,7 @@ public function getMetadatas(array $keys, array $options = array()) */ public function setItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -760,7 +491,7 @@ public function addItem($key, $value, array $options = array()) */ public function addItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -798,7 +529,7 @@ public function replaceItem($key, $value, array $options = array()) */ public function replaceItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -838,7 +569,8 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) */ public function touchItem($key, array $options = array()) { - if (!$this->getWritable() || !$this->getReadable()) { + $classOptions = $this->getOptions(); + if (!$classOptions->getWritable() || !$classOptions->getReadable()) { return false; } @@ -873,7 +605,7 @@ public function touchItem($key, array $options = array()) public function touchItems(array $keys, array $options = array()) { // Don't check readable because not all adapters needs to read the item before - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -893,7 +625,7 @@ public function touchItems(array $keys, array $options = array()) */ public function removeItems(array $keys, array $options = array()) { - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -915,14 +647,15 @@ public function removeItems(array $keys, array $options = array()) */ public function incrementItem($key, $value, array $options = array()) { - if (!$this->getWritable() || !$this->getReadable()) { - return false; - } + $classOptions = $this->getOptions(); + if (!$classOptions->getWritable() || !$classOptions->getReadable()) { + return false; + } - $value = (int) $value; - $get = (int) $this->getItem($key, $options); - $this->setItem($key, $get + $value, $options); - return $get + $value; + $value = (int) $value; + $get = (int) $this->getItem($key, $options); + $this->setItem($key, $get + $value, $options); + return $get + $value; } /** @@ -935,7 +668,7 @@ public function incrementItem($key, $value, array $options = array()) public function incrementItems(array $keyValuePairs, array $options = array()) { // Don't check readable because not all adapters needs read the value before - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -956,7 +689,8 @@ public function incrementItems(array $keyValuePairs, array $options = array()) */ public function decrementItem($key, $value, array $options = array()) { - if (!$this->getWritable() || !$this->getReadable()) { + $classOptions = $this->getOptions(); + if (!$classOptions->getWritable() || !$classOptions->getReadable()) { return false; } @@ -976,7 +710,7 @@ public function decrementItem($key, $value, array $options = array()) public function decrementItems(array $keyValuePairs, array $options = array()) { // Don't check readable because not all adapters needs read the value before - if (!$this->getWritable()) { + if (!$this->getOptions()->getWritable()) { return false; } @@ -1003,7 +737,7 @@ public function getDelayed(array $keys, array $options = array()) throw new Exception\RuntimeException('Statement already in use'); } - if (!$this->getReadable()) { + if (!$this->getOptions()->getReadable()) { return false; } elseif (!$keys) { // empty statement @@ -1016,7 +750,7 @@ public function getDelayed(array $keys, array $options = array()) $options['select'] = array('key', 'value'); } - $this->stmtOptions = array_merge($this->getOptions(), $options); + $this->stmtOptions = array_merge($this->getOptions()->toArray(), $options); $this->stmtKeys = $keys; $this->stmtActive = true; @@ -1189,25 +923,27 @@ public function getCapabilities() */ protected function normalizeOptions(array &$options) { + $baseOptions = $this->getOptions(); + // ttl if (isset($options['ttl'])) { $this->normalizeTtl($options['ttl']); } else { - $options['ttl'] = $this->getTtl(); + $options['ttl'] = $baseOptions->getTtl(); } // namespace if (isset($options['namespace'])) { $this->normalizeNamespace($options['namespace']); } else { - $options['namespace'] = $this->getNamespace(); + $options['namespace'] = $baseOptions->getNamespace(); } // ignore_missing_items if (isset($options['ignore_missing_items'])) { $options['ignore_missing_items'] = (bool) $options['ignore_missing_items']; } else { - $options['ignore_missing_items'] = $this->getIgnoreMissingItems(); + $options['ignore_missing_items'] = $baseOptions->getIgnoreMissingItems(); } // tags @@ -1259,7 +995,7 @@ protected function normalizeNamespace(&$namespace) if ($namespace === '') { throw new Exception\InvalidArgumentException('Empty namespaces are not allowed'); - } elseif (($p = $this->getNamespacePattern()) && !preg_match($p, $namespace)) { + } elseif (($p = $baseOptions->getNamespacePattern()) && !preg_match($p, $namespace)) { throw new Exception\InvalidArgumentException( "The namespace '{$namespace}' doesn't match against pattern '{$p}'" ); @@ -1330,7 +1066,7 @@ protected function normalizeKey(&$key) { $key = (string) $key; - if (($p = $this->getKeyPattern()) && !preg_match($p, $key)) { + if (($p = $this->getOptions()->getKeyPattern()) && !preg_match($p, $key)) { throw new Exception\InvalidArgumentException( "The key '{$key}' doesn't match agains pattern '{$p}'" ); diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php new file mode 100644 index 000000000..20bb0101a --- /dev/null +++ b/src/Storage/Adapter/AdapterOptions.php @@ -0,0 +1,336 @@ + $value) { + $normalizedKey = preg_replace_callback('/([A-Z])/', $transform, $key); + $array[$normalizedKey] = $value; + } + return $array; + } + + /** + * Enables or disables ignoring of missing items. + * + * - If enabled and a missing item was requested: + * - getItem, getMetadata: return false + * - removeItem[s]: return true + * - incrementItem[s], decrementItem[s]: add a new item with 0 as base + * - touchItem[s]: add new empty item + * + * - If disabled and a missing item was requested: + * - getItem, getMetadata, incrementItem[s], decrementItem[s], touchItem[s] + * throws ItemNotFoundException + * + * @param boolean $flag + * @return AdapterOptions + */ + public function setIgnoreMissingItems($flag) + { + $this->ignoreMissingItems = (bool) $flag; + return $this; + } + + /** + * Ignore missing items + * + * @return boolean + * @see setIgnoreMissingItems() + */ + public function getIgnoreMissingItems() + { + return $this->ignoreMissingItems; + } + + /** + * Set key pattern + * + * @param null|string $pattern + * @return AdapterOptions + */ + public function setKeyPattern($pattern) + { + if (($pattern = (string) $pattern) === '') { + $this->keyPattern = ''; + return $this; + } + + // validate pattern + if (@preg_match($pattern, '') === false) { + $err = error_get_last(); + throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); + } + + $this->keyPattern = $pattern; + + return $this; + } + + /** + * Get key pattern + * + * @return string + */ + public function getKeyPattern() + { + return $this->keyPattern; + } + + /** + * Set namespace. + * + * @param string $namespace + * @return AdapterOptions + */ + public function setNamespace($namespace) + { + $nameapace = (string)$namespace; + if ($namespace === '') { + throw new Exception\InvalidArgumentException('No namespace given'); + } + + if (($pattern = $this->getNamespacePattern()) + && !preg_match($pattern, $namespace) + ) { + throw new Exception\InvalidArgumentException( + "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" + ); + } + $this->namespace = (string) $namespace; + return $this; + } + + /** + * Get namespace + * + * @return string + */ + public function getNamespace() + { + return $this->namespace; + } + + /** + * Set namespace pattern + * + * @param null|string $pattern + * @return AdapterOptions + */ + public function setNamespacePattern($pattern) + { + if (($pattern = (string) $pattern) === '') { + $this->namespacePattern = ''; + return $this; + } + + // validate pattern + if (@preg_match($pattern, '') === false) { + $err = error_get_last(); + throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); + + // validate current namespace + } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { + throw new Exception\RuntimeException( + "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" + . " - please change the namespace first" + ); + } + + $this->namespacePattern = $pattern; + + return $this; + } + + /** + * Get namespace pattern + * + * @return string + */ + public function getNamespacePattern() + { + return $this->namespacePattern; + } + + /** + * Enable/Disable reading data from cache. + * + * @param boolean $flag + * @return AbstractAdapter + */ + public function setReadable($flag) + { + $this->readable = (bool) $flag; + return $this; + } + + /** + * If reading data from cache enabled. + * + * @return boolean + */ + public function getReadable() + { + return $this->readable; + } + + /** + * Set time to live. + * + * @param int|float $ttl + * @return AdapterOptions + */ + public function setTtl($ttl) + { + $this->normalizeTtl($ttl); + $this->ttl = $ttl; + return $this; + } + + /** + * Get time to live. + * + * @return float + */ + public function getTtl() + { + return $this->ttl; + } + + /** + * Enable/Disable writing data to cache. + * + * @param boolean $flag + * @return AdapterOptions + */ + public function setWritable($flag) + { + $this->writable = (bool) $flag; + return $this; + } + + /** + * If writing data to cache enabled. + * + * @return boolean + */ + public function getWritable() + { + return $this->writable; + } + + /** + * Validates and normalize a TTL. + * + * @param int|float $ttl + * @throws Exception\InvalidArgumentException + */ + protected function normalizeTtl(&$ttl) + { + if (!is_int($ttl)) { + $ttl = (float) $ttl; + + // convert to int if possible + if ($ttl === (float) (int) $ttl) { + $ttl = (int) $ttl; + } + } + + if ($ttl < 0) { + throw new Exception\InvalidArgumentException("TTL can't be negative"); + } + } +} diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 62bac5713..ab8e6aa75 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -23,6 +23,7 @@ use ArrayObject, GlobIterator, + stdClass, Zend\Cache\Exception, Zend\Cache\Storage, Zend\Cache\Storage\Capabilities, @@ -37,108 +38,6 @@ */ class Filesystem extends AbstractAdapter { - /** - * Overwrite default namespace pattern - * - * @var string - */ - protected $namespacePattern = '/^[a-z0-9_\+\-]*$/Di'; - - /** - * Namespace separator - * - * @var string - */ - protected $namespaceSeparator = '-'; - - /** - * Overwrite default key pattern - */ - protected $keyPattern = '/^[a-z0-9_\+\-]*$/Di'; - - /** - * Directory to store cache files - * - * @var null|string The cache directory - * or NULL for the systems temporary directory - */ - protected $cacheDir = null; - - /** - * Used umask on creating a cache file - * - * @var int - */ - protected $fileUmask = 0117; - - /** - * Lock files on writing - * - * @var boolean - */ - protected $fileLocking = true; - - /** - * Block writing files until writing by another process finished. - * - * NOTE1: this only attempts if fileLocking is enabled - * NOTE3: if disabled writing operations return false in part of a locked file - * - * @var boolean - */ - protected $fileBlocking = true; - - /** - * Used umask on creating a cache directory - * - * @var int - */ - protected $dirUmask = 0007; - - /** - * How much sub-directaries should be created? - * - * @var int - */ - protected $dirLevel = 1; - - /** - * Don't get 'fileatime' as 'atime' on metadata - * - * @var boolean - */ - protected $noAtime = true; - - /** - * Don't get 'filectime' as 'ctime' on metadata - * - * @var boolean - */ - protected $noCtime = true; - - /** - * Read control enabled ? - * - * If enabled a hash (readControlAlgo) will be saved and check on read. - * - * @var boolean - */ - protected $readControl = false; - - /** - * The used hash algorithm if read control is enabled - * - * @var string - */ - protected $readControlAlgo = 'crc32'; - - /** - * Call clearstatcache enabled? - * - * @var boolean - */ - protected $clearStatCache = true; - /** * GlobIterator used as statement * @@ -173,420 +72,42 @@ class Filesystem extends AbstractAdapter /* configuration */ /** - * Get options - * - * @return array - */ - public function getOptions() - { - $options = parent::getOptions(); - $options['namespace_separator'] = $this->getNamespaceSeparator(); - $options['cache_dir'] = $this->getCacheDir(); - $options['file_perm'] = $this->getFilePerm(); - $options['file_umask'] = $this->getFileUmask(); - $options['file_locking'] = $this->getFileLocking(); - $options['file_blocking'] = $this->getFileBlocking(); - $options['dir_perm'] = $this->getDirPerm(); - $options['dir_umask'] = $this->getDirUmask(); - $options['dir_level'] = $this->getDirLevel(); - $options['no_atime'] = $this->getNoAtime(); - $options['no_ctime'] = $this->getNoCtime(); - $options['read_control'] = $this->getReadControl(); - $options['read_control_algo'] = $this->getReadControlAlgo(); - $options['clear_stat_cache'] = $this->getClearStatCache(); - return $options; - } - - /** - * Set namespace separator - * - * @param string $separator - * @return Filesystem - */ - public function setNamespaceSeparator($separator) - { - $this->namespaceSeparator = (string) $separator; - $this->updateCapabilities(); - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - - /** - * Set cache dir + * Set options. * - * @param string $dir - * @return Filesystem - * @throws Exception\InvalidArgumentException + * @param array|Traversable|FilesystemOptions $options + * @return FilesystemAdapter + * @see getOptions() */ - public function setCacheDir($dir) + public function setOptions($options) { - if ($dir !== null) { - if (!is_dir($dir)) { - throw new Exception\InvalidArgumentException( - "Cache directory '{$dir}' not found or not a directoy" - ); - } elseif (!is_writable($dir)) { - throw new Exception\InvalidArgumentException( - "Cache directory '{$dir}' not writable" - ); - } elseif (!is_readable($dir)) { - throw new Exception\InvalidArgumentException( - "Cache directory '{$dir}' not readable" - ); - } - - $dir = rtrim(realpath($dir), \DIRECTORY_SEPARATOR); - } - - $this->cacheDir = $dir; - return $this; - } - - /** - * Get cache dir - * - * @return null|string - */ - public function getCacheDir() - { - if ($this->cacheDir === null) { - $this->setCacheDir(sys_get_temp_dir()); - } - - return $this->cacheDir; - } - - /** - * Set file perm - * - * @param $perm - * @return Filesystem - */ - public function setFilePerm($perm) - { - if (is_string($perm)) { - $perm = octdec($perm); - } else { - $perm = (int) $perm; - } - - // use umask - return $this->setFileUmask(~$perm); - } - - /** - * Get file perm - * - * @return int - */ - public function getFilePerm() - { - return ~$this->getFileUmask(); - } - - /** - * Set file umask - * - * @param $umask - * @return Filesystem - * @throws Exception\InvalidArgumentException - */ - public function setFileUmask($umask) - { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int) $umask; - } - if ((~$umask & 0600) != 0600 ) { - throw new Exception\InvalidArgumentException( - 'Invalid file umask or file permission: ' - . 'need permissions to read and write files by owner' - ); - } elseif ((~$umask & 0111) > 0) { - throw new Exception\InvalidArgumentException( - 'Invalid file umask or file permission: ' - . 'executable cache files are not allowed' - ); - } - - $this->fileUmask = $umask; - return $this; - } - - /** - * Get file umask - * - * @return int - */ - public function getFileUmask() - { - return $this->fileUmask; - } - - /** - * Set file locking - * - * @param bool $flag - * @return Filesystem - */ - public function setFileLocking($flag) - { - $this->fileLocking = (bool)$flag; - return $this; - } - - /** - * Get file locking - * - * @return bool - */ - public function getFileLocking() - { - return $this->fileLocking; - } - - /** - * Set file blocking - * - * @param bool $flag - * @return Filesystem - */ - public function setFileBlocking($flag) - { - $this->fileBlocking = (bool) $flag; - return $this; - } - - /** - * Get file blocking - * - * @return bool - */ - public function getFileBlocking() - { - return $this->fileBlocking; - } - - /** - * Set no atime - * - * @param bool $flag - * @return Filesystem - */ - public function setNoAtime($flag) - { - $this->noAtime = (bool) $flag; - $this->updateCapabilities(); - return $this; - } - - /** - * Get no atime - * - * @return bool - */ - public function getNoAtime() - { - return $this->noAtime; - } - - /** - * Set no ctime - * - * @param bool $flag - * @return Filesystem - */ - public function setNoCtime($flag) - { - $this->noCtime = (bool) $flag; - $this->updateCapabilities(); - return $this; - } - - /** - * Get no ctime - * - * @return bool - */ - public function getNoCtime() - { - return $this->noCtime; - } - - /** - * Set dir perm - * - * @param string|integer $perm - * @return Filesystem - */ - public function setDirPerm($perm) - { - if (is_string($perm)) { - $perm = octdec($perm); - } else { - $perm = (int) $perm; - } - - // use umask - return $this->setDirUmask(~$perm); - } - - /** - * Get dir perm - * - * @return int - */ - public function getDirPerm() - { - return ~$this->getDirUmask(); - } - - /** - * Set dir umask - * - * @param string|integer $umask - * @return Filesystem - * @throws Exception\InvalidArgumentException - */ - public function setDirUmask($umask) - { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int) $umask; - } - - if ((~$umask & 0700) != 0700 ) { - throw new Exception\InvalidArgumentException( - 'Invalid directory umask or directory permissions: ' - . 'need permissions to execute, read and write directories by owner' - ); - } - - $this->dirUmask = $umask; - return $this; - } - - /** - * Get dir umask - * - * @return int - */ - public function getDirUmask() - { - return $this->dirUmask; - } - - /** - * Set dir level - * - * @param integer $level - * @return Filesystem - * @throws Exception\InvalidArgumentException - */ - public function setDirLevel($level) - { - $level = (int)$level; - if ($level < 0 || $level > 16) { - throw new Exception\InvalidArgumentException( - "Directory level '{$level}' have to be between 0 and 16" - ); - } - $this->dirLevel = $level; - return $this; - } - - /** - * Get dir level - * - * @return int - */ - public function getDirLevel() - { - return $this->dirLevel; - } - - /** - * Set read control - * - * @param bool $flag - * @return Filesystem - */ - public function setReadControl($flag) - { - $this->readControl = (bool) $flag; + if (!is_array($options) + && !$options instanceof Traversable + && !$options instanceof FilesystemOptions + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array, a Traversable object, or an FilesystemOptions instance; ' + . 'received "%s"', + __METHOD__, + (is_object($options) ? get_class($options) : gettype($options)) + )); + } + $this->options = $options; + $options->setTarget($this); return $this; } /** - * Get read control - * - * @return bool - */ - public function getReadControl() - { - return $this->readControl; - } - - /** - * Set real control algo + * Get options. * - * @param string $algo - * @return Filesystem - * @throws Exception\InvalidArgumentException + * @return AdapterOptions + * @see setOptions() */ - public function setReadControlAlgo($algo) + public function getOptions() { - $algo = strtolower($algo); - - if (!in_array($algo, Utils::getHashAlgos())) { - throw new Exception\InvalidArgumentException("Unsupported hash algorithm '{$algo}"); + if (!$this->options) { + $this->setOptions(new FilesystemOptions()); } - - $this->readControlAlgo = $algo; - return $this; - } - - /** - * Get read control algo - * - * @return string - */ - public function getReadControlAlgo() - { - return $this->readControlAlgo; - } - - /** - * Set clear stat cache - * - * @param bool $flag - * @return Filesystem - */ - public function setClearStatCache($flag) - { - $this->clearStatCache = (bool) $flag; - return $this; - } - - /** - * Get clear stat cache - * - * @return bool - */ - public function getClearStatCache() - { - return $this->clearStatCache; + return $this->options; } /* reading */ @@ -600,7 +121,8 @@ public function getClearStatCache() */ public function getItem($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -617,7 +139,7 @@ public function getItem($key, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -643,7 +165,8 @@ public function getItem($key, array $options = array()) */ public function getItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -662,7 +185,7 @@ public function getItems(array $keys, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -688,7 +211,8 @@ public function getItems(array $keys, array $options = array()) */ public function hasItem($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -705,7 +229,7 @@ public function hasItem($key, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -725,7 +249,8 @@ public function hasItem($key, array $options = array()) */ public function hasItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -741,7 +266,7 @@ public function hasItems(array $keys, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -767,7 +292,8 @@ public function hasItems(array $keys, array $options = array()) */ public function getMetadata($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -784,11 +310,11 @@ public function getMetadata($key, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } - $lastInfoId = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $lastInfoId = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; if ($this->lastInfoId == $lastInfoId && $this->lastInfoAll) { return $this->lastInfoAll; } @@ -810,7 +336,8 @@ public function getMetadata($key, array $options = array()) */ public function getMetadatas(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -829,7 +356,7 @@ public function getMetadatas(array $keys, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -859,7 +386,8 @@ public function getMetadatas(array $keys, array $options = array()) */ public function setItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -877,7 +405,7 @@ public function setItem($key, $value, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -897,7 +425,8 @@ public function setItem($key, $value, array $options = array()) */ public function setItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -913,7 +442,7 @@ public function setItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -939,7 +468,8 @@ public function setItems(array $keyValuePairs, array $options = array()) */ public function replaceItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -957,7 +487,7 @@ public function replaceItem($key, $value, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -982,7 +512,8 @@ public function replaceItem($key, $value, array $options = array()) */ public function replaceItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -998,7 +529,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -1027,7 +558,8 @@ public function replaceItems(array $keyValuePairs, array $options = array()) */ public function addItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1045,7 +577,7 @@ public function addItem($key, $value, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -1070,7 +602,8 @@ public function addItem($key, $value, array $options = array()) */ public function addItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1086,7 +619,7 @@ public function addItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -1117,7 +650,8 @@ public function addItems(array $keyValuePairs, array $options = array()) */ public function checkAndSetItem($token, $key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1136,7 +670,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -1171,7 +705,8 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) */ public function touchItem($key, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1188,7 +723,7 @@ public function touchItem($key, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } @@ -1211,7 +746,8 @@ public function touchItem($key, array $options = array()) */ public function touchItems(array $keys, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1248,7 +784,8 @@ public function touchItems(array $keys, array $options = array()) */ public function removeItem($key, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1284,7 +821,8 @@ public function removeItem($key, array $options = array()) */ public function removeItems(array $keys, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1328,13 +866,14 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) throw new Exception\RuntimeException('Statement already in use'); } - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - $options = array_merge($this->getOptions(), $options); + $options = array_merge($baseOptions->toArray(), $options); $args = new ArrayObject(array( 'mode' => & $mode, 'options' => & $options, @@ -1346,16 +885,16 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) return $eventRs->last(); } - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } try { - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); $find = $options['cache_dir'] . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new \GlobIterator($find); + $glob = new GlobIterator($find); $this->stmtActive = true; $this->stmtGlob = $glob; @@ -1464,7 +1003,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a return $eventRs->last(); } - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = $options['namespace'] . $this->getOptions()->getNamespaceSeparator(); $result = $this->clearByPrefix($prefix, $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { @@ -1480,7 +1019,8 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a */ public function optimize(array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1497,7 +1037,7 @@ public function optimize(array $options = array()) if ( ($dirLevel = $this->getDirLevel()) ) { // removes only empty directories - $this->rmDir($this->getCacheDir(), $options['namespace'] . $this->getNamespaceSeparator()); + $this->rmDir($this->getCacheDir(), $options['namespace'] . $baseOptions->getNamespaceSeparator()); } $result = true; @@ -1525,7 +1065,7 @@ public function getCapabilities() } if ($this->capabilities === null) { - $this->capabilityMarker = new \stdClass(); + $this->capabilityMarker = new stdClass(); $this->capabilities = new Capabilities( $this->capabilityMarker, array( @@ -1546,7 +1086,7 @@ public function getCapabilities() 'expiredRead' => true, 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getNamespaceSeparator(), + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), 'iterable' => true, 'clearAllNamespaces' => true, 'clearByNamespace' => true, @@ -1600,9 +1140,10 @@ public function getCapacity(array $options = array()) */ protected function internalSetItem($key, $value, array &$options) { + $baseOptions = $this->getOptions(); $oldUmask = null; - $lastInfoId = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $lastInfoId = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; if ($this->lastInfoId == $lastInfoId) { $filespec = $this->lastInfo['filespec']; // if lastKeyInfo is available I'm sure that the cache directory exist @@ -1611,7 +1152,7 @@ protected function internalSetItem($key, $value, array &$options) if ($this->getDirLevel() > 0) { $path = dirname($filespec); if (!file_exists($path)) { - $oldUmask = umask($this->getDirUmask()); + $oldUmask = umask($baseOptions->getDirUmask()); if ( !@mkdir($path, 0777, true) ) { // reset umask on exception umask($oldUmask); @@ -1625,9 +1166,9 @@ protected function internalSetItem($key, $value, array &$options) } $info = null; - if ($this->getReadControl()) { + if ($baseOptions->getReadControl()) { $info['hash'] = Utils::generateHash($this->getReadControlAlgo(), $data, true); - $info['algo'] = $this->getReadControlAlgo(); + $info['algo'] = $baseOptions->getReadControlAlgo(); } if (isset($options['tags']) && $options['tags']) { @@ -1636,9 +1177,9 @@ protected function internalSetItem($key, $value, array &$options) try { if ($oldUmask !== null) { // $oldUmask could be defined on set directory_umask - umask($this->getFileUmask()); + umask($baseOptions->getFileUmask()); } else { - $oldUmask = umask($this->getFileUmask()); + $oldUmask = umask($baseOptions->getFileUmask()); } $ret = $this->putFileContent($filespec . '.dat', $value); @@ -1697,7 +1238,7 @@ protected function internalRemoveItem($key, array &$options) protected function internalGetItem($key, array &$options) { if ( !$this->internalHasItem($key, $options) - || !($keyInfo=$this->getKeyInfo($key, $options['namespace'])) + || !($keyInfo = $this->getKeyInfo($key, $options['namespace'])) ) { if ($options['ignore_missing_items']) { return false; @@ -1708,10 +1249,11 @@ protected function internalGetItem($key, array &$options) } } + $baseOptions = $this->getOptions(); try { $data = $this->getFileContent($keyInfo['filespec'] . '.dat'); - if ($this->getReadControl()) { + if ($baseOptions->getReadControl()) { if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) && isset($info['hash'], $info['algo']) ) { @@ -1767,7 +1309,8 @@ protected function internalHasItem($key, array &$options) * @return array|bool * @throws ItemNotFoundException */ - protected function internalGetMetadata($key, array &$options) { + protected function internalGetMetadata($key, array &$options) + { $keyInfo = $this->getKeyInfo($key, $options['namespace']); if (!$keyInfo) { if ($options['ignore_missing_items']) { @@ -1819,7 +1362,7 @@ protected function fetchByGlob() $options = $this->stmtOptions; $mode = $this->stmtMatch; - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = $options['namespace'] . $this->getOptions()->getNamespaceSeparator(); $prefixL = strlen($prefix); do { @@ -1926,21 +1469,22 @@ protected function fetchByGlob() */ protected function clearByPrefix($prefix, $mode, array &$opts) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $ttl = $opts['ttl']; - if ($this->getClearStatCache()) { + if ($baseOptions->getClearStatCache()) { clearstatcache(); } try { - $find = $this->getCacheDir() - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $this->getDirLevel()) + $find = $baseOptions->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $baseOptions->getDirLevel()) . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new \GlobIterator($find); + $glob = new GlobIterator($find); } catch (\Exception $e) { throw new Exception\RuntimeException('Instantiating GlobIterator failed', 0, $e); } @@ -2052,7 +1596,7 @@ protected function rmDir($dir, $prefix) */ protected function getKeyInfo($key, $ns) { - $lastInfoId = $ns . $this->getNamespaceSeparator() . $key; + $lastInfoId = $ns . $this->getOptions()->getNamespaceSeparator() . $key; if ($this->lastInfoId == $lastInfoId) { return $this->lastInfo; } @@ -2090,14 +1634,15 @@ protected function getKeyInfo($key, $ns) */ protected function getFileSpec($key, $ns) { - $prefix = $ns . $this->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $ns . $options->getNamespaceSeparator(); $lastInfoId = $prefix . $key; if ($this->lastInfoId == $lastInfoId) { return $this->lastInfo['filespec']; } - $path = $this->getCacheDir(); - $level = $this->getDirLevel(); + $path = $options->getCacheDir(); + $level = $options->getDirLevel(); if ( $level > 0 ) { // create up to 256 directories per directory level $hash = md5($key); @@ -2116,7 +1661,8 @@ protected function getFileSpec($key, $ns) * @return array|boolean The info array or false if file wasn't found * @throws Exception\RuntimeException */ - protected function readInfoFile($file) { + protected function readInfoFile($file) + { if (!file_exists($file)) { return false; } @@ -2140,7 +1686,7 @@ protected function readInfoFile($file) { protected function getFileContent($file) { // if file locking enabled -> file_get_contents can't be used - if ($this->getFileLocking()) { + if ($this->getOptions()->getFileLocking()) { $fp = @fopen($file, 'rb'); if ($fp === false) { $lastErr = error_get_last(); @@ -2185,8 +1731,9 @@ protected function getFileContent($file) */ protected function putFileContent($file, $data) { - $locking = $this->getFileLocking(); - $blocking = $locking ? $this->getFileBlocking() : false; + $options = $this->getOptions(); + $locking = $options->getFileLocking(); + $blocking = $locking ? $options->getFileBlocking() : false; if ($locking && !$blocking) { $fp = @fopen($file, 'cb'); @@ -2235,7 +1782,8 @@ protected function putFileContent($file, $data) * @return void * @throw RuntimeException */ - protected function unlink($file) { + protected function unlink($file) + { if (!@unlink($file)) { // only throw exception if file still exists after deleting if (file_exists($file)) { @@ -2253,21 +1801,22 @@ protected function unlink($file) { protected function updateCapabilities() { if ($this->capabilities) { + $options = $this->getOptions(); // update namespace separator $this->capabilities->setNamespaceSeparator( $this->capabilityMarker, - $this->getNamespaceSeparator() + $options->getNamespaceSeparator() ); // update metadata capabilities $metadata = array('mtime', 'filespec'); - if (!$this->getNoCtime()) { + if (!$options->getNoCtime()) { $metadata[] = 'ctime'; } - if (!$this->getNoAtime()) { + if (!$options->getNoAtime()) { $metadata[] = 'atime'; } diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php new file mode 100644 index 000000000..4052ef641 --- /dev/null +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -0,0 +1,570 @@ +target = $filesystem; + $this->updateCapabilities(); + return $this; + } + + /** + * Update target capabilities + * + * @return void + */ + protected function updateCapabilities() + { + if (!$this->target) { + return; + } + $this->target->updateCapabilities(); + } + + /** + * Set namespace separator + * + * @param string $separator + * @return Filesystem + */ + public function setNamespaceSeparator($separator) + { + $this->namespaceSeparator = (string) $separator; + $this->updateCapabilities(); + return $this; + } + + /** + * Get namespace separator + * + * @return string + */ + public function getNamespaceSeparator() + { + return $this->namespaceSeparator; + } + + /** + * Set cache dir + * + * @param string $dir + * @return Filesystem + * @throws Exception\InvalidArgumentException + */ + public function setCacheDir($dir) + { + if ($dir !== null) { + if (!is_dir($dir)) { + throw new Exception\InvalidArgumentException( + "Cache directory '{$dir}' not found or not a directoy" + ); + } elseif (!is_writable($dir)) { + throw new Exception\InvalidArgumentException( + "Cache directory '{$dir}' not writable" + ); + } elseif (!is_readable($dir)) { + throw new Exception\InvalidArgumentException( + "Cache directory '{$dir}' not readable" + ); + } + + $dir = rtrim(realpath($dir), \DIRECTORY_SEPARATOR); + } + + $this->cacheDir = $dir; + return $this; + } + + /** + * Get cache dir + * + * @return null|string + */ + public function getCacheDir() + { + if ($this->cacheDir === null) { + $this->setCacheDir(sys_get_temp_dir()); + } + + return $this->cacheDir; + } + + /** + * Set file perm + * + * @param $perm + * @return Filesystem + */ + public function setFilePerm($perm) + { + $perm = $this->normalizeUmask($perm); + + // use umask + return $this->setFileUmask(~$perm); + } + + /** + * Get file perm + * + * @return int + */ + public function getFilePerm() + { + return ~$this->getFileUmask(); + } + + /** + * Set file umask + * + * @param $umask + * @return Filesystem + * @throws Exception\InvalidArgumentException + */ + public function setFileUmask($umask) + { + $umask = $this->normalizeUmask($umask, function($umask) { + if ((~$umask & 0600) != 0600 ) { + throw new Exception\InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'need permissions to read and write files by owner' + ); + } elseif ((~$umask & 0111) > 0) { + throw new Exception\InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'executable cache files are not allowed' + ); + } + }); + + $this->fileUmask = $umask; + return $this; + } + + /** + * Get file umask + * + * @return int + */ + public function getFileUmask() + { + return $this->fileUmask; + } + + /** + * Set file locking + * + * @param bool $flag + * @return Filesystem + */ + public function setFileLocking($flag) + { + $this->fileLocking = (bool)$flag; + return $this; + } + + /** + * Get file locking + * + * @return bool + */ + public function getFileLocking() + { + return $this->fileLocking; + } + + /** + * Set file blocking + * + * @param bool $flag + * @return Filesystem + */ + public function setFileBlocking($flag) + { + $this->fileBlocking = (bool) $flag; + return $this; + } + + /** + * Get file blocking + * + * @return bool + */ + public function getFileBlocking() + { + return $this->fileBlocking; + } + + /** + * Set no atime + * + * @param bool $flag + * @return Filesystem + */ + public function setNoAtime($flag) + { + $this->noAtime = (bool) $flag; + $this->updateCapabilities(); + return $this; + } + + /** + * Get no atime + * + * @return bool + */ + public function getNoAtime() + { + return $this->noAtime; + } + + /** + * Set no ctime + * + * @param bool $flag + * @return Filesystem + */ + public function setNoCtime($flag) + { + $this->noCtime = (bool) $flag; + $this->updateCapabilities(); + return $this; + } + + /** + * Get no ctime + * + * @return bool + */ + public function getNoCtime() + { + return $this->noCtime; + } + + /** + * Set dir perm + * + * @param string|integer $perm + * @return Filesystem + */ + public function setDirPerm($perm) + { + $perm = $this->normalizeUmask($perm); + + // use umask + return $this->setDirUmask(~$perm); + } + + /** + * Get dir perm + * + * @return int + */ + public function getDirPerm() + { + return ~$this->getDirUmask(); + } + + /** + * Set dir umask + * + * @param string|integer $umask + * @return Filesystem + * @throws Exception\InvalidArgumentException + */ + public function setDirUmask($umask) + { + $umask = $this->normalizeUmask($umask, function($umask) { + if ((~$umask & 0700) != 0700 ) { + throw new Exception\InvalidArgumentException( + 'Invalid directory umask or directory permissions: ' + . 'need permissions to execute, read and write directories by owner' + ); + } + }); + + $this->dirUmask = $umask; + return $this; + } + + /** + * Get dir umask + * + * @return int + */ + public function getDirUmask() + { + return $this->dirUmask; + } + + /** + * Set dir level + * + * @param integer $level + * @return Filesystem + * @throws Exception\InvalidArgumentException + */ + public function setDirLevel($level) + { + $level = (int) $level; + if ($level < 0 || $level > 16) { + throw new Exception\InvalidArgumentException( + "Directory level '{$level}' must be between 0 and 16" + ); + } + $this->dirLevel = $level; + return $this; + } + + /** + * Get dir level + * + * @return int + */ + public function getDirLevel() + { + return $this->dirLevel; + } + + /** + * Set read control + * + * @param bool $flag + * @return Filesystem + */ + public function setReadControl($flag) + { + $this->readControl = (bool) $flag; + return $this; + } + + /** + * Get read control + * + * @return bool + */ + public function getReadControl() + { + return $this->readControl; + } + + /** + * Set real control algo + * + * @param string $algo + * @return Filesystem + * @throws Exception\InvalidArgumentException + */ + public function setReadControlAlgo($algo) + { + $algo = strtolower($algo); + + if (!in_array($algo, Utils::getHashAlgos())) { + throw new Exception\InvalidArgumentException("Unsupported hash algorithm '{$algo}"); + } + + $this->readControlAlgo = $algo; + return $this; + } + + /** + * Get read control algo + * + * @return string + */ + public function getReadControlAlgo() + { + return $this->readControlAlgo; + } + + /** + * Set clear stat cache + * + * @param bool $flag + * @return Filesystem + */ + public function setClearStatCache($flag) + { + $this->clearStatCache = (bool) $flag; + return $this; + } + + /** + * Get clear stat cache + * + * @return bool + */ + public function getClearStatCache() + { + return $this->clearStatCache; + } + + /** + * Normalize a umask and optionally apply a callback to it + * + * @param int|string $umask + * @param callable $callback + * @return int + */ + protected function normalizeUmask($umask, $callback = null) + { + if (is_string($umask)) { + $umask = octdec($umask); + } else { + $umask = (int) $umask; + } + + if (is_callable($callback)) { + $callback($umask); + } + + return $umask; + } +} From 3a219b89c286ee8f27f0b4a0f352148c7bf54257 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Wed, 14 Dec 2011 11:08:34 -0600 Subject: [PATCH 143/311] Refactored adapters to use Options objects - Created AdapterOptions class - Encapsulates options from the AbstractAdapter - Consumed by the AbstractAdapter and Memory adapter - Created specific options classes for the Filesystem and Apc adapters - Updated the StorageFactory to properly initialize adapters and plugins with the appropriate options classes - Ensured all tests are formed properly to test the above; all tests pass currently --- src/Storage/Adapter.php | 11 +- src/Storage/Adapter/AbstractAdapter.php | 13 +- src/Storage/Adapter/Apc.php | 157 ++++--- src/Storage/Adapter/ApcOptions.php | 65 +++ src/Storage/Adapter/Filesystem.php | 21 +- src/Storage/Adapter/FilesystemOptions.php | 429 ++++++++++--------- src/Storage/Adapter/Memory.php | 57 ++- src/StorageFactory.php | 34 +- test/Storage/Adapter/AbstractAdapterTest.php | 126 +++--- test/Storage/Adapter/ApcTest.php | 7 +- test/Storage/Adapter/CommonAdapterTest.php | 131 +++--- test/Storage/Adapter/FilesystemTest.php | 62 +-- test/Storage/Adapter/MemoryTest.php | 2 + test/Storage/TestAsset/MockPlugin.php | 11 +- test/StorageFactoryTest.php | 8 +- 15 files changed, 646 insertions(+), 488 deletions(-) create mode 100644 src/Storage/Adapter/ApcOptions.php diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index 0285eb707..d4ccc34a6 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -86,19 +86,12 @@ interface Adapter */ const MATCH_TAGS_AND_NOT = 030; - /** - * Constructor - * - * @param array|Traversable $options - */ - public function __construct($options = array()); - /* configuration */ /** * Set options. * - * @param array|Traversable $options + * @param array|Traversable|Adapter\AdapterOptions $options * @return Adapter */ public function setOptions($options); @@ -106,7 +99,7 @@ public function setOptions($options); /** * Get options * - * @return array + * @return Adapter\AdapterOptions */ public function getOptions(); diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 040745e41..05a571f25 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -137,6 +137,11 @@ public function setOptions($options) (is_object($options) ? get_class($options) : gettype($options)) )); } + + if (!$options instanceof AdapterOptions) { + $options = new AdapterOptions($options); + } + $this->options = $options; return $this; } @@ -349,8 +354,8 @@ public function getPlugins() */ public function getItems(array $keys, array $options = array()) { - $options = $this->getOptions(); - if (!$options->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -991,11 +996,11 @@ protected function normalizeTtl(&$ttl) */ protected function normalizeNamespace(&$namespace) { - $namespace = (string)$namespace; + $namespace = (string) $namespace; if ($namespace === '') { throw new Exception\InvalidArgumentException('Empty namespaces are not allowed'); - } elseif (($p = $baseOptions->getNamespacePattern()) && !preg_match($p, $namespace)) { + } elseif (($p = $this->getOptions()->getNamespacePattern()) && !preg_match($p, $namespace)) { throw new Exception\InvalidArgumentException( "The namespace '{$namespace}' doesn't match against pattern '{$p}'" ); diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index ed28ed4da..ea53c94ff 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -67,7 +67,7 @@ class Apc extends AbstractAdapter * @throws Exception * @return void */ - public function __construct($options = array()) + public function __construct() { if (version_compare('3.1.6', phpversion('apc')) > 0) { throw new Exception\ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); @@ -85,8 +85,8 @@ public function __construct($options = array()) } // init select map - if (self::$selectMap === null) { - self::$selectMap = array( + if (static::$selectMap === null) { + static::$selectMap = array( // 'key' => \APC_ITER_KEY, 'value' => \APC_ITER_VALUE, 'mtime' => \APC_ITER_MTIME, @@ -102,34 +102,49 @@ public function __construct($options = array()) 'internal_key' => \APC_ITER_KEY, ); } - - parent::__construct($options); } /* options */ /** - * Set namespace separator for keys - * - * @param string $separator - * @return Apc + * Set options. + * + * @param array|Traversable|ApcOptions $options + * @return ApcAdapter + * @see getOptions() */ - public function setNamespaceSeparator($separator) + public function setOptions($options) { - $this->namespaceSeparator = (string) $separator; + if (!is_array($options) + && !$options instanceof Traversable + && !$options instanceof ApcOptions + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array, a Traversable object, or an ApcOptions instance; ' + . 'received "%s"', + __METHOD__, + (is_object($options) ? get_class($options) : gettype($options)) + )); + } + $this->options = $options; return $this; } /** - * Get namespace separator for keys - * - * @return string + * Get options. + * + * @return ApcOptions + * @see setOptions() */ - public function getNamespaceSeparator() + public function getOptions() { - return $this->namespaceSeparator; + if (!$this->options) { + $this->setOptions(new ApcOptions()); + } + return $this->options; } + /* reading */ /** @@ -154,7 +169,8 @@ public function getNamespaceSeparator() */ public function getItem($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -171,7 +187,7 @@ public function getItem($key, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $result = apc_fetch($internalKey, $success); if (!$success) { if (!$options['ignore_missing_items']) { @@ -210,7 +226,8 @@ public function getItem($key, array $options = array()) */ public function getItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -226,9 +243,10 @@ public function getItems(array $keys, array $options = array()) return $eventRs->last(); } + $namespaceSep = $baseOptions->getNamespaceSeparator(); $internalKeys = array(); foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $internalKeys[] = $options['namespace'] . $namespaceSep . $key; } $fetch = apc_fetch($internalKeys); @@ -240,7 +258,7 @@ public function getItems(array $keys, array $options = array()) } // remove namespace prefix - $prefixL = strlen($options['namespace'] . $this->getNamespaceSeparator()); + $prefixL = strlen($options['namespace'] . $namespaceSep); $result = array(); foreach ($fetch as $internalKey => &$value) { $result[ substr($internalKey, $prefixL) ] = $value; @@ -272,7 +290,8 @@ public function getItems(array $keys, array $options = array()) */ public function hasItem($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -289,7 +308,7 @@ public function hasItem($key, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $result = apc_exists($internalKey); return $this->triggerPost(__FUNCTION__, $args, $result); @@ -318,7 +337,8 @@ public function hasItem($key, array $options = array()) */ public function hasItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -334,14 +354,15 @@ public function hasItems(array $keys, array $options = array()) return $eventRs->last(); } + $namespaceSep = $baseOptions->getNamespaceSeparator(); $internalKeys = array(); foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $internalKeys[] = $options['namespace'] . $namespaceSep . $key; } $exists = apc_exists($internalKeys); $result = array(); - $prefixL = strlen($options['namespace'] . $this->getNamespaceSeparator()); + $prefixL = strlen($options['namespace'] . $namespaceSep); foreach ($exists as $internalKey => $bool) { if ($bool === true) { $result[] = substr($internalKey, $prefixL); @@ -372,13 +393,14 @@ public function hasItems(array $keys, array $options = array()) */ public function getMetadata($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $key = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; $regexp = '/^' . preg_quote($key, '/') . '$/'; @@ -412,16 +434,18 @@ public function getMetadata($key, array $options = array()) */ public function getMetadatas(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } $this->normalizeOptions($options); $nsl = strlen($options['namespace']); - $keysRegExp = array(); + $namespaceSep = $baseOptions->getNamespaceSeparator(); + $keysRegExp = array(); foreach ($keys as &$key) { - $keysRegExp[] = preg_quote($options['namespace'] . $this->getNamespaceSeparator() . $key, '/'); + $keysRegExp[] = preg_quote($options['namespace'] . $namespaceSep . $key, '/'); } $regexp = '/^(' . implode('|', $keysRegExp) . ')$/'; @@ -437,7 +461,7 @@ public function getMetadatas(array $keys, array $options = array()) $this->normalizeMetadata($metadata); - $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); + $key = substr($internalKey, strpos($internalKey, $namespaceSep) + 1); $ret[$key] = & $metadata; } @@ -470,13 +494,14 @@ public function getMetadatas(array $keys, array $options = array()) */ public function setItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $key = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; if (!apc_store($key, $value, $options['ttl'])) { $type = is_object($value) ? get_class($value) : gettype($value); @@ -502,7 +527,8 @@ public function setItem($key, $value, array $options = array()) */ public function setItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -510,7 +536,7 @@ public function setItems(array $keyValuePairs, array $options = array()) $keyValuePairs2 = array(); foreach ($keyValuePairs as $key => &$value) { - $keyValuePairs2[ $options['namespace'] . $this->getNamespaceSeparator() . $key ] = &$value; + $keyValuePairs2[ $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key ] = &$value; } $errKeys = apc_store($keyValuePairs2, null, $options['ttl']); @@ -542,13 +568,14 @@ public function setItems(array $keyValuePairs, array $options = array()) */ public function addItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $key = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; if (!apc_add($key, $value, $options['ttl'])) { if (apc_exists($key)) { @@ -578,7 +605,8 @@ public function addItem($key, $value, array $options = array()) */ public function addItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -586,7 +614,7 @@ public function addItems(array $keyValuePairs, array $options = array()) $keyValuePairs2 = array(); foreach ($keyValuePairs as $key => &$value) { - $keyValuePairs2[ $options['namespace'] . $this->getNamespaceSeparator() . $key ] = &$value; + $keyValuePairs2[ $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key ] = &$value; } $errKeys = apc_add($keyValuePairs2, null, $options['ttl']); @@ -618,13 +646,14 @@ public function addItems(array $keyValuePairs, array $options = array()) */ public function replaceItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $key = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; if (!apc_exists($key)) { throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); @@ -654,13 +683,14 @@ public function replaceItem($key, $value, array $options = array()) */ public function removeItem($key, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $key = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; if (!apc_delete($key)) { if (!$options['ignore_missing_items']) { @@ -687,13 +717,14 @@ public function removeItem($key, array $options = array()) */ public function removeItems(array $keys, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); foreach ($keys as &$key) { - $key = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $key = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; } $errKeys = apc_delete($keys); @@ -723,13 +754,14 @@ public function removeItems(array $keys, array $options = array()) */ public function incrementItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $value = (int)$value; $newValue = apc_inc($internalKey, $value); @@ -768,13 +800,14 @@ public function incrementItem($key, $value, array $options = array()) */ public function decrementItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); - $internalKey = $options['namespace'] . $this->getNamespaceSeparator() . $key; + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $value = (int)$value; $newValue = apc_dec($internalKey, $value); @@ -812,7 +845,8 @@ public function getDelayed(array $keys, array $options = array()) throw new Exception\RuntimeException('Statement already in use'); } - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -822,7 +856,7 @@ public function getDelayed(array $keys, array $options = array()) $this->normalizeOptions($options); - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); $prefix = preg_quote($prefix, '/'); $format = 0; @@ -884,7 +918,8 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) throw new Exception\RuntimeException('Statement already in use'); } - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -895,7 +930,7 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) return true; } - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); $search = '/^' . preg_quote($prefix, '/') . '+/'; $format = 0; @@ -944,7 +979,10 @@ public function fetch() $select = $this->stmtOptions['select']; if (in_array('key', $select)) { $internalKey = $this->stmtIterator->key(); - $key = substr($internalKey, strpos($internalKey, $this->getNamespaceSeparator()) + 1); + $key = substr( + $internalKey, + strpos($internalKey, $this->getOptions()->getNamespaceSeparator()) + 1 + ); $metadata['key'] = $key; } } @@ -1001,7 +1039,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { $this->normalizeOptions($options); - $prefix = $options['namespace'] . $this->getNamespaceSeparator(); + $prefix = $options['namespace'] . $this->getOptions()->getNamespaceSeparator(); $regex = '/^' . preg_quote($prefix, '/') . '+/'; return $this->clearByRegEx($regex, $mode, $options); @@ -1049,7 +1087,7 @@ public function getCapabilities() 'expiredRead' => false, 'maxKeyLength' => 5182, 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getNamespaceSeparator(), + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), 'iterable' => true, 'clearAllNamespaces' => true, 'clearByNamespace' => true, @@ -1088,7 +1126,8 @@ public function getCapacity(array $options = array()) */ protected function clearByRegEx($regex, $mode, array &$options) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1127,7 +1166,7 @@ protected function normalizeMetadata(array &$metadata) // remove namespace prefix if (isset($metadata['key'])) { - $pos = strpos($metadata['key'], $this->getNamespaceSeparator()); + $pos = strpos($metadata['key'], $this->getOptions()->getNamespaceSeparator()); if ($pos !== false) { $metadata['internal_key'] = $metadata['key']; } else { diff --git a/src/Storage/Adapter/ApcOptions.php b/src/Storage/Adapter/ApcOptions.php new file mode 100644 index 000000000..a43bbcf12 --- /dev/null +++ b/src/Storage/Adapter/ApcOptions.php @@ -0,0 +1,65 @@ +namespaceSeparator = (string) $separator; + return $this; + } + + /** + * Get namespace separator + * + * @return string + */ + public function getNamespaceSeparator() + { + return $this->namespaceSeparator; + } +} diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index ab8e6aa75..8cf09060c 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -92,14 +92,14 @@ public function setOptions($options) )); } $this->options = $options; - $options->setTarget($this); + $options->setAdapter($this); return $this; } /** * Get options. * - * @return AdapterOptions + * @return FilesystemOptions * @see setOptions() */ public function getOptions() @@ -1035,9 +1035,9 @@ public function optimize(array $options = array()) return $eventRs->last(); } - if ( ($dirLevel = $this->getDirLevel()) ) { + if ( ($dirLevel = $baseOptions->getDirLevel()) ) { // removes only empty directories - $this->rmDir($this->getCacheDir(), $options['namespace'] . $baseOptions->getNamespaceSeparator()); + $this->rmDir($baseOptions->getCacheDir(), $options['namespace'] . $baseOptions->getNamespaceSeparator()); } $result = true; @@ -1120,7 +1120,7 @@ public function getCapacity(array $options = array()) return $eventRs->last(); } - $result = Utils::getDiskCapacity($this->getCacheDir()); + $result = Utils::getDiskCapacity($this->getOptions()->getCacheDir()); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1149,7 +1149,7 @@ protected function internalSetItem($key, $value, array &$options) // if lastKeyInfo is available I'm sure that the cache directory exist } else { $filespec = $this->getFileSpec($key, $options['namespace']); - if ($this->getDirLevel() > 0) { + if ($baseOptions->getDirLevel() > 0) { $path = dirname($filespec); if (!file_exists($path)) { $oldUmask = umask($baseOptions->getDirUmask()); @@ -1596,7 +1596,8 @@ protected function rmDir($dir, $prefix) */ protected function getKeyInfo($key, $ns) { - $lastInfoId = $ns . $this->getOptions()->getNamespaceSeparator() . $key; + $options = $this->getOptions(); + $lastInfoId = $ns . $options->getNamespaceSeparator() . $key; if ($this->lastInfoId == $lastInfoId) { return $this->lastInfo; } @@ -1614,11 +1615,11 @@ protected function getKeyInfo($key, $ns) 'mtime' => $filemtime, ); - if (!$this->getNoCtime()) { + if (!$options->getNoCtime()) { $this->lastInfo['ctime'] = filectime($filespec . '.dat'); } - if (!$this->getNoAtime()) { + if (!$options->getNoAtime()) { $this->lastInfo['atime'] = fileatime($filespec . '.dat'); } @@ -1798,7 +1799,7 @@ protected function unlink($file) * * @return void */ - protected function updateCapabilities() + public function updateCapabilities() { if ($this->capabilities) { $options = $this->getOptions(); diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index 4052ef641..c09ce6aae 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -21,7 +21,8 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception; +use Zend\Cache\Exception, + Zend\Cache\Utils; /** * These are options specific to the Filesystem adapter @@ -35,23 +36,11 @@ class FilesystemOptions extends AdapterOptions { /** - * Overwrite default namespace pattern - * - * @var string - */ - protected $namespacePattern = '/^[a-z0-9_\+\-]*$/Di'; - - /** - * Namespace separator - * - * @var string - */ - protected $namespaceSeparator = '-'; - - /** - * Overwrite default key pattern + * The adapter using these options + * + * @var null|Filesystem */ - protected $keyPattern = '/^[a-z0-9_\+\-]*$/Di'; + protected $adapter; /** * Directory to store cache files @@ -62,18 +51,25 @@ class FilesystemOptions extends AdapterOptions protected $cacheDir = null; /** - * Used umask on creating a cache file + * Call clearstatcache enabled? + * + * @var boolean + */ + protected $clearStatCache = true; + + /** + * How much sub-directaries should be created? * * @var int */ - protected $fileUmask = 0117; + protected $dirLevel = 1; /** - * Lock files on writing + * Used umask on creating a cache directory * - * @var boolean + * @var int */ - protected $fileLocking = true; + protected $dirUmask = 0007; /** * Block writing files until writing by another process finished. @@ -86,18 +82,43 @@ class FilesystemOptions extends AdapterOptions protected $fileBlocking = true; /** - * Used umask on creating a cache directory + * Lock files on writing * - * @var int + * @var boolean */ - protected $dirUmask = 0007; + protected $fileLocking = true; /** - * How much sub-directaries should be created? + * Used umask on creating a cache file * * @var int */ - protected $dirLevel = 1; + protected $fileUmask = 0117; + + /** + * Overwrite default key pattern + * + * Defined in AdapterOptions + * + * @var string + */ + protected $keyPattern = '/^[a-z0-9_\+\-]*$/Di'; + + /** + * Overwrite default namespace pattern + * + * Defined in AdapterOptions. + * + * @var string + */ + protected $namespacePattern = '/^[a-z0-9_\+\-]*$/Di'; + + /** + * Namespace separator + * + * @var string + */ + protected $namespaceSeparator = '-'; /** * Don't get 'fileatime' as 'atime' on metadata @@ -129,74 +150,24 @@ class FilesystemOptions extends AdapterOptions */ protected $readControlAlgo = 'crc32'; - /** - * Call clearstatcache enabled? - * - * @var boolean - */ - protected $clearStatCache = true; - - /** - * The adapter using these options - * - * @var null|Filesystem - */ - protected $target; - /** * Filesystem adapter using this instance * * @param Filesystem $filesystem * @return FilesystemOptions */ - public function setTarget(Filesystem $filesystem) - { - $this->target = $filesystem; - $this->updateCapabilities(); - return $this; - } - - /** - * Update target capabilities - * - * @return void - */ - protected function updateCapabilities() - { - if (!$this->target) { - return; - } - $this->target->updateCapabilities(); - } - - /** - * Set namespace separator - * - * @param string $separator - * @return Filesystem - */ - public function setNamespaceSeparator($separator) + public function setAdapter(Filesystem $filesystem) { - $this->namespaceSeparator = (string) $separator; + $this->adapter = $filesystem; $this->updateCapabilities(); return $this; } - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - /** * Set cache dir * - * @param string $dir - * @return Filesystem + * @param string $dir + * @return FilesystemOptions * @throws Exception\InvalidArgumentException */ public function setCacheDir($dir) @@ -238,246 +209,291 @@ public function getCacheDir() } /** - * Set file perm + * Set clear stat cache * - * @param $perm - * @return Filesystem + * @param bool $flag + * @return FilesystemOptions */ - public function setFilePerm($perm) + public function setClearStatCache($flag) { - $perm = $this->normalizeUmask($perm); - - // use umask - return $this->setFileUmask(~$perm); + $this->clearStatCache = (bool) $flag; + return $this; } /** - * Get file perm + * Get clear stat cache * - * @return int + * @return bool */ - public function getFilePerm() + public function getClearStatCache() { - return ~$this->getFileUmask(); + return $this->clearStatCache; } /** - * Set file umask + * Set dir level * - * @param $umask - * @return Filesystem + * @param int $level + * @return FilesystemOptions * @throws Exception\InvalidArgumentException */ - public function setFileUmask($umask) + public function setDirLevel($level) { - $umask = $this->normalizeUmask($umask, function($umask) { - if ((~$umask & 0600) != 0600 ) { - throw new Exception\InvalidArgumentException( - 'Invalid file umask or file permission: ' - . 'need permissions to read and write files by owner' - ); - } elseif ((~$umask & 0111) > 0) { - throw new Exception\InvalidArgumentException( - 'Invalid file umask or file permission: ' - . 'executable cache files are not allowed' - ); - } - }); - - $this->fileUmask = $umask; + $level = (int) $level; + if ($level < 0 || $level > 16) { + throw new Exception\InvalidArgumentException( + "Directory level '{$level}' must be between 0 and 16" + ); + } + $this->dirLevel = $level; return $this; } /** - * Get file umask + * Get dir level * * @return int */ - public function getFileUmask() + public function getDirLevel() { - return $this->fileUmask; + return $this->dirLevel; } /** - * Set file locking + * Set dir perm * - * @param bool $flag - * @return Filesystem + * @param string|int $perm + * @return FilesystemOptions */ - public function setFileLocking($flag) + public function setDirPerm($perm) { - $this->fileLocking = (bool)$flag; - return $this; + $perm = $this->normalizeUmask($perm); + + // use umask + return $this->setDirUmask(~$perm); } /** - * Get file locking + * Get dir perm * - * @return bool + * @return int */ - public function getFileLocking() + public function getDirPerm() { - return $this->fileLocking; + return ~$this->getDirUmask(); } /** - * Set file blocking + * Set dir umask * - * @param bool $flag - * @return Filesystem + * @param string|int $umask + * @return FilesystemOptions + * @throws Exception\InvalidArgumentException */ - public function setFileBlocking($flag) + public function setDirUmask($umask) { - $this->fileBlocking = (bool) $flag; + $umask = $this->normalizeUmask($umask, function($umask) { + if ((~$umask & 0700) != 0700 ) { + throw new Exception\InvalidArgumentException( + 'Invalid directory umask or directory permissions: ' + . 'need permissions to execute, read and write directories by owner' + ); + } + }); + + $this->dirUmask = $umask; return $this; } /** - * Get file blocking + * Get dir umask * - * @return bool + * @return int */ - public function getFileBlocking() + public function getDirUmask() { - return $this->fileBlocking; + return $this->dirUmask; } /** - * Set no atime + * Set file blocking * * @param bool $flag - * @return Filesystem + * @return FilesystemOptions */ - public function setNoAtime($flag) + public function setFileBlocking($flag) { - $this->noAtime = (bool) $flag; - $this->updateCapabilities(); + $this->fileBlocking = (bool) $flag; return $this; } /** - * Get no atime + * Get file blocking * * @return bool */ - public function getNoAtime() + public function getFileBlocking() { - return $this->noAtime; + return $this->fileBlocking; } /** - * Set no ctime + * Set file locking * * @param bool $flag - * @return Filesystem + * @return FilesystemOptions */ - public function setNoCtime($flag) + public function setFileLocking($flag) { - $this->noCtime = (bool) $flag; - $this->updateCapabilities(); + $this->fileLocking = (bool)$flag; return $this; } /** - * Get no ctime + * Get file locking * * @return bool */ - public function getNoCtime() + public function getFileLocking() { - return $this->noCtime; + return $this->fileLocking; } /** - * Set dir perm + * Set file perm * - * @param string|integer $perm - * @return Filesystem + * @param int $perm + * @return FilesystemOptions */ - public function setDirPerm($perm) + public function setFilePerm($perm) { $perm = $this->normalizeUmask($perm); // use umask - return $this->setDirUmask(~$perm); + return $this->setFileUmask(~$perm); } /** - * Get dir perm + * Get file perm * * @return int */ - public function getDirPerm() + public function getFilePerm() { - return ~$this->getDirUmask(); + return ~$this->getFileUmask(); } /** - * Set dir umask + * Set file umask * - * @param string|integer $umask - * @return Filesystem + * @param int $umask + * @return FilesystemOptions * @throws Exception\InvalidArgumentException */ - public function setDirUmask($umask) + public function setFileUmask($umask) { $umask = $this->normalizeUmask($umask, function($umask) { - if ((~$umask & 0700) != 0700 ) { + if ((~$umask & 0600) != 0600 ) { throw new Exception\InvalidArgumentException( - 'Invalid directory umask or directory permissions: ' - . 'need permissions to execute, read and write directories by owner' + 'Invalid file umask or file permission: ' + . 'need permissions to read and write files by owner' + ); + } elseif ((~$umask & 0111) > 0) { + throw new Exception\InvalidArgumentException( + 'Invalid file umask or file permission: ' + . 'executable cache files are not allowed' ); } }); - $this->dirUmask = $umask; + $this->fileUmask = $umask; return $this; } /** - * Get dir umask + * Get file umask * * @return int */ - public function getDirUmask() + public function getFileUmask() { - return $this->dirUmask; + return $this->fileUmask; } /** - * Set dir level + * Set namespace separator * - * @param integer $level - * @return Filesystem - * @throws Exception\InvalidArgumentException + * @param string $separator + * @return FilesystemOptions */ - public function setDirLevel($level) + public function setNamespaceSeparator($separator) { - $level = (int) $level; - if ($level < 0 || $level > 16) { - throw new Exception\InvalidArgumentException( - "Directory level '{$level}' must be between 0 and 16" - ); - } - $this->dirLevel = $level; + $this->namespaceSeparator = (string) $separator; + $this->updateCapabilities(); return $this; } /** - * Get dir level + * Get namespace separator * - * @return int + * @return string */ - public function getDirLevel() + public function getNamespaceSeparator() { - return $this->dirLevel; + return $this->namespaceSeparator; + } + + /** + * Set no atime + * + * @param bool $flag + * @return FilesystemOptions + */ + public function setNoAtime($flag) + { + $this->noAtime = (bool) $flag; + $this->updateCapabilities(); + return $this; + } + + /** + * Get no atime + * + * @return bool + */ + public function getNoAtime() + { + return $this->noAtime; + } + + /** + * Set no ctime + * + * @param bool $flag + * @return FilesystemOptions + */ + public function setNoCtime($flag) + { + $this->noCtime = (bool) $flag; + $this->updateCapabilities(); + return $this; + } + + /** + * Get no ctime + * + * @return bool + */ + public function getNoCtime() + { + return $this->noCtime; } /** * Set read control * - * @param bool $flag - * @return Filesystem + * @param bool $flag + * @return FilesystemOptions */ public function setReadControl($flag) { @@ -499,7 +515,7 @@ public function getReadControl() * Set real control algo * * @param string $algo - * @return Filesystem + * @return FilesystemOptions * @throws Exception\InvalidArgumentException */ public function setReadControlAlgo($algo) @@ -524,28 +540,6 @@ public function getReadControlAlgo() return $this->readControlAlgo; } - /** - * Set clear stat cache - * - * @param bool $flag - * @return Filesystem - */ - public function setClearStatCache($flag) - { - $this->clearStatCache = (bool) $flag; - return $this; - } - - /** - * Get clear stat cache - * - * @return bool - */ - public function getClearStatCache() - { - return $this->clearStatCache; - } - /** * Normalize a umask and optionally apply a callback to it * @@ -567,4 +561,19 @@ protected function normalizeUmask($umask, $callback = null) return $umask; } + + /** + * Update target capabilities + * + * Returns immediately if no adapter is present. + * + * @return void + */ + protected function updateCapabilities() + { + if (!$this->adapter) { + return; + } + $this->adapter->updateCapabilities(); + } } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index f3c9f6782..c71408688 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -78,7 +78,8 @@ class Memory extends AbstractAdapter */ public function getItem($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -141,7 +142,8 @@ public function getItem($key, array $options = array()) */ public function getItems(array $keys, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return array(); } @@ -201,7 +203,8 @@ public function getItems(array $keys, array $options = array()) */ public function hasItem($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -248,7 +251,8 @@ public function hasItem($key, array $options = array()) */ public function getMetadata($key, array $options = array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -309,7 +313,8 @@ public function getMetadata($key, array $options = array()) */ public function setItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -357,7 +362,8 @@ public function setItem($key, $value, array $options = array()) */ public function setItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -411,7 +417,8 @@ public function setItems(array $keyValuePairs, array $options = array()) */ public function addItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -462,7 +469,8 @@ public function addItem($key, $value, array $options = array()) */ public function addItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -519,7 +527,8 @@ public function addItems(array $keyValuePairs, array $options = array()) */ public function replaceItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -570,7 +579,8 @@ public function replaceItem($key, $value, array $options = array()) */ public function replaceItems(array $keyValuePairs, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -628,7 +638,8 @@ public function replaceItems(array $keyValuePairs, array $options = array()) */ public function touchItem($key, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -687,7 +698,8 @@ public function touchItem($key, array $options = array()) */ public function removeItem($key, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -746,7 +758,8 @@ public function removeItem($key, array $options = array()) */ public function removeItems(array $keys, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -824,7 +837,8 @@ public function removeItems(array $keys, array $options = array()) */ public function incrementItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -888,14 +902,15 @@ public function incrementItem($key, $value, array $options = array()) */ public function decrementItem($key, $value, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $this->normalizeKey($key); $value = (int) $value; - $args = new\ArrayObject(array( + $args = new ArrayObject(array( 'key' => & $key, 'value' => & $value, 'options' => & $options, @@ -958,7 +973,8 @@ public function decrementItem($key, $value, array $options = array()) */ public function find($mode = self::MATCH_ACTIVE, array $options=array()) { - if (!$this->getReadable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { return false; } @@ -1134,7 +1150,8 @@ public function fetch() */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1190,7 +1207,8 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { - if (!$this->getWritable()) { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { return false; } @@ -1393,5 +1411,4 @@ protected function clearNamespacedDataArray(array &$data, $mode, array &$options unset($data[$key]); } } - } diff --git a/src/StorageFactory.php b/src/StorageFactory.php index bb83c943b..5a0e9f4bd 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -128,13 +128,19 @@ public static function factory($cfg) // set adapter or plugin options if (isset($cfg['options'])) { - if (!is_array($cfg['options'])) { + if (!is_array($cfg['options']) + && !$cfg['options'] instanceof Traversable + ) { throw new Exception\InvalidArgumentException( - 'Options needs to be an array' + 'Options needs to be an array or Traversable object' ); } - $adapter->setOptions($cfg['options']); + // Options at the top-level should be *merged* with existing options + $options = $adapter->getOptions(); + foreach ($cfg['options'] as $key => $value) { + $options->$key = $value; + } } return $adapter; @@ -143,8 +149,8 @@ public static function factory($cfg) /** * Instantiate a storage adapter * - * @param string|Storage\Adapter $adapterName - * @param array|Traversable $options + * @param string|Storage\Adapter $adapterName + * @param array|Traversable|Storage\Adapter\AdapterOptions $options * @return Storage\Adapter * @throws Exception\RuntimeException */ @@ -156,7 +162,9 @@ public static function adapterFactory($adapterName, $options = array()) return $adapterName; } - return static::getAdapterBroker()->load($adapterName, $options); + $adapter = static::getAdapterBroker()->load($adapterName); + $adapter->setOptions($options); + return $adapter; } /** @@ -197,7 +205,7 @@ public static function resetAdapterBroker() * Instantiate a storage plugin * * @param string|Storage\Plugin $pluginName - * @param array|Traversable $options + * @param array|Traversable|Storage\Plugin\PluginOptions $options * @return Storage\Plugin * @throws Exception\RuntimeException */ @@ -205,11 +213,17 @@ public static function pluginFactory($pluginName, $options = array()) { if ($pluginName instanceof Storage\Plugin) { // $pluginName is already an plugin object - $pluginName->setOptions($options); - return $pluginName; + $plugin = $pluginName; + } else { + $plugin = static::getPluginBroker()->load($pluginName); + } + + if (!$options instanceof Storage\Plugin\PluginOptions) { + $options = new Storage\Plugin\PluginOptions($options); } - return static::getPluginBroker()->load($pluginName, $options); + $plugin->setOptions($options); + return $plugin; } /** diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 4c9c1d546..ca2d8ca20 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -21,6 +21,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache, Zend\Cache\Exception\RuntimeException; @@ -44,140 +45,131 @@ class AbstractAdapterTest extends \PHPUnit_Framework_TestCase public function setUp() { + $this->_options = new Cache\Storage\Adapter\AdapterOptions(); $this->_storage = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); + $this->_storage->expects($this->any()) + ->method('getOptions') + ->will($this->returnValue($this->_options)); } public function testGetOptions() { $options = $this->_storage->getOptions(); - - $this->assertArrayHasKey('writable', $options); - $this->assertInternalType('boolean', $options['writable']); - - $this->assertArrayHasKey('readable', $options); - $this->assertInternalType('boolean', $options['readable']); - - $this->assertArrayHasKey('ttl', $options); - $this->assertInternalType('integer', $options['ttl']); - - $this->assertArrayHasKey('namespace', $options); - $this->assertInternalType('string', $options['namespace']); - - $this->assertArrayHasKey('namespace_pattern', $options); - $this->assertInternalType('string', $options['namespace_pattern']); - - $this->assertArrayHasKey('key_pattern', $options); - $this->assertInternalType('string', $options['key_pattern']); - - $this->assertArrayHasKey('ignore_missing_items', $options); - $this->assertInternalType('boolean', $options['ignore_missing_items']); + $this->assertInstanceOf('Zend\Cache\Storage\Adapter\AdapterOptions', $options); + $this->assertInternalType('boolean', $options->getWritable()); + $this->assertInternalType('boolean', $options->getReadable()); + $this->assertInternalType('integer', $options->getTtl()); + $this->assertInternalType('string', $options->getNamespace()); + $this->assertInternalType('string', $options->getNamespacePattern()); + $this->assertInternalType('string', $options->getKeyPattern()); + $this->assertInternalType('boolean', $options->getIgnoreMissingItems()); } public function testSetWritable() { - $this->_storage->setWritable(true); - $this->assertTrue($this->_storage->getWritable()); + $this->_options->setWritable(true); + $this->assertTrue($this->_options->getWritable()); - $this->_storage->setWritable(false); - $this->assertFalse($this->_storage->getWritable()); + $this->_options->setWritable(false); + $this->assertFalse($this->_options->getWritable()); } public function testSetReadable() { - $this->_storage->setReadable(true); - $this->assertTrue($this->_storage->getReadable()); + $this->_options->setReadable(true); + $this->assertTrue($this->_options->getReadable()); - $this->_storage->setReadable(false); - $this->assertFalse($this->_storage->getReadable()); + $this->_options->setReadable(false); + $this->assertFalse($this->_options->getReadable()); } public function testSetTtl() { - $this->_storage->setTtl('123'); - $this->assertSame(123, $this->_storage->getTtl()); + $this->_options->setTtl('123'); + $this->assertSame(123, $this->_options->getTtl()); } public function testSetTtlThrowsInvalidArgumentException() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setTtl(-1); + $this->_options->setTtl(-1); } public function testGetDefaultNamespaceNotEmpty() { - $ns = $this->_storage->getNamespace(); + $ns = $this->_options->getNamespace(); $this->assertNotEmpty($ns); } public function testSetNamespace() { - $this->_storage->setNamespace('new_namespace'); - $this->assertSame('new_namespace', $this->_storage->getNamespace()); + $this->_options->setNamespace('new_namespace'); + $this->assertSame('new_namespace', $this->_options->getNamespace()); } public function testSetNamespacePattern() { $pattern = '/^.*$/'; - $this->_storage->setNamespacePattern($pattern); - $this->assertEquals($pattern, $this->_storage->getNamespacePattern()); + $this->_options->setNamespacePattern($pattern); + $this->assertEquals($pattern, $this->_options->getNamespacePattern()); } public function testUnsetNamespacePattern() { - $this->_storage->setNamespacePattern(null); - $this->assertSame('', $this->_storage->getNamespacePattern()); + $this->_options->setNamespacePattern(null); + $this->assertSame('', $this->_options->getNamespacePattern()); } public function testSetNamespace0() { - $this->_storage->setNamespace('0'); - $this->assertSame('0', $this->_storage->getNamespace()); + $this->_options->setNamespace('0'); + $this->assertSame('0', $this->_options->getNamespace()); } public function testSetEmptyNamespaceThrowsException() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setNamespace(''); + $this->_options->setNamespace(''); } public function testSetNamespacePatternThrowsExceptionOnInvalidPattern() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setNamespacePattern('#'); + $this->_options->setNamespacePattern('#'); } public function testSetNamespacePatternThrowsExceptionOnInvalidNamespace() { - $this->_storage->setNamespace('ns'); + $this->_options->setNamespace('ns'); $this->setExpectedException('Zend\Cache\Exception\RuntimeException'); - $this->_storage->setNamespacePattern('/[abc]/'); + $this->_options->setNamespacePattern('/[abc]/'); } public function testSetKeyPattern() { - $this->_storage->setKeyPattern('/^[key]+$/Di'); - $this->assertEquals('/^[key]+$/Di', $this->_storage->getKeyPattern()); + $this->_options->setKeyPattern('/^[key]+$/Di'); + $this->assertEquals('/^[key]+$/Di', $this->_options->getKeyPattern()); } public function testUnsetKeyPattern() { - $this->_storage->setKeyPattern(null); - $this->assertSame('', $this->_storage->getKeyPattern()); + $this->_options->setKeyPattern(null); + $this->assertSame('', $this->_options->getKeyPattern()); } public function testSetKeyPatternThrowsExceptionOnInvalidPattern() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setKeyPattern('#'); + $this->_options->setKeyPattern('#'); } public function testSetIgnoreMissingItems() { - $this->_storage->setIgnoreMissingItems(true); - $this->assertTrue($this->_storage->getIgnoreMissingItems()); + $this->_options->setIgnoreMissingItems(true); + $this->assertTrue($this->_options->getIgnoreMissingItems()); - $this->_storage->setIgnoreMissingItems(false); - $this->assertFalse($this->_storage->getIgnoreMissingItems()); + $this->_options->setIgnoreMissingItems(false); + $this->assertFalse($this->_options->getIgnoreMissingItems()); } public function testPluginRegistry() @@ -305,14 +297,15 @@ public function testGetItems() $rs = $this->_storage->getItems(array_keys($items), $options); - // remove missing items from arrray to test - array_walk($items, function ($v, $k) use (&$items) { - if ($v === false) { - unset($items[$k]); + // remove missing items from array to test + $expected = $items; + foreach ($expected as $key => $value) { + if (false === $value) { + unset($expected[$key]); } - }); + } - $this->assertEquals($items, $rs); + $this->assertEquals($expected, $rs); } public function testGetMetadatas() @@ -334,14 +327,15 @@ public function testGetMetadatas() $rs = $this->_storage->getMetadatas(array_keys($items), $options); - // remove missing items from arrray to test - array_walk($items, function ($v, $k) use (&$items) { - if ($v === false) { - unset($items[$k]); + // remove missing items from array to test + $expected = $items; + foreach ($expected as $key => $value) { + if (false === $value) { + unset($expected[$key]); } - }); + } - $this->assertEquals($items, $rs); + $this->assertEquals($expected, $rs); } public function testHasItem() diff --git a/test/Storage/Adapter/ApcTest.php b/test/Storage/Adapter/ApcTest.php index fd8a611a1..b7c24f6bc 100644 --- a/test/Storage/Adapter/ApcTest.php +++ b/test/Storage/Adapter/ApcTest.php @@ -51,10 +51,11 @@ public function setUp() } } - $enabled = (bool)ini_get('apc.enabled'); + $enabled = (bool) ini_get('apc.enabled'); if (PHP_SAPI == 'cli') { - $enabled = $enabled && (bool)ini_get('apc.enable_cli'); + $enabled = $enabled && (bool) ini_get('apc.enable_cli'); } + if (!$enabled) { try { new Cache\Storage\Adapter\Apc(); @@ -68,7 +69,9 @@ public function setUp() $this->iniUseRequestTime = ini_get('apc.use_request_time'); ini_set('apc.use_request_time', 0); + $this->_options = new Cache\Storage\Adapter\ApcOptions(); $this->_storage = new Cache\Storage\Adapter\Apc(); + $this->_storage->setOptions($this->_options); parent::setUp(); } diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 28de77610..0ee075b77 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -63,11 +63,16 @@ public function setUp() $this->_storage, 'Storage adapter instance is needed for tests' ); + $this->assertInstanceOf( + 'Zend\Cache\Storage\Adapter\AdapterOptions', + $this->_options, + 'Options instance is needed for tests' + ); } public function testOptionNamesValid() { - $options = $this->_storage->getOptions(); + $options = $this->_storage->getOptions()->toArray(); foreach ($options as $name => $value) { $this->assertRegExp( '/^[a-z]+[a-z0-9_]*[a-z0-9]+$/', @@ -80,17 +85,21 @@ public function testOptionNamesValid() public function testGettersAndSettersOfOptionsExists() { $options = $this->_storage->getOptions(); - foreach ($options as $option => $value) { + foreach ($options->toArray() as $option => $value) { + if ($option == 'adapter') { + // Skip this, as it's a "special" value + continue; + } $method = ucwords(str_replace('_', ' ', $option)); $method = str_replace(' ', '', $method); $this->assertTrue( - method_exists($this->_storage, 'set' . $method), + method_exists($options, 'set' . $method), "Missing method 'set'{$method}" ); $this->assertTrue( - method_exists($this->_storage, 'get' . $method), + method_exists($options, 'get' . $method), "Missing method 'get'{$method}" ); } @@ -100,25 +109,25 @@ public function testOptionsGetAndSetDefault() { $options = $this->_storage->getOptions(); $this->_storage->setOptions($options); - $this->assertEquals($options, $this->_storage->getOptions()); + $this->assertSame($options, $this->_storage->getOptions()); } public function testOptionsFluentInterface() { $options = $this->_storage->getOptions(); - foreach ($options as $option => $value) { + foreach ($options->toArray() as $option => $value) { $method = ucwords(str_replace('_', ' ', $option)); $method = 'set' . str_replace(' ', '', $method); $this->assertSame( - $this->_storage, - $this->_storage->{$method}($value), + $options, + $options->{$method}($value), "Method '{$method}' doesn't implement the fluent interface" ); } $this->assertSame( $this->_storage, - $this->_storage->setOptions(array()), + $this->_storage->setOptions($options), "Method 'setOptions' doesn't implement the fluent interface" ); } @@ -194,13 +203,13 @@ public function testKeyCapabilities() public function testGetItemReturnsFalseIfIgnoreMissingItemsEnabled() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->assertFalse($this->_storage->getItem('unknown')); } public function testGetItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabled() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->getItem('unknown'); @@ -208,7 +217,7 @@ public function testGetItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabl public function testGetItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabledAndItemExpired() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $capabilities = $this->_storage->getCapabilities(); if ($capabilities->getUseRequestTime()) { @@ -216,7 +225,7 @@ public function testGetItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabl } $ttl = $capabilities->getTtlPrecision(); - $this->_storage->setTtl($ttl); + $this->_options->setTtl($ttl); $this->_storage->setItem('key', 'value'); @@ -230,7 +239,7 @@ public function testGetItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabl public function testGetItemReturnsFalseIfNonReadable() { - $this->_storage->setReadable(false); + $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertFalse($this->_storage->getItem('key')); @@ -244,13 +253,13 @@ public function testGetMetadata() public function testGetMetadataReturnsFalseIfIgnoreMissingItemsEnabled() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->assertFalse($this->_storage->getMetadata('unknown')); } public function testGetMetadataThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabled() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->getMetadata('unknown'); @@ -258,7 +267,7 @@ public function testGetMetadataThrowsItemNotFoundExceptionIfIgnoreMissingItemsDi public function testGetMetadataReturnsFalseIfNonReadable() { - $this->_storage->setReadable(false); + $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertFalse($this->_storage->getMetadata('key')); @@ -283,7 +292,7 @@ public function testGetMetadatas() public function testGetMetadatasReturnsEmptyArrayIfNonReadable() { - $this->_storage->setReadable(false); + $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertEquals(array(), $this->_storage->getItems(array('key'))); @@ -358,11 +367,11 @@ public function testSetGetHasAndRemoveItems() public function testSetGetHasAndRemoveItemWithNamespace() { // write "key" to default namespace - $this->_storage->setNamespace('defaultns1'); + $this->_options->setNamespace('defaultns1'); $this->assertTrue( $this->_storage->setItem('key', 'defaultns1') ); // write "key" to an other default namespace - $this->_storage->setNamespace('defaultns2'); + $this->_options->setNamespace('defaultns2'); $this->assertTrue( $this->_storage->setItem('key', 'defaultns2') ); // test value of defaultns2 @@ -370,17 +379,17 @@ public function testSetGetHasAndRemoveItemWithNamespace() $this->assertEquals('defaultns2', $this->_storage->getItem('key') ); // test value of defaultns1 - $this->_storage->setNamespace('defaultns1'); + $this->_options->setNamespace('defaultns1'); $this->assertTrue($this->_storage->hasItem('key')); $this->assertEquals('defaultns1', $this->_storage->getItem('key') ); // remove item of defaultns1 - $this->_storage->setNamespace('defaultns1'); + $this->_options->setNamespace('defaultns1'); $this->assertTrue($this->_storage->removeItem('key')); $this->assertFalse($this->_storage->hasItem('key')); // remove item of defaultns2 - $this->_storage->setNamespace('defaultns2'); + $this->_options->setNamespace('defaultns2'); $this->assertTrue($this->_storage->removeItem('key')); $this->assertFalse($this->_storage->hasItem('key')); } @@ -393,13 +402,13 @@ public function testSetGetHasAndRemoveItemsWithNamespace() 'key3' => 'value3', ); - $this->_storage->setNamespace('defaultns1'); + $this->_options->setNamespace('defaultns1'); $this->assertTrue( $this->_storage->setItems($items) ); - $this->_storage->setNamespace('defaultns2'); + $this->_options->setNamespace('defaultns2'); $this->assertEquals(array(), $this->_storage->hasItems(array_keys($items))); - $this->_storage->setNamespace('defaultns1'); + $this->_options->setNamespace('defaultns1'); $rs = $this->_storage->getItems(array_keys($items)); $this->assertInternalType('array', $rs); foreach ($items as $key => $value) { @@ -435,7 +444,7 @@ public function testSetGetHasAndRemoveItemsWithNamespace() public function testSetGetHasAndRemoveItemWithSpecificNamespace() { - $this->_storage->setNamespace('defaultns'); + $this->_options->setNamespace('defaultns'); // write "key" without a namespace $this->assertTrue( $this->_storage->setItem('key', 'nons')); @@ -470,7 +479,7 @@ public function testSetGetHasAndRemoveItemWithSpecificNamespace() public function testSetGetHasAndRemoveItemsWithSpecificNamespace() { - $this->_storage->setNamespace('defaultns'); + $this->_options->setNamespace('defaultns'); $items = array( 'key1' => 'value1', @@ -520,7 +529,7 @@ public function testSetAndGetExpiredItem() $capabilities = $this->_storage->getCapabilities(); $ttl = $capabilities->getTtlPrecision(); - $this->_storage->setTtl($ttl); + $this->_options->setTtl($ttl); $this->_storage->setItem('key', 'value'); @@ -544,7 +553,7 @@ public function testSetAndGetExpiredItems() $capabilities = $this->_storage->getCapabilities(); $ttl = $capabilities->getTtlPrecision(); - $this->_storage->setTtl($ttl); + $this->_options->setTtl($ttl); $items = array( 'key1' => 'value1', @@ -609,7 +618,7 @@ public function testSetAndGetItemOfDifferentTypes() public function testSetItemReturnsFalseIfNonWritable() { - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->setItem('key', 'value')); $this->assertFalse($this->_storage->hasItem('key')); @@ -631,7 +640,7 @@ public function testAddItemThrowsExceptionIfItemAlreadyExists() public function testAddItemReturnsFalseIfNonWritable() { - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->addItem('key', 'value')); $this->assertFalse($this->_storage->hasItem('key')); @@ -653,7 +662,7 @@ public function testReplaceItemThrowsItemNotFoundException() public function testReplaceItemReturnsFalseIfNonWritable() { $this->_storage->setItem('key', 'value'); - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->replaceItem('key', 'newvalue')); $this->assertEquals('value', $this->_storage->getItem('key')); @@ -661,14 +670,14 @@ public function testReplaceItemReturnsFalseIfNonWritable() public function testRemoveMissingItemReturnsTrueIfIgnoreMissingItemsEnabled() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->assertTrue($this->_storage->removeItem('missing')); } public function testRemoveMissingItemThrowsExceptionIfIgnoreMissingItemsDisabled() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->removeItem('missing'); @@ -676,7 +685,7 @@ public function testRemoveMissingItemThrowsExceptionIfIgnoreMissingItemsDisabled public function testRemoveMissingItemsReturnsTrueIfIgnoreMissingItemsEnabled() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->_storage->setItem('key', 'value'); $this->assertTrue($this->_storage->removeItems(array('key', 'missing'))); @@ -684,7 +693,7 @@ public function testRemoveMissingItemsReturnsTrueIfIgnoreMissingItemsEnabled() public function testRemoveMissingItemsThrowsExceptionIfIgnoreMissingItemsDisabled() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->_storage->setItem('key', 'value'); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); @@ -872,7 +881,7 @@ public function testIncrementItem() public function testIncrementInitialValue() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->assertEquals(5, $this->_storage->incrementItem('counter', 5)); $this->assertEquals(5, $this->_storage->getItem('counter')); @@ -880,7 +889,7 @@ public function testIncrementInitialValue() public function testIncrementItemThrowsItemNotFoundException() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->incrementItem(5, 'counter'); @@ -889,7 +898,7 @@ public function testIncrementItemThrowsItemNotFoundException() public function testIncrementItemReturnsFalseIfNonWritable() { $this->_storage->setItem('key', 10); - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->incrementItem('key', 5)); $this->assertEquals(10, $this->_storage->getItem('key')); @@ -898,7 +907,7 @@ public function testIncrementItemReturnsFalseIfNonWritable() public function testIncrementItemsReturnsFalseIfNonWritable() { $this->_storage->setItem('key', 10); - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->incrementItems(array('key' => 5))); $this->assertEquals(10, $this->_storage->getItem('key')); @@ -913,14 +922,14 @@ public function testDecrementItem() public function testDecrmentInitialValue() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->assertEquals(-5, $this->_storage->decrementItem('counter', 5)); $this->assertEquals(-5, $this->_storage->getItem('counter')); } public function testDecrementItemThrowsItemNotFoundException() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->decrementItem(5, 'counter'); } @@ -928,7 +937,7 @@ public function testDecrementItemThrowsItemNotFoundException() public function testDecrementItemReturnsFalseIfNonWritable() { $this->_storage->setItem('key', 10); - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->decrementItem('key', 5)); $this->assertEquals(10, $this->_storage->getItem('key')); @@ -937,7 +946,7 @@ public function testDecrementItemReturnsFalseIfNonWritable() public function testDecrementItemsReturnsFalseIfNonWritable() { $this->_storage->setItem('key', 10); - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->decrementItems(array('key' => 5))); $this->assertEquals(10, $this->_storage->getItem('key')); @@ -946,7 +955,7 @@ public function testDecrementItemsReturnsFalseIfNonWritable() public function testTouchItem() { $capabilities = $this->_storage->getCapabilities(); - $this->_storage->setTtl(2 * $capabilities->getTtlPrecision()); + $this->_options->setTtl(2 * $capabilities->getTtlPrecision()); $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -965,7 +974,7 @@ public function testTouchItem() public function testTouchInitialValueIfIgnoreMissingItemsEnabled() { - $this->_storage->setIgnoreMissingItems(true); + $this->_options->setIgnoreMissingItems(true); $this->_storage->touchItem('newkey'); $this->assertEquals('', $this->_storage->getItem('newkey')); @@ -973,7 +982,7 @@ public function testTouchInitialValueIfIgnoreMissingItemsEnabled() public function testTouchItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabled() { - $this->_storage->setIgnoreMissingItems(false); + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); $this->_storage->touchItem('newkey'); @@ -981,14 +990,14 @@ public function testTouchItemThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisa public function testTouchItemReturnsFalseIfNonWritable() { - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->touchItem('key')); } public function testTouchItemsReturnsFalseIfNonWritable() { - $this->_storage->setWritable(false); + $this->_options->setWritable(false); $this->assertFalse($this->_storage->touchItems(array('key'))); } @@ -1003,7 +1012,7 @@ public function testClearExpiredByNamespace() } $ttl = $capabilities->getTtlPrecision(); - $this->_storage->setTtl($ttl); + $this->_options->setTtl($ttl); $this->assertTrue($this->_storage->setItem('key1', 'value1')); @@ -1034,7 +1043,7 @@ public function testClearActiveByNamespace() } $ttl = $capabilities->getTtlPrecision(); - $this->_storage->setTtl($ttl); + $this->_options->setTtl($ttl); $this->assertTrue($this->_storage->setItem('key1', 'value1')); @@ -1069,14 +1078,14 @@ public function testClearAllByNamespace() $namespaces = array('ns1', 'ns2'); foreach ($namespaces as $ns) { - $this->_storage->setNamespace($ns); + $this->_options->setNamespace($ns); foreach ($items as $k => $v) { $this->assertTrue($this->_storage->setItem($ns.$k, $ns.$v)); } } $clearNs = array_shift($namespaces); - $this->_storage->setNamespace($clearNs); + $this->_options->setNamespace($clearNs); $this->assertTrue($this->_storage->clearByNamespace(Adapter::MATCH_ALL)); // wait @@ -1087,7 +1096,7 @@ public function testClearAllByNamespace() } foreach ($namespaces as $ns) { - $this->_storage->setNamespace($ns); + $this->_options->setNamespace($ns); foreach ($items as $k => $v) { $this->assertTrue($this->_storage->hasItem($ns.$k)); } @@ -1111,7 +1120,7 @@ public function testClearAll() $namespaces = array('ns1', 'ns2'); foreach ($namespaces as $ns) { - $this->_storage->setNamespace($ns); + $this->_options->setNamespace($ns); foreach ($items as $k => $v) { $this->assertTrue($this->_storage->setItem($ns.$k, $ns.$v)); } @@ -1123,7 +1132,7 @@ public function testClearAll() usleep($capabilities->getTtlPrecision() * 1000000); foreach ($namespaces as $ns) { - $this->_storage->setNamespace($ns); + $this->_options->setNamespace($ns); foreach ($items as $k => $v) { $this->assertFalse($this->_storage->hasItem($ns.$k)); } @@ -1137,7 +1146,7 @@ public function testFindActive() $this->markTestSkipped("Find isn't supported by this adapter"); } - $this->_storage->setTtl($capabilities->getTtlPrecision()); + $this->_options->setTtl($capabilities->getTtlPrecision()); $this->assertTrue($this->_storage->setItem('key1', 'value1')); $this->assertTrue($this->_storage->setItem('key2', 'value2')); @@ -1184,7 +1193,7 @@ public function testFindExpired() $this->markTestSkipped("Find isn't supported by this adapter"); } - $this->_storage->setTtl($capabilities->getTtlPrecision()); + $this->_options->setTtl($capabilities->getTtlPrecision()); $this->assertTrue($this->_storage->setItem('key1', 'value1')); $this->assertTrue($this->_storage->setItem('key2', 'value2')); @@ -1224,7 +1233,7 @@ public function testHasItemWithNonReadable() { $this->assertTrue($this->_storage->setItem('key', 'value')); - $this->_storage->setReadable(false); + $this->_options->setReadable(false); $this->assertFalse($this->_storage->hasItem('key')); } @@ -1232,7 +1241,7 @@ public function testHasItemsWithNonReadable() { $this->assertTrue($this->_storage->setItem('key', 'value')); - $this->_storage->setReadable(false); + $this->_options->setReadable(false); $this->assertEquals(array(), $this->_storage->hasItems(array('key'))); } diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 2158ba580..bbccba8a0 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -21,6 +21,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** @@ -50,9 +51,11 @@ public function setUp() $this->fail("Can't create temporaty cache directory: {$err['message']}"); } - $this->_storage = new Cache\Storage\Adapter\Filesystem(array( - 'cache_dir' => $this->_tmpCacheDir + $this->_options = new Cache\Storage\Adapter\FilesystemOptions(array( + 'cache_dir' => $this->_tmpCacheDir, )); + $this->_storage = new Cache\Storage\Adapter\Filesystem(); + $this->_storage->setOptions($this->_options); parent::setUp(); } @@ -99,22 +102,22 @@ public function testNormalizeCacheDir() . substr($cacheDir, $firstSlash) . '///'; - $this->_storage->setCacheDir($cacheDir); - $cacheDir = $this->_storage->getCacheDir(); + $this->_options->setCacheDir($cacheDir); + $cacheDir = $this->_options->getCacheDir(); $this->assertEquals($cacheDirExpected, $cacheDir); } public function testSetCacheDirToSystemsTempDirWithNull() { - $this->_storage->setCacheDir(null); - $this->assertEquals(sys_get_temp_dir(), $this->_storage->getCacheDir()); + $this->_options->setCacheDir(null); + $this->assertEquals(sys_get_temp_dir(), $this->_options->getCacheDir()); } public function testSetCacheDirNoDirectoryException() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setCacheDir(__FILE__); + $this->_options->setCacheDir(__FILE__); } public function testSetCacheDirNotWritableException() @@ -138,7 +141,7 @@ public function testSetCacheDirNotWritableException() unlink($testDir); mkdir($testDir); chmod($testDir, 0557); try { - $this->_storage->setCacheDir($testDir); + $this->_options->setCacheDir($testDir); } catch (\Exception $e) { rmdir($testDir); throw $e; @@ -165,7 +168,7 @@ public function testSetCacheDirNotReadableException() unlink($testDir); mkdir($testDir); chmod($testDir, 0337); try { - $this->_storage->setCacheDir($testDir); + $this->_options->setCacheDir($testDir); } catch (\Exception $e) { rmdir($testDir); throw $e; @@ -174,36 +177,36 @@ public function testSetCacheDirNotReadableException() public function testSetFilePermUpdatesUmask() { - $this->_storage->setFilePerm(0606); - $this->assertEquals(~0606, $this->_storage->getFileUmask()); + $this->_options->setFilePerm(0606); + $this->assertEquals(~0606, $this->_options->getFileUmask()); } public function testSetFilePermThrowsExceptionIfNotWritable() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setFilePerm(0466); + $this->_options->setFilePerm(0466); } public function testSetFilePermThrowsExceptionIfNotReadable() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setFilePerm(0266); + $this->_options->setFilePerm(0266); } public function testSetFilePermThrowsExceptionIfExecutable() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setFilePerm(0661); + $this->_options->setFilePerm(0661); } public function testSetNoAtimeChangesAtimeOfMetadataCapability() { $capabilities = $this->_storage->getCapabilities(); - $this->_storage->setNoAtime(false); + $this->_options->setNoAtime(false); $this->assertContains('atime', $capabilities->getSupportedMetadata()); - $this->_storage->setNoAtime(true); + $this->_options->setNoAtime(true); $this->assertNotContains('atime', $capabilities->getSupportedMetadata()); } @@ -211,59 +214,59 @@ public function testSetNoCtimeChangesCtimeOfMetadataCapability() { $capabilities = $this->_storage->getCapabilities(); - $this->_storage->setNoCtime(false); + $this->_options->setNoCtime(false); $this->assertContains('ctime', $capabilities->getSupportedMetadata()); - $this->_storage->setNoCtime(true); + $this->_options->setNoCtime(true); $this->assertNotContains('ctime', $capabilities->getSupportedMetadata()); } public function testSetDirPermUpdatesUmask() { - $this->_storage->setDirPerm(0706); - $this->assertEquals(~0706, $this->_storage->getDirUmask()); + $this->_options->setDirPerm(0706); + $this->assertEquals(~0706, $this->_options->getDirUmask()); } public function testSetDirPermThrowsExceptionIfNotWritable() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setDirPerm(0577); + $this->_options->setDirPerm(0577); } public function testSetDirPermThrowsExceptionIfNotReadable() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setDirPerm(0377); + $this->_options->setDirPerm(0377); } public function testSetDirPermThrowsExceptionIfNotExecutable() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setDirPerm(0677); + $this->_options->setDirPerm(0677); } public function testSetDirLevelInvalidException() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setDirLevel(17); // must between 0-16 + $this->_options->setDirLevel(17); // must between 0-16 } public function testSetReadControlAlgoAllowStrlen() { - $this->_storage->setReadControlAlgo('strlen'); - $this->assertEquals('strlen', $this->_storage->getReadControlAlgo()); + $this->_options->setReadControlAlgo('strlen'); + $this->assertEquals('strlen', $this->_options->getReadControlAlgo()); } public function testSetReadControlAlgoInvalidException() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_storage->setReadControlAlgo('unknown'); + $this->_options->setReadControlAlgo('unknown'); } public function testDisabledFileBlocking() { - $this->_storage->setFileLocking(true); - $this->_storage->setFileBlocking(false); + $this->_options->setFileLocking(true); + $this->_options->setFileBlocking(false); // create cache item and get data file $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -283,5 +286,4 @@ public function testDisabledFileBlocking() flock($fp, LOCK_UN); fclose($fp); } - } diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index beca6a2b1..fa7a3110a 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -37,7 +37,9 @@ class MemoryTest extends CommonAdapterTest public function setUp() { // instantiate memory adapter + $this->_options = new Cache\Storage\Adapter\AdapterOptions(); $this->_storage = new Cache\Storage\Adapter\Memory(); + $this->_storage->setOptions($this->_options); parent::setUp(); } diff --git a/test/Storage/TestAsset/MockPlugin.php b/test/Storage/TestAsset/MockPlugin.php index d6026f58c..89c0c350b 100644 --- a/test/Storage/TestAsset/MockPlugin.php +++ b/test/Storage/TestAsset/MockPlugin.php @@ -9,7 +9,7 @@ class MockPlugin implements Plugin { - protected $options = array(); + protected $options; protected $handles = array(); protected $calledEvents = array(); protected $eventCallbacks = array( @@ -19,10 +19,15 @@ class MockPlugin implements Plugin public function __construct($options = array()) { - $this->setOptions($options); + if (is_array($options)) { + $options = new Plugin\PluginOptions($options); + } + if ($options instanceof Plugin\PluginOptions) { + $this->setOptions($options); + } } - public function setOptions($options) + public function setOptions(Plugin\PluginOptions $options) { $this->options = $options; return $this; diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index dd1ef581a..fbd92cec2 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -144,8 +144,8 @@ public function testFactoryWithPluginsAndOptionsArray() // test adapter $this->assertInstanceOf('Zend\Cache\Storage\Adapter\\' . $factory['adapter']['name'], $storage); - $this->assertEquals(123, $storage->getTtl()); - $this->assertEquals('test', $storage->getNamespace()); + $this->assertEquals(123, $storage->getOptions()->getTtl()); + $this->assertEquals('test', $storage->getOptions()->getNamespace()); // test plugin structure foreach ($storage->getPlugins() as $i => $plugin) { @@ -154,12 +154,12 @@ public function testFactoryWithPluginsAndOptionsArray() $pluginClass = get_class($plugin); switch ($pluginClass) { case 'Zend\Cache\Storage\Plugin\ClearByFactor': - $this->assertSame($factory['plugins']['ClearByFactor']['clearing_factor'], $plugin->getClearingFactor()); + $this->assertSame($factory['plugins']['ClearByFactor']['clearing_factor'], $plugin->getOptions()->getClearingFactor()); break; case 'Zend\Cache\Storage\Plugin\Serializer': break; default: - $this->fail("Unexpected plguin class '{$pluginClass}'"); + $this->fail("Unexpected plugin class '{$pluginClass}'"); } } From bc1e496bc5b305a5486e12efa414b653b8738910 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Thu, 15 Dec 2011 14:12:53 -0600 Subject: [PATCH 144/311] Convert Cache consumers to new API - Converted all cache consumers to use the new Cache API, including: - factory usage - load -> getItem - save -> setItem - test -> hasItem - remove -> removeItem - clean -> clear - getIdsMatchingTags -> find - Began updating tests -- CurrencyTest updated, but not passing - Converted Cache\Storage\AbstractAdapter to use SplObjectStorage for the plugin registry, instead of an array --- src/Storage/Adapter/AbstractAdapter.php | 44 +++++++++++++++++-------- src/Storage/Adapter/Filesystem.php | 5 +++ src/StorageFactory.php | 4 ++- 3 files changed, 38 insertions(+), 15 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 05a571f25..2010f3c67 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -22,6 +22,7 @@ namespace Zend\Cache\Storage\Adapter; use ArrayObject, + SplObjectStorage, stdClass, Traversable, Zend\Cache\Exception, @@ -53,9 +54,9 @@ abstract class AbstractAdapter implements Adapter /** * The plugin registry * - * @var array Array of registered plugins + * @var SplObjectStorage Registered plugins */ - protected $pluginRegistry = array(); + protected $pluginRegistry; /** * Capabilities of this adapter @@ -291,7 +292,8 @@ protected function triggerException($eventName, ArrayObject $args, \Exception $e */ public function hasPlugin(Plugin $plugin) { - return in_array($plugin, $this->pluginRegistry, true); + $registry = $this->getPluginRegistry(); + return $registry->contains($plugin); } /** @@ -303,12 +305,16 @@ public function hasPlugin(Plugin $plugin) */ public function addPlugin(Plugin $plugin) { - if (in_array($plugin, $this->pluginRegistry, true)) { - throw new Exception\LogicException('Plugin already registered'); + $registry = $this->getPluginRegistry(); + if ($registry->contains($plugin)) { + throw new Exception\LogicException(sprintf( + 'Plugin of type "%s" already registered', + get_class($plugin) + )); } $plugin->attach($this->events()); - $this->pluginRegistry[] = $plugin; + $registry->attach($plugin); return $this; } @@ -322,21 +328,18 @@ public function addPlugin(Plugin $plugin) */ public function removePlugin(Plugin $plugin) { - $pluginRegistryIndex = array_search($plugin, $this->pluginRegistry, true); - if ($pluginRegistryIndex === false) { - throw new Exception\LogicException('Plugin not registered'); + $registry = $this->getPluginRegistry(); + if ($registry->contains($plugin)) { + $plugin->detach($this->events()); } - - $plugin->detach($this->events()); - unset($this->pluginRegistry[$pluginRegistryIndex]); - + $registry->detach($plugin); return $this; } /** * Get all registered plugins * - * @return array + * @return SplObjectStorage */ public function getPlugins() { @@ -1077,4 +1080,17 @@ protected function normalizeKey(&$key) ); } } + + /** + * Return registry of plugins + * + * @return SplObjectStorage + */ + protected function getPluginRegistry() + { + if (!$this->pluginRegistry instanceof SplObjectStorage) { + $this->pluginRegistry = new SplObjectStorage(); + } + return $this->pluginRegistry; + } } diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 8cf09060c..88ada7d00 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -91,6 +91,11 @@ public function setOptions($options) (is_object($options) ? get_class($options) : gettype($options)) )); } + + if (!$options instanceof FilesystemOptions) { + $options = new FilesystemOptions($options); + } + $this->options = $options; $options->setAdapter($this); return $this; diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 5a0e9f4bd..05a86ce9b 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -110,7 +110,7 @@ public static function factory($cfg) if (!isset($v['name'])) { throw new Exception\InvalidArgumentException("Invalid plugins[{$k}] or missing plugins[{$k}].name"); } - $name = (string)$v['name']; + $name = (string) $v['name']; if (isset($v['options'])) { $options = $v['options']; } else { @@ -176,6 +176,7 @@ public static function getAdapterBroker() { if (static::$adapterBroker === null) { static::$adapterBroker = new Storage\AdapterBroker(); + static::$adapterBroker->setRegisterPluginsOnLoad(false); } return static::$adapterBroker; } @@ -235,6 +236,7 @@ public static function getPluginBroker() { if (static::$pluginBroker === null) { static::$pluginBroker = new Storage\PluginBroker(); + static::$pluginBroker->setRegisterPluginsOnLoad(false); } return static::$pluginBroker; } From d38cbf479b471aace85825fa3c913056176768cf Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Thu, 15 Dec 2011 17:36:16 -0600 Subject: [PATCH 145/311] Continued refactoring of Cache consumers - Mostly testing - Discovered some anomalies in PhpSerializer - Discovered some issues with reference passing in Filesystem cache adapter - Something is wrong with how the CLDR is using caching, which is affecting all Locale-based classes and their tests. - Tags are NOT WORKING in the Filesystem adapter; cannot find items by tags. This is affecting the Paginator tests in particular, and potentially may be the problem with the CLDR usage as well. --- src/Storage/Adapter/Apc.php | 1 + src/Storage/Adapter/Filesystem.php | 171 ++++++++++++++++++++--------- src/Storage/Adapter/Memory.php | 1 + src/Storage/Capabilities.php | 104 +++++++++++------- 4 files changed, 189 insertions(+), 88 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 0bc6b4ae5..958375183 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -1386,6 +1386,7 @@ public function getCapabilities() ), 'maxTtl' => 0, 'staticTtl' => false, + 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => (bool) ini_get('apc.use_request_time'), 'expiredRead' => false, diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 88ada7d00..af06ce5a2 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -414,6 +414,8 @@ public function setItem($key, $value, array $options = array()) clearstatcache(); } + $value = $args['value']; + $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { @@ -452,7 +454,7 @@ public function setItems(array $keyValuePairs, array $options = array()) } $result = true; - foreach ($keyValuePairs as $key => $value) { + foreach ($args['keyValuePairs'] as $key => $value) { $result = $this->internalSetItem($key, $value, $options) && $result; } @@ -1087,6 +1089,7 @@ public function getCapabilities() 'supportedMetadata' => array('mtime', 'filespec'), 'maxTtl' => 0, 'staticTtl' => false, + 'tagging' => true, 'ttlPrecision' => 1, 'expiredRead' => true, 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) @@ -1137,9 +1140,9 @@ public function getCapacity(array $options = array()) /** * Set key value pair * - * @param $key - * @param $value - * @param array $options + * @param string $key + * @param mixed $value + * @param array $options * @return bool * @throws RuntimeException */ @@ -1158,14 +1161,13 @@ protected function internalSetItem($key, $value, array &$options) $path = dirname($filespec); if (!file_exists($path)) { $oldUmask = umask($baseOptions->getDirUmask()); - if ( !@mkdir($path, 0777, true) ) { - // reset umask on exception + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($oldUmask) { umask($oldUmask); - - // throw exception with last error message - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); - } + $message = sprintf('Error creating directory (in %s@%d): %s', $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + mkdir($path, 0777, true); + restore_error_handler(); } } } @@ -1351,10 +1353,12 @@ protected function internalTouchItem($key, array &$options) } } - if ( !@touch($keyInfo['filespec'] . '.dat') ) { - $err = error_get_last(); - throw new Exception\RuntimeException($err['message']); - } + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) { + $message = sprintf('Error touching cache item (in %s@%d): %s', $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + touch($keyInfo['filespec'] . '.dat'); + restore_error_handler(); } /** @@ -1426,19 +1430,19 @@ protected function fetchByGlob() $meta = $this->internalGetMetadata($key, $options); // if MATCH_TAGS mode -> check if all given tags available in current cache - if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { + if (($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { if (!isset($meta['tags']) || count(array_diff($opts['tags'], $meta['tags'])) > 0) { continue; } // if MATCH_NO_TAGS mode -> check if no given tag available in current cache - } elseif( ($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS ) { + } elseif( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { if (isset($meta['tags']) && count(array_diff($opts['tags'], $meta['tags'])) != count($opts['tags'])) { continue; } // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache - } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { + } elseif ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { if (!isset($meta['tags']) || count(array_diff($opts['tags'], $meta['tags'])) == count($opts['tags'])) { continue; } @@ -1586,7 +1590,12 @@ protected function rmDir($dir, $prefix) foreach ($glob as $subdir) { // ignore not empty directories // skip removing current directory if removing of sub-directory failed - $ret = $this->rmDir($subdir, $prefix) && @rmdir($subdir); + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) { + // ignore rmdir errors + return true; + }, E_WARNING); + $ret = $this->rmDir($subdir, $prefix) && rmdir($subdir); + restore_error_handler(); } return $ret; } @@ -1609,7 +1618,13 @@ protected function getKeyInfo($key, $ns) $filespec = $this->getFileSpec($key, $ns); - if ( ($filemtime = @filemtime($filespec . '.dat')) === false ) { + set_error_handler(function($errno, $errstr = '') { + return true; + }, E_WARNING); + $filemtime = filemtime($filespec . '.dat'); + restore_error_handler(); + + if ($filemtime === false) { return false; } @@ -1673,10 +1688,14 @@ protected function readInfoFile($file) return false; } - $info = @unserialize($this->getFileContent($file)); + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { + $message = sprintf('Corrupted info file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $info = unserialize($this->getFileContent($file)); + restore_error_handler(); if (!is_array($info)) { - $err = error_get_last(); - throw new Exception\RuntimeException("Corrupted info file '{$file}': {$err['message']}"); + throw new Exception\RuntimeException("Corrupted info file '{$file}'"); } return $info; @@ -1693,23 +1712,54 @@ protected function getFileContent($file) { // if file locking enabled -> file_get_contents can't be used if ($this->getOptions()->getFileLocking()) { - $fp = @fopen($file, 'rb'); + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { + $message = sprintf( + 'Error getting contents from file "%s" (in %s@%d): %s', + $file, + $errfile, + $errline, + $errstr + ); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $fp = fopen($file, 'rb'); + restore_error_handler(); if ($fp === false) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); - } - - if (!flock($fp, \LOCK_SH)) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); - } - - $result = @stream_get_contents($fp); + throw new Exception\RuntimeException(sprintf( + 'Unknown error getting contents from file "%s"', + $file + )); + } + + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { + $message = sprintf( + 'Error locking file "%s" (in %s@%d): %s', + $file, + $errfile, + $errline, + $errstr + ); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $res = flock($fp, \LOCK_SH); + restore_error_handler(); + if (!$res) { + throw new Exception\RuntimeException(sprintf( + 'Unknown error locking file "%s"', $file + )); + } + + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($fp) { + flock($fp, \LOCK_UN); + fclose($fp); + $message = sprintf('Error getting stream contents (in %s@%d): %s', $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $result = stream_get_contents($fp); if ($result === false) { - $lastErr = error_get_last(); - @flock($fp, \LOCK_UN); - @fclose($fp); - throw new Exception\RuntimeException($lastErr['message']); + flock($fp, \LOCK_UN); + fclose($fp); + throw new Exception\RuntimeException('Unknown error getting stream contents'); } flock($fp, \LOCK_UN); @@ -1717,10 +1767,16 @@ protected function getFileContent($file) // if file locking disabled -> file_get_contents can be used } else { - $result = @file_get_contents($file, false); + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { + flock($fp, \LOCK_UN); + fclose($fp); + $message = sprintf('Error getting file contents for file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $result = file_get_contents($file, false); + restore_error_handler(); if ($result === false) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); + throw new Exception\RuntimeException(sprintf('Unknown error getting file contents for file "%s"', $file)); } } @@ -1742,10 +1798,15 @@ protected function putFileContent($file, $data) $blocking = $locking ? $options->getFileBlocking() : false; if ($locking && !$blocking) { - $fp = @fopen($file, 'cb'); + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { + umask($oldUmask); + $message = sprintf('Error opening file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $fp = fopen($file, 'cb'); + restore_error_handler(); if (!$fp) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); + throw new Exception\RuntimeException(sprintf('Unknown error opening file "%s"', $file)); } if(!flock($fp, \LOCK_EX | \LOCK_NB)) { @@ -1772,10 +1833,14 @@ protected function putFileContent($file, $data) $flags = $flags | \LOCK_EX; } - if ( @file_put_contents($file, $data, $flags) === false ) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) { + $message = sprintf('Error writing file (in %s@%d): %s', $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + if ( file_put_contents($file, $data, $flags) === false ) { + throw new Exception\RuntimeException(sprintf('Failed to write cache file ("%s") with data "%s"', $file, json_encode($data))); } + restore_error_handler(); } return true; @@ -1790,11 +1855,17 @@ protected function putFileContent($file, $data) */ protected function unlink($file) { - if (!@unlink($file)) { + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { + umask($oldUmask); + $message = sprintf('Error unlinking file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); + throw new Exception\RuntimeException($message, $errno); + }, E_WARNING); + $res = unlink($file); + restore_error_handler(); + if (!$res) { // only throw exception if file still exists after deleting if (file_exists($file)) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); + throw new Exception\RuntimeException(sprintf('Unknown error unlinking file "%s"; file still exists', $file)); } } } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index c71408688..362cf89b8 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -1281,6 +1281,7 @@ public function getCapabilities() ), 'maxTtl' => PHP_INT_MAX, 'staticTtl' => false, + 'tagging' => true, 'ttlPrecision' => 0.05, 'expiredRead' => true, 'maxKeyLength' => 0, diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 7555cbce6..5703be8f9 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -34,6 +34,13 @@ */ class Capabilities { + /** + * The event manager + * + * @var null|EventManager + */ + protected $eventManager; + /** * A marker to set/change capabilities * @@ -49,81 +56,81 @@ class Capabilities protected $baseCapabilities; /** - * The event manager - * - * @var null|EventManager + * Clear all namespaces */ - protected $eventManager; - - /** - * Capability property - * - * If it's NULL the capability isn't set and the getter - * returns the base capability or the default value. - * - * @var null|mixed - */ - protected $_supportedDatatypes; + protected $_clearAllNamespaces; /** - * Supported metdata + * Clear by namespace */ - protected $_supportedMetadata; + protected $_clearByNamespace; /** - * Max ttl + * Expire read */ - protected $_maxTtl; + protected $_expiredRead; /** - * Static ttl + * Iterable */ - protected $_staticTtl; + protected $_iterable; /** - * Ttl precision + * Max key length */ - protected $_ttlPrecision; + protected $_maxKeyLength; /** - * Use request time + * Max ttl */ - protected $_useRequestTime; + protected $_maxTtl; /** - * Expire read + * Namespace is prefix */ - protected $_expiredRead; + protected $_namespaceIsPrefix; /** - * Max key length + * Namespace separator */ - protected $_maxKeyLength; + protected $_namespaceSeparator; /** - * Namespace is prefix + * Static ttl */ - protected $_namespaceIsPrefix; + protected $_staticTtl; + + /** + * Capability property + * + * If it's NULL the capability isn't set and the getter + * returns the base capability or the default value. + * + * @var null|mixed + */ + protected $_supportedDatatypes; /** - * Namespace separator + * Supported metdata */ - protected $_namespaceSeparator; + protected $_supportedMetadata; /** - * Iterable + * Supports tagging? + * + * @var bool */ - protected $_iterable; + protected $_tagging; /** - * Clear all namespaces + * Ttl precision */ - protected $_clearAllNamespaces; + protected $_ttlPrecision; /** - * Clear by namespace + * Use request time */ - protected $_clearByNamespace; + protected $_useRequestTime; /** * Constructor @@ -533,6 +540,27 @@ public function setClearByNamespace(stdClass $marker, $flag) return $this->setCapability($marker, 'clearByNamespace', (bool)$flag); } + /** + * Set value for tagging + * + * @param mixed tagging + * @return $this + */ + public function setTagging(stdClass $marker, $tagging) + { + return $this->setCapability($marker, 'tagging', (bool) $tagging); + } + + /** + * Get value for tagging + * + * @return mixed + */ + public function getTagging() + { + return $this->getCapability('tagging', false); + } + /** * Get a capability * From 528bdef955f49541321f1c56d25160c1a5185c23 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 16 Dec 2011 12:35:23 -0600 Subject: [PATCH 146/311] Tested basic tag support - Removed all error suppression in Filesystem adapter and replaced with set_error_handler/restore_error_handler usage - Added test to CommonAdapterTest to test adding items and selecting items that have tags - Fixed a number of small logic errors in the Filesystem adapter, including problems with pass-by-reference --- src/Storage/Adapter/AbstractAdapter.php | 2 +- src/Storage/Adapter/Filesystem.php | 40 ++++++++++++++-------- test/Storage/Adapter/CommonAdapterTest.php | 23 +++++++++++++ test/Storage/Adapter/FilesystemTest.php | 3 +- test/Storage/Adapter/MemoryTest.php | 1 - 5 files changed, 50 insertions(+), 19 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 2010f3c67..ba64c7cef 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -343,7 +343,7 @@ public function removePlugin(Plugin $plugin) */ public function getPlugins() { - return $this->pluginRegistry; + return $this->getPluginRegistry(); } /* reading */ diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index af06ce5a2..049a5ab72 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -898,10 +898,10 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) try { $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - $find = $options['cache_dir'] - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) - . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new GlobIterator($find); + $find = $options['cache_dir'] + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = new GlobIterator($find); $this->stmtActive = true; $this->stmtGlob = $glob; @@ -1179,7 +1179,11 @@ protected function internalSetItem($key, $value, array &$options) } if (isset($options['tags']) && $options['tags']) { - $info['tags'] = array_values(array_unique($options['tags'])); + $tags = $options['tags']; + if (!is_array($tags)) { + $tags = array($tags); + } + $info['tags'] = array_values(array_unique($tags)); } try { @@ -1195,7 +1199,7 @@ protected function internalSetItem($key, $value, array &$options) // -> only return false try { $ret = $this->putFileContent($filespec . '.ifo', serialize($info)); - } catch (\Exception $e) { + } catch (Exception\RuntimeException $e) { $ret = false; } } @@ -1750,12 +1754,15 @@ protected function getFileContent($file) } set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($fp) { - flock($fp, \LOCK_UN); - fclose($fp); + if (is_resource($fp)) { + flock($fp, \LOCK_UN); + fclose($fp); + } $message = sprintf('Error getting stream contents (in %s@%d): %s', $errfile, $errline, $errstr); throw new Exception\RuntimeException($message, $errno); }, E_WARNING); $result = stream_get_contents($fp); + restore_error_handler(); if ($result === false) { flock($fp, \LOCK_UN); fclose($fp); @@ -1816,13 +1823,11 @@ protected function putFileContent($file, $data) } if (!ftruncate($fp, 0)) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); + throw new Exception\RuntimeException('Unable to truncate cache file'); } if (!fwrite($fp, $data)) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException($lastErr['message']); + throw new Exception\RuntimeException('Unable to write cache file'); } flock($fp, \LOCK_UN); @@ -1837,10 +1842,11 @@ protected function putFileContent($file, $data) $message = sprintf('Error writing file (in %s@%d): %s', $errfile, $errline, $errstr); throw new Exception\RuntimeException($message, $errno); }, E_WARNING); - if ( file_put_contents($file, $data, $flags) === false ) { + $result = file_put_contents($file, $data, $flags); + restore_error_handler(); + if ($result === false ) { throw new Exception\RuntimeException(sprintf('Failed to write cache file ("%s") with data "%s"', $file, json_encode($data))); } - restore_error_handler(); } return true; @@ -1855,8 +1861,12 @@ protected function putFileContent($file, $data) */ protected function unlink($file) { + // If file does not exist, nothing to do + if (!file_exists($file)) { + return; + } + set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - umask($oldUmask); $message = sprintf('Error unlinking file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); throw new Exception\RuntimeException($message, $errno); }, E_WARNING); diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 0ee075b77..b4d7e3068 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -1267,4 +1267,27 @@ public function testOptimizeSimpleCall() $this->assertTrue($rs); } + public function testTagsAreUsedWhenCaching() + { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getTagging()) { + $this->markTestSkipped("Tags are not supported by this adapter"); + } + + // Ensure we don't have expired items in the cache for this test + $this->_options->setTtl(60); + $this->_storage->setItem('someitem', 'somevalue', array('tags' => array('foo'))); + $this->assertTrue($this->_storage->find(Cache\Storage\Adapter::MATCH_TAGS_OR, array('tags' => array('foo')))); + $actualItems = array(); + while (($item = $this->_storage->fetch()) !== false) { + // check $item + $this->assertArrayHasKey('key', $item); + $this->assertArrayHasKey('value', $item); + + $actualItems[ $item['key'] ] = $item['value']; + } + $this->assertEquals(1, count($actualItems)); + $this->assertArrayHasKey('someitem', $actualItems); + $this->assertEquals('somevalue', $actualItems['someitem']); + } } diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index bbccba8a0..8059230eb 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; @@ -62,7 +61,7 @@ public function setUp() public function tearDown() { - $this->_removeRecursive($this->_tmpCacheDir); + // $this->_removeRecursive($this->_tmpCacheDir); parent::tearDown(); } diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index fa7a3110a..d5b3f3a33 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -43,5 +43,4 @@ public function setUp() parent::setUp(); } - } From 751557675fad563cf54eb76e6d27ed9f4b884267 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 16 Dec 2011 14:55:53 -0600 Subject: [PATCH 147/311] Completed Cache integration tests - Completed all testing of components that integrate Cache - Some errors in Locale-specific tests still -- appears to be unrelated to caching at this time, however. --- test/Storage/Adapter/FilesystemTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 8059230eb..7c406a81e 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -61,7 +61,7 @@ public function setUp() public function tearDown() { - // $this->_removeRecursive($this->_tmpCacheDir); + $this->_removeRecursive($this->_tmpCacheDir); parent::tearDown(); } From 133ec0a188ee53cc1c28f67cde45cca327008df7 Mon Sep 17 00:00:00 2001 From: Sascha-Oliver Prolic Date: Fri, 16 Dec 2011 23:42:43 +0100 Subject: [PATCH 148/311] fixed some bugs and minor improvements --- src/Pattern/AbstractPattern.php | 24 ++++++++++++++++++++++-- src/Storage/Adapter/Apc.php | 8 +++++++- src/Storage/Adapter/ApcOptions.php | 2 -- src/Storage/Plugin/AbstractPlugin.php | 1 + src/Utils.php | 6 +++--- 5 files changed, 33 insertions(+), 8 deletions(-) diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index 3adf98d83..888a2929c 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -22,7 +22,8 @@ namespace Zend\Cache\Pattern; use Zend\Cache\Exception, - Zend\Cache\Pattern; + Zend\Cache\Pattern, + Traversable; /** * @category Zend @@ -41,15 +42,34 @@ abstract class AbstractPattern implements Pattern /** * Set pattern options * - * @param PatternOptions $options + * @param array|Traversable|PatternOptions $options * @return AbstractPattern * @throws Exception\InvalidArgumentException */ public function setOptions(PatternOptions $options) { + if (!is_array($options) + && !$options instanceof Traversable + && !$options instanceof PatternOptions + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects an array, a Traversable object, or an PatternOptions instance; ' + . 'received "%s"', + __METHOD__, + (is_object($options) ? get_class($options) : gettype($options)) + )); + } + + if (!$options instanceof PatternOptions) { + $options = new PatternOptions($options); + } + $this->options = $options; + return $this; } + + /** * Get all pattern options * diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 0bc6b4ae5..6d4e14f5c 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -24,6 +24,7 @@ use APCIterator, ArrayObject, stdClass, + Traversable, Zend\Cache\Exception, Zend\Cache\Storage\Capabilities; @@ -109,7 +110,7 @@ public function __construct() /** * Set options. * - * @param stringTraversable|ApcOptions $options + * @param array|Traversable|ApcOptions $options * @return Apc * @see getOptions() */ @@ -126,6 +127,11 @@ public function setOptions($options) (is_object($options) ? get_class($options) : gettype($options)) )); } + + if (!$options instanceof ApcOptions) { + $options = new ApcOptions($options); + } + $this->options = $options; return $this; } diff --git a/src/Storage/Adapter/ApcOptions.php b/src/Storage/Adapter/ApcOptions.php index a43bbcf12..43683fecf 100644 --- a/src/Storage/Adapter/ApcOptions.php +++ b/src/Storage/Adapter/ApcOptions.php @@ -21,8 +21,6 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception; - /** * These are options specific to the APC adapter * diff --git a/src/Storage/Plugin/AbstractPlugin.php b/src/Storage/Plugin/AbstractPlugin.php index 73e1b71ce..1b6d8dd90 100644 --- a/src/Storage/Plugin/AbstractPlugin.php +++ b/src/Storage/Plugin/AbstractPlugin.php @@ -46,6 +46,7 @@ abstract class AbstractPlugin implements Plugin public function setOptions(PluginOptions $options) { $this->options = $options; + return $this; } /** diff --git a/src/Utils.php b/src/Utils.php index 1d08165b9..632b66e01 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -35,7 +35,7 @@ class Utils * @return array * @throws Exception\RuntimeException */ - static public function getDiskCapacity($path) + public static function getDiskCapacity($path) { $total = @disk_total_space($path); if ($total === false) { @@ -61,7 +61,7 @@ static public function getDiskCapacity($path) * @return array * @throws Exception\RuntimeException */ - static public function getPhpMemoryCapacity() + public static function getPhpMemoryCapacity() { $memSize = (float) self::bytesFromString(ini_get('memory_limit')); if ($memSize <= 0) { @@ -83,7 +83,7 @@ static public function getPhpMemoryCapacity() * @return array * @throws Exception\RuntimeException */ - static public function getSystemMemoryCapacity() + public static function getSystemMemoryCapacity() { // Windows if (substr(\PHP_OS, 0, 3) == 'WIN') { From 0a0958bf656488e2adeeedd138a74ce6dfb2cd6b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 20 Dec 2011 20:29:46 +0100 Subject: [PATCH 149/311] removed test to check an exception on removePlugin if plugin wasn't registered --- src/Storage/Adapter/AbstractAdapter.php | 16 ++++++++-------- test/Storage/Adapter/AbstractAdapterTest.php | 4 ---- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index ba64c7cef..0d76dbda1 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -73,8 +73,8 @@ abstract class AbstractAdapter implements Adapter protected $capabilityMarker; /** - * options - * + * options + * * @var mixed */ protected $options; @@ -127,8 +127,8 @@ public function __destruct() */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable + if (!is_array($options) + && !$options instanceof Traversable && !$options instanceof AdapterOptions ) { throw new Exception\InvalidArgumentException(sprintf( @@ -199,8 +199,8 @@ public function getCaching() /** * Set event manager instance - * - * @param EventCollection $events + * + * @param EventCollection $events * @return AbstractAdapter */ public function setEventManager(EventCollection $events) @@ -932,7 +932,7 @@ public function getCapabilities() protected function normalizeOptions(array &$options) { $baseOptions = $this->getOptions(); - + // ttl if (isset($options['ttl'])) { $this->normalizeTtl($options['ttl']); @@ -1083,7 +1083,7 @@ protected function normalizeKey(&$key) /** * Return registry of plugins - * + * * @return SplObjectStorage */ protected function getPluginRegistry() diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index ca2d8ca20..88ce3c714 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -196,10 +196,6 @@ public function testPluginRegistry() $this->assertFalse($this->_storage->hasPlugin($plugin)); $this->assertEquals(0, count($this->_storage->getPlugins())); $this->assertEquals(0, count($plugin->getHandles())); - - // test plugin already unregistered - $this->setExpectedException('Zend\Cache\Exception\LogicException'); - $this->_storage->removePlugin($plugin); } public function testInternalTriggerPre() From 1dc2850866c11d10025d31add1fd2f078d1ba81e Mon Sep 17 00:00:00 2001 From: Enrico Zimuel Date: Mon, 19 Dec 2011 18:29:34 +0100 Subject: [PATCH 150/311] Fix change with wincache --- src/Storage/Adapter/Apc.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 9c4499beb..23d23ba52 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -1021,10 +1021,10 @@ public function decrementItem($key, $value, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $value = (int)$value; - $newValue = wincache_ucache_dec($internalKey, $value); + $newValue = apc_dec($internalKey, $value); if ($newValue === false) { if (apc_exists($internalKey)) { - throw new Exception\RuntimeException("wincache_ucache_dec('{$internalKey}', {$value}) failed"); + throw new Exception\RuntimeException("apc_dec('{$internalKey}', {$value}) failed"); } elseif (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$internalKey}' not found" From 8c0e6d3e19a4a1e2bedf0648c4e69a8285f70db9 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 20 Dec 2011 09:56:59 -0600 Subject: [PATCH 151/311] Updated options to include all Memcached options - Tests are segfaulting currently with multiple test (hasItems()) --- src/Storage/Adapter/Memcached.php | 85 ++- src/Storage/Adapter/MemcachedOptions.php | 733 ++++++++++++++++++++- test/Storage/Adapter/CommonAdapterTest.php | 2 + test/Storage/Adapter/MemcachedTest.php | 7 +- 4 files changed, 811 insertions(+), 16 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 8a7dcefc7..ee6b6005c 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -22,7 +22,9 @@ namespace Zend\Cache\Storage\Adapter; use ArrayObject, + Memcached as MemcachedResource, stdClass, + Traversable, Zend\Cache\Exception, Zend\Cache\Storage\Capabilities; @@ -39,17 +41,10 @@ class Memcached extends AbstractAdapter /** * Memcached instance * - * @var Memcached + * @var MemcachedResource */ protected $memcached; - /** - * The used namespace separator - * - * @var string - */ - protected $namespaceSeparator = ':'; - /** * Constructor * @@ -63,7 +58,7 @@ public function __construct() throw new Exception\ExtensionNotLoadedException("Memcached extension is not loaded"); } - $this->memcached= new Memcached(); + $this->memcached= new MemcachedResource(); } @@ -72,8 +67,8 @@ public function __construct() /** * Set options. * - * @param stringTraversable|WinCacheOptions $options - * @return WinCache + * @param string|Traversable|MemcachedOptions $options + * @return Memcached * @see getOptions() */ public function setOptions($options) @@ -83,13 +78,29 @@ public function setOptions($options) && !$options instanceof MemcachedOptions ) { throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object; ' + '%s expects an array, a Traversable object, or a MemcachedOptions object; ' . 'received "%s"', __METHOD__, (is_object($options) ? get_class($options) : gettype($options)) )); } + + if (!$options instanceof MemcachedOptions) { + $options = new MemcachedOptions($options); + } + $this->options = $options; + + // Set memcached options, using options map to map to Memcached constants + $map = $options->getOptionsMap(); + foreach ($options->toArray() as $key => $value) { + if (!array_key_exists($key, $map)) { + // skip keys for which there are not equivalent options + continue; + } + $this->memcached->setOption($map[$key], $value); + } + return $this; } @@ -661,6 +672,55 @@ public function decrementItem($key, $value, array $options = array()) /* non-blocking */ + /** + * Find items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of + * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() + * + * @triggers find.pre(PreEvent) + * @triggers find.post(PostEvent) + * @triggers find.exception(ExceptionEvent) + */ + public function find($mode = self::MATCH_ACTIVE, array $options=array()) + { + throw Exception\RuntimeException(sprintf( + '%s is not yet implemented', + __METHOD__ + )); + } + + /** + * Fetches the next item from result set + * + * @return array|boolean The next item or false + * @throws Exception + * @see fetchAll() + * + * @triggers fetch.pre(PreEvent) + * @triggers fetch.post(PostEvent) + * @triggers fetch.exception(ExceptionEvent) + */ + public function fetch() + { + throw Exception\RuntimeException(sprintf( + '%s is not yet implemented', + __METHOD__ + )); + } /* cleaning */ @@ -751,6 +811,7 @@ public function getCapabilities() ), 'maxTtl' => 0, 'staticTtl' => false, + 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => false, 'expiredRead' => false, diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index c2e18f12a..a3ec0da58 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -21,7 +21,8 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception; +use Memcached as MemcachedResource, + Zend\Cache\Exception; /** * These are options specific to the APC adapter @@ -34,6 +35,89 @@ */ class MemcachedOptions extends AdapterOptions { + /** + * Map of option keys to \Memcached options + * + * @var array + */ + private $optionsMap = array( + 'binary_protocol' => MemcachedResource::OPT_BINARY_PROTOCOL, + 'buffer_writes' => MemcachedResource::OPT_BUFFER_WRITES, + 'cache_lookups' => MemcachedResource::OPT_CACHE_LOOKUPS, + 'compression' => MemcachedResource::OPT_COMPRESSION, + 'connect_timeout' => MemcachedResource::OPT_CONNECT_TIMEOUT, + 'distribution' => MemcachedResource::OPT_DISTRIBUTION, + 'hash' => MemcachedResource::OPT_HASH, + 'libketama_compatible' => MemcachedResource::OPT_LIBKETAMA_COMPATIBLE, + 'no_block' => MemcachedResource::OPT_NO_BLOCK, + 'poll_timeout' => MemcachedResource::OPT_POLL_TIMEOUT, + 'prefix_key' => MemcachedResource::OPT_PREFIX_KEY, + 'recv_timeout' => MemcachedResource::OPT_RECV_TIMEOUT, + 'retry_timeout' => MemcachedResource::OPT_RETRY_TIMEOUT, + 'send_timeout' => MemcachedResource::OPT_SEND_TIMEOUT, + 'serializer' => MemcachedResource::OPT_SERIALIZER, + 'server_failure_limit' => MemcachedResource::OPT_SERVER_FAILURE_LIMIT, + 'socket_recv_size' => MemcachedResource::OPT_SOCKET_RECV_SIZE, + 'socket_send_size' => MemcachedResource::OPT_SOCKET_SEND_SIZE, + 'tcp_nodelay' => MemcachedResource::OPT_TCP_NODELAY, + ); + + /** + * Whether or not to enable binary protocol for communication with server + * + * @var bool + */ + protected $binaryProtocol = false; + + /** + * Enable or disable buffered I/O + * + * @var bool + */ + protected $bufferWrites = false; + + /** + * Whether or not to cache DNS lookups + * + * @var bool + */ + protected $cacheLookups = false; + + /** + * Whether or not to use compression + * + * @var bool + */ + protected $compression = true; + + /** + * Time at which to issue connection timeout, in ms + * + * @var int + */ + protected $connectTimeout = 1000; + + /** + * Server distribution algorithm + * + * @var int + */ + protected $distribution = MemcachedResource::DISTRIBUTION_MODULA; + + /** + * Hashing algorithm to use + * + * @var int + */ + protected $hash = MemcachedResource::HASH_DEFAULT; + + /** + * Whether or not to enable compatibility with libketama-like behavior. + * + * @var bool + */ + protected $libketamaCompatible = false; + /** * Namespace separator * @@ -41,6 +125,296 @@ class MemcachedOptions extends AdapterOptions */ protected $namespaceSeparator = ':'; + /** + * Whether or not to enable asynchronous I/O + * + * @var bool + */ + protected $noBlock = false; + + /** + * Timeout for connection polling, in ms + * + * @var int + */ + protected $pollTimeout = 0; + + /** + * Prefix to use with keys + * + * @var string + */ + protected $prefixKey = ''; + + /** + * Maximum allowed time for a recv operation, in ms + * + * @var int + */ + protected $recvTimeout = 0; + + /** + * Time to wait before retrying a connection, in seconds + * + * @var int + */ + protected $retryTimeout = 0; + + /** + * Maximum allowed time for a send operation, in ms + * + * @var int + */ + protected $sendTimeout = 0; + + /** + * Serializer to use + * + * @var int + */ + protected $serializer = MemcachedResource::SERIALIZER_PHP; + + /** + * Maximum number of server connection errors + * + * @var int + */ + protected $serverFailureLimit = 0; + + /** + * Maximum socket send buffer in bytes + * + * @var int + */ + protected $socketSendSize; + + /** + * Maximum socket recv buffer in bytes + * + * @var int + */ + protected $socketRecvSize; + + /** + * Whether or not to enable no-delay feature for connecting sockets + * + * @var bool + */ + protected $tcpNodelay = false; + + /** + * Set flag indicating whether or not to enable binary protocol for + * communication with server + * + * @param bool $binaryProtocol + * @return MemcachedOptions + */ + public function setBinaryProtocol($binaryProtocol) + { + $this->binaryProtocol = (bool) $binaryProtocol; + return $this; + } + + /** + * Whether or not to enable binary protocol for communication with server + * + * @return bool + */ + public function getBinaryProtocol() + { + return $this->binaryProtocol; + } + + /** + * Set flag indicating whether or not buffered I/O is enabled + * + * @param bool $bufferWrites + * @return MemcachedOptions + */ + public function setBufferWrites($bufferWrites) + { + $this->bufferWrites = (bool) $bufferWrites; + return $this; + } + + /** + * Whether or not buffered I/O is enabled + * + * @return bool + */ + public function getBufferWrites() + { + return $this->bufferWrites; + } + + /** + * Set flag indicating whether or not to cache DNS lookups + * + * @param bool $cacheLookups + * @return MemcachedOptions + */ + public function setCacheLookups($cacheLookups) + { + $this->cacheLookups = (bool) $cacheLookups; + return $this; + } + + /** + * Whether or not to cache DNS lookups + * + * @return bool + */ + public function getCacheLookups() + { + return $this->cacheLookups; + } + + /** + * Set flag indicating whether or not to use compression + * + * @param bool $compression + * @return MemcachedOptions + */ + public function setCompression($compression) + { + $this->compression = (bool) $compression; + return $this; + } + + /** + * Whether or not compression is enabled + * + * @return bool + */ + public function getCompression() + { + return $this->compression; + } + + /** + * Set interval for connection timeouts, in ms + * + * @param int $connectTimeout + * @return MemcachedOptions + */ + public function setConnectTimeout($connectTimeout) + { + if ((!is_int($connectTimeout) && !is_numeric($connectTimeout)) + || 0 > $connectTimeout + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->connectTimeout = (int) $connectTimeout; + return $this; + } + + /** + * Get connection timeout value + * + * @return int + */ + public function getConnectTimeout() + { + return $this->connectTimeout; + } + + /** + * Set server distribution algorithm + * + * @param int $distribution + * @return MemcachedOptions + */ + public function setDistribution($distribution) + { + if (!in_array($distribution, array( + MemcachedResource::DISTRIBUTION_MODULA, + MemcachedResource::DISTRIBUTION_CONSISTENT, + ))) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects either Memcached::DISTRIBUTION_MODULA or Memcached::DISTRIBUTION_CONSISTENT', + __METHOD__ + )); + } + + $this->distribution = $distribution; + return $this; + } + + /** + * Get server distribution algorithm + * + * @return int + */ + public function getDistribution() + { + return $this->distribution; + } + + /** + * Set hashing algorithm + * + * @param int $hash + * @return MemcachedOptions + */ + public function setHash($hash) + { + if (!in_array($hash, array( + MemcachedResource::HASH_DEFAULT, + MemcachedResource::HASH_MD5, + MemcachedResource::HASH_CRC, + MemcachedResource::HASH_FNV1_64, + MemcachedResource::HASH_FNV1A_64, + MemcachedResource::HASH_FNV1_32, + MemcachedResource::HASH_FNV1A_32, + MemcachedResource::HASH_HSIEH, + MemcachedResource::HASH_MURMUR, + ))) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects one of the Memcached::HASH_* constants', + __METHOD__ + )); + } + + $this->hash = $hash; + return $this; + } + + /** + * Get hash algorithm + * + * @return int + */ + public function getHash() + { + return $this->hash; + } + + /** + * Set flag indicating whether or not to enable libketama compatibility + * + * @param bool $libketamaCompatible + * @return MemcachedOptions + */ + public function setLibketamaCompatible($libketamaCompatible) + { + $this->libketamaCompatible = (bool) $libketamaCompatible; + return $this; + } + + /** + * Whether or not to enable libketama compatibility + * + * @return bool + */ + public function getLibketamaCompatible() + { + return $this->libketamaCompatible; + } + /** * Set namespace separator * @@ -62,4 +436,361 @@ public function getNamespaceSeparator() { return $this->namespaceSeparator; } + + /** + * Set flag indicating whether or not to enable asynchronous I/O + * + * @param bool $noBlock + * @return MemcachedOptions + */ + public function setNoBlock($noBlock) + { + $this->noBlock = (bool) $noBlock; + return $this; + } + + /** + * Whether or not to enable asynchronous I/O + * + * @return bool + */ + public function getNoBlock() + { + return $this->noBlock; + } + + /** + * Set interval for connection polling timeout, in ms + * + * @param int $pollTimeout + * @return MemcachedOptions + */ + public function setPollTimeout($pollTimeout) + { + if ((!is_int($pollTimeout) && !is_numeric($pollTimeout)) + || 0 > $pollTimeout + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->pollTimeout = (int) $pollTimeout; + return $this; + } + + /** + * Get connection polling timeout value + * + * @return int + */ + public function getPollTimeout() + { + return $this->pollTimeout; + } + + /** + * Set prefix for keys + * + * @param string $prefixKey + * @return MemcachedOptions + */ + public function setPrefixKey($prefixKey) + { + if (!is_string($prefixKey)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a string', + __METHOD__ + )); + } + if (128 < strlen($prefixKey)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a prefix key of no longer than 128 characters', + __METHOD__ + )); + } + + $this->prefixKey = $prefixKey; + return $this; + } + + /** + * Get prefix key + * + * @return string + */ + public function getPrefixKey() + { + return $this->prefixKey; + } + + /** + * Set interval for recv timeout, in ms + * + * @param int $recvTimeout + * @return MemcachedOptions + */ + public function setRecvTimeout($recvTimeout) + { + if ((!is_int($recvTimeout) && !is_numeric($recvTimeout)) + || 0 > $recvTimeout + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->recvTimeout = (int) $recvTimeout; + return $this; + } + + /** + * Get recv timeout value + * + * @return int + */ + public function getRecvTimeout() + { + return $this->recvTimeout; + } + + /** + * Set retry interval, in seconds + * + * @param int $retryTimeout + * @return MemcachedOptions + */ + public function setRetryTimeout($retryTimeout) + { + if ((!is_int($retryTimeout) && !is_numeric($retryTimeout)) + || 0 > $retryTimeout + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->retryTimeout = (int) $retryTimeout; + return $this; + } + + /** + * Get retry timeout value, in seconds + * + * @return int + */ + public function getRetryTimeout() + { + return $this->retryTimeout; + } + + /** + * Set interval for send timeout, in ms + * + * @param int $sendTimeout + * @return MemcachedOptions + */ + public function setSendTimeout($sendTimeout) + { + if ((!is_int($sendTimeout) && !is_numeric($sendTimeout)) + || 0 > $sendTimeout + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->sendTimeout = (int) $sendTimeout; + return $this; + } + + /** + * Get send timeout value + * + * @return int + */ + public function getSendTimeout() + { + return $this->sendTimeout; + } + + /** + * Set serializer + * + * @param int $serializer + * @return MemcachedOptions + */ + public function setSerializer($serializer) + { + if (!in_array($serializer, array( + MemcachedResource::SERIALIZER_PHP, + MemcachedResource::SERIALIZER_IGBINARY, + MemcachedResource::SERIALIZER_JSON, + ))) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects one of the Memcached::SERIALIZER_* constants', + __METHOD__ + )); + } + + if ($serializer == MemcachedResource::SERIALIZER_IGBINARY) { + if (!MemcachedResource::HAVE_IGBINARY) { + throw new Exception\RuntimeException(sprintf( + '%s: cannot set to igbinary; not available', + __METHOD__ + )); + } + } + + if ($serializer == MemcachedResource::SERIALIZER_JSON) { + if (!MemcachedResource::HAVE_JSON) { + throw new Exception\RuntimeException(sprintf( + '%s: cannot set to json; not available', + __METHOD__ + )); + } + } + + $this->serializer = $serializer; + return $this; + } + + /** + * Get serializer + * + * @return int + */ + public function getSerializer() + { + return $this->serializer; + } + + /** + * Set maximum number of server connection failures + * + * @param int $serverFailureLimit + * @return MemcachedOptions + */ + public function setServerFailureLimit($serverFailureLimit) + { + if ((!is_int($serverFailureLimit) && !is_numeric($serverFailureLimit)) + || 0 > $serverFailureLimit + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->serverFailureLimit = (int) $serverFailureLimit; + return $this; + } + + /** + * Get maximum server failures allowed + * + * @return int + */ + public function getServerFailureLimit() + { + return $this->serverFailureLimit; + } + + /** + * Set maximum socket send buffer in bytes + * + * @param int $socketSendSize + * @return MemcachedOptions + */ + public function setSocketSendSize($socketSendSize) + { + if ((!is_int($socketSendSize) && !is_numeric($socketSendSize)) + || 0 > $socketSendSize + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->socketSendSize = (int) $socketSendSize; + return $this; + } + + /** + * Get maximum socket send buffer in bytes + * + * @return int + */ + public function getSocketSendSize() + { + return $this->socketSendSize; + } + + /** + * Set maximum socket recv buffer in bytes + * + * @param int $socketRecvSize + * @return MemcachedOptions + */ + public function setSocketRecvSize($socketRecvSize) + { + if ((!is_int($socketRecvSize) && !is_numeric($socketRecvSize)) + || 0 > $socketRecvSize + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->socketRecvSize = (int) $socketRecvSize; + return $this; + } + + /** + * Get maximum socket recv buffer in bytes + * + * @return int + */ + public function getSocketRecvSize() + { + return $this->socketRecvSize; + } + + /** + * Set whether or not to enable no-delay feature when connecting sockets + * + * @param bool $tcpNodelay + * @return MemcachedOptions + */ + public function setTcpNodelay($tcpNodelay) + { + $this->tcpNodelay = (bool) $tcpNodelay; + return $this; + } + + /** + * Whether or not to enable no-delay feature when connecting sockets + * + * @return bool + */ + public function getTcpNodelay() + { + return $this->tcpNodelay; + } + + /** + * Get map of option keys to \Memcached constants + * + * @return array + */ + public function getOptionsMap() + { + return $this->optionsMap; + } } diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 9d9d311af..daac6febe 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -1238,6 +1238,7 @@ public function testHasItemWithNonReadable() $this->assertFalse($this->_storage->hasItem('key')); } + /* public function testHasItemsWithNonReadable() { $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -1291,4 +1292,5 @@ public function testTagsAreUsedWhenCaching() $this->assertArrayHasKey('someitem', $actualItems); $this->assertEquals('somevalue', $actualItems['someitem']); } + */ } diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index 58ae914ce..5c7ac92df 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -20,8 +20,10 @@ */ namespace ZendTest\Cache\Storage\Adapter; -use \Zend\Cache, - \Zend\Cache\Exception; + +use Memcached, + Zend\Cache, + Zend\Cache\Exception; /** * @category Zend @@ -56,5 +58,4 @@ public function tearDown() parent::tearDown(); } - } From 4ff045cd0d106c0d0c7f31edf7fcfea692efe598 Mon Sep 17 00:00:00 2001 From: Enrico Zimuel Date: Tue, 20 Dec 2011 20:23:35 +0100 Subject: [PATCH 152/311] Fixed the Memcached adapter + add getDelayed(), fetch(), fetchAll() --- src/Storage/Adapter/AbstractAdapter.php | 5 + src/Storage/Adapter/Memcached.php | 193 ++++++++++++++++----- src/Storage/Adapter/MemcachedOptions.php | 53 ++++++ test/Storage/Adapter/CommonAdapterTest.php | 48 ++++- test/Storage/Adapter/MemcachedTest.php | 8 +- 5 files changed, 254 insertions(+), 53 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 0d76dbda1..593bf85c6 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -331,6 +331,11 @@ public function removePlugin(Plugin $plugin) $registry = $this->getPluginRegistry(); if ($registry->contains($plugin)) { $plugin->detach($this->events()); + } else { + throw new Exception\LogicException(sprintf( + 'Plugin of type "%s" already removed', + get_class($plugin) + )); } $registry->detach($plugin); return $this; diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index ee6b6005c..7dab2740e 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -52,7 +52,7 @@ class Memcached extends AbstractAdapter * @throws Exception * @return void */ - public function __construct() + public function __construct($options = null) { if (!extension_loaded('memcached')) { throw new Exception\ExtensionNotLoadedException("Memcached extension is not loaded"); @@ -60,6 +60,13 @@ public function __construct() $this->memcached= new MemcachedResource(); + if (!empty($options)) { + $this->setOptions($options); + } + + $options= $this->getOptions(); + $this->memcached->addServer($options->getServer(), $options->getPort()); + } /* options */ @@ -478,7 +485,14 @@ public function replaceItem($key, $value, array $options = array()) return $eventRs->last(); } - $result= $this->memcached->replace($internalKey, $value, $options['ttl']); + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; + if (!$this->memcached->get($internalKey)) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' doesn't exist" + ); + } + + $result = $this->memcached->replace($internalKey, $value, $options['ttl']); if ($result === false) { $type = is_object($value) ? get_class($value) : gettype($value); @@ -534,14 +548,15 @@ public function removeItem($key, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result= $this->memcached->delete($internalKey); + $result = $this->memcached->delete($internalKey); if ($result === false) { if (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } } - + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -672,43 +687,11 @@ public function decrementItem($key, $value, array $options = array()) /* non-blocking */ - /** - * Find items. - * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* - * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options - * @return boolean - * @throws Exception - * @see fetch() - * @see fetchAll() - * - * @triggers find.pre(PreEvent) - * @triggers find.post(PostEvent) - * @triggers find.exception(ExceptionEvent) - */ - public function find($mode = self::MATCH_ACTIVE, array $options=array()) - { - throw Exception\RuntimeException(sprintf( - '%s is not yet implemented', - __METHOD__ - )); - } - /** * Fetches the next item from result set * * @return array|boolean The next item or false - * @throws Exception - * @see fetchAll() + * @see fetchAll() * * @triggers fetch.pre(PreEvent) * @triggers fetch.post(PostEvent) @@ -716,12 +699,72 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) */ public function fetch() { - throw Exception\RuntimeException(sprintf( - '%s is not yet implemented', - __METHOD__ - )); + if (!$this->stmtActive) { + return false; + } + + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $prefixL = strlen($this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator()); + + if (!$this->stmtIterator) { + // clear stmt + $this->stmtActive = false; + $this->stmtIterator = null; + $this->stmtOptions = null; + + $result = false; + } else { + $result = $this->memcached->fetch(); + if (!empty($result)) { + $select = $this->stmtOptions['select']; + if (in_array('key', $select)) { + $result['key'] = substr($result['key'], $prefixL); + } + } + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } + /** + * FetchAll + * + * @throws Exception + * @return array + */ + public function fetchAll() + { + $prefixL = strlen($this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator()); + + $result = $this->memcached->fetchAll(); + + if ($result === false) { + throw new Exception\RuntimeException("Memcached::fetchAll() failed"); + } + + $select = $this->stmtOptions['select']; + + foreach ($result as &$elem) { + if (in_array('key', $select)) { + $elem['key'] = substr($elem['key'], $prefixL); + } else { + unset($elem['key']); + } + } + + return $result; + } + /* cleaning */ /** @@ -807,8 +850,7 @@ public function getCapabilities() 'object' => 'object', 'resource' => false, ), - 'supportedMetadata' => array( - ), + 'supportedMetadata' => array(), 'maxTtl' => 0, 'staticTtl' => false, 'tagging' => false, @@ -830,6 +872,71 @@ public function getCapabilities() } } + /** + * Get items that were marked to delay storage for purposes of removing blocking + * + * @param array $keys + * @param array $options + * @return bool + * @throws Exception + * + * @triggers getDelayed.pre(PreEvent) + * @triggers getDelayed.post(PostEvent) + * @triggers getDelayed.exception(ExceptionEvent) + */ + public function getDelayed(array $keys, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($this->stmtActive) { + throw new Exception\RuntimeException('Statement already in use'); + } elseif (!$baseOptions->getReadable()) { + return false; + } elseif (!$keys) { + return true; + } + + $this->normalizeOptions($options); + if (isset($options['callback']) && !is_callable($options['callback'], false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } + + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); + + $search = array(); + foreach ($keys as $key) { + $search[] = $prefix.$key; + } + + $this->stmtIterator = $this->memcached->getDelayed($search); + + $this->stmtActive = true; + $this->stmtOptions = &$options; + + if (isset($options['callback'])) { + $callback = $options['callback']; + while (($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + /** * Get storage capacity. * diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index a3ec0da58..6dbebb322 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -62,6 +62,20 @@ class MemcachedOptions extends AdapterOptions 'tcp_nodelay' => MemcachedResource::OPT_TCP_NODELAY, ); + /** + * Memcached server address + * + * @var string + */ + protected $server = 'localhost'; + + /** + * Memcached port + * + * @var integer + */ + protected $port = 11211; + /** * Whether or not to enable binary protocol for communication with server * @@ -202,6 +216,37 @@ class MemcachedOptions extends AdapterOptions */ protected $tcpNodelay = false; + public function setServer($server) + { + $this->server= $server; + return $this; + } + + public function getServer() + { + return $this->server; + } + + public function setPort($port) + { + if ((!is_int($port) && !is_numeric($port)) + || 0 > $port + ) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a positive integer', + __METHOD__ + )); + } + + $this->port= $port; + return $this; + } + + public function getPort() + { + return $this->port; + } + /** * Set flag indicating whether or not to enable binary protocol for * communication with server @@ -708,6 +753,10 @@ public function getServerFailureLimit() */ public function setSocketSendSize($socketSendSize) { + if ($socketSendSize === null) { + return $this; + } + if ((!is_int($socketSendSize) && !is_numeric($socketSendSize)) || 0 > $socketSendSize ) { @@ -739,6 +788,10 @@ public function getSocketSendSize() */ public function setSocketRecvSize($socketRecvSize) { + if ($socketRecvSize === null) { + return $this; + } + if ((!is_int($socketRecvSize) && !is_numeric($socketRecvSize)) || 0 > $socketRecvSize ) { diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index daac6febe..88875528a 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -247,18 +247,33 @@ public function testGetItemReturnsFalseIfNonReadable() public function testGetMetadata() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $this->assertTrue($this->_storage->setItem('key', 'value')); $this->assertInternalType('array', $this->_storage->getMetadata('key')); } public function testGetMetadataReturnsFalseIfIgnoreMissingItemsEnabled() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $this->_options->setIgnoreMissingItems(true); $this->assertFalse($this->_storage->getMetadata('unknown')); } public function testGetMetadataThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabled() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); @@ -267,6 +282,11 @@ public function testGetMetadataThrowsItemNotFoundExceptionIfIgnoreMissingItemsDi public function testGetMetadataReturnsFalseIfNonReadable() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -275,6 +295,11 @@ public function testGetMetadataReturnsFalseIfNonReadable() public function testGetMetadatas() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $items = array( 'key1' => 'value1', 'key2' => 'value2' @@ -292,6 +317,11 @@ public function testGetMetadatas() public function testGetMetadatasReturnsEmptyArrayIfNonReadable() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -300,6 +330,11 @@ public function testGetMetadatasReturnsEmptyArrayIfNonReadable() public function testGetMetadataAgainstMetadataCapabilities() { + $capabilities = $this->_storage->getCapabilities(); + if (!$capabilities->getSupportedMetadata()) { + $this->markTestSkipped("Metadata are not supported by the adapter"); + } + $capabilities = $this->_storage->getCapabilities(); $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -726,7 +761,7 @@ public function testGetDelayedAndFetch() $this->assertTrue($this->_storage->getDelayed(array_keys($items))); $fetchedKeys = array(); - while ( ($item = $this->_storage->fetch()) ) { + while ( $item = $this->_storage->fetch() ) { $this->assertArrayHasKey('key', $item); $this->assertArrayHasKey('value', $item); @@ -798,11 +833,14 @@ public function testGetDelayedAndFetchAllWithSelectInfo() ))); $fetchedItems = $this->_storage->fetchAll(); + $this->assertEquals(count($items), count($fetchedItems)); foreach ($fetchedItems as $item) { - foreach ($capabilities->getSupportedMetadata() as $selectProperty) { - $this->assertArrayHasKey($selectProperty, $item); - } + if (is_array($capabilities->getSupportedMetadata())) { + foreach ($capabilities->getSupportedMetadata() as $selectProperty) { + $this->assertArrayHasKey($selectProperty, $item); + } + } } } @@ -964,7 +1002,7 @@ public function testTouchItem() usleep($capabilities->getTtlPrecision() * 2000000); $this->assertTrue($this->_storage->touchItem('key')); - usleep($capabilities->getTtlPrecision() * 2000000); + usleep($capabilities->getTtlPrecision() * 1000000); $this->assertTrue($this->_storage->hasItem('key')); if (!$capabilities->getUseRequestTime()) { diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index 5c7ac92df..d4f801203 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -21,8 +21,7 @@ namespace ZendTest\Cache\Storage\Adapter; -use Memcached, - Zend\Cache, +use Zend\Cache, Zend\Cache\Exception; /** @@ -51,9 +50,8 @@ public function setUp() public function tearDown() { - if (extension_loaded('memcached')) { - $m = new Memcached(); - $m->flush(); + if (!empty($this->_storage)) { + $this->_storage->clear(); } parent::tearDown(); From 9c7d024d481c4d924d7570321d661759329fcaeb Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 20:53:17 +0100 Subject: [PATCH 153/311] Zend\Cache\Storage\Adapter::getMetadata[s] should never throw an exception if the adapter doesn't support metadata. Instead return an empty array. - fixed memcached adapter - fixed tests --- src/Storage/Adapter/Memcached.php | 87 +++++++++++++++------- test/Storage/Adapter/CommonAdapterTest.php | 80 +++++++------------- 2 files changed, 85 insertions(+), 82 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 7dab2740e..b6867cab7 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -57,16 +57,16 @@ public function __construct($options = null) if (!extension_loaded('memcached')) { throw new Exception\ExtensionNotLoadedException("Memcached extension is not loaded"); } - + $this->memcached= new MemcachedResource(); - + if (!empty($options)) { $this->setOptions($options); } $options= $this->getOptions(); $this->memcached->addServer($options->getServer(), $options->getPort()); - + } /* options */ @@ -80,9 +80,9 @@ public function __construct($options = null) */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof MemcachedOptions + if (!is_array($options) + && !$options instanceof Traversable + && !$options instanceof MemcachedOptions ) { throw new Exception\InvalidArgumentException(sprintf( '%s expects an array, a Traversable object, or a MemcachedOptions object; ' @@ -230,11 +230,11 @@ public function getItems(array $keys, array $options = array()) } $fetch = $this->memcached->getMulti($internalKeys); - + if ($fetch===false) { throw new Exception\ItemNotFoundException('Memcached::getMulti() failed'); } - + // remove namespace prefix $prefixL = strlen($options['namespace'] . $namespaceSep); $result = array(); @@ -270,7 +270,38 @@ public function getItems(array $keys, array $options = array()) */ public function getMetadata($key, array $options = array()) { - throw new Exception\UnsupportedMethodCallException(__FUNCTION__ . ' is not supported by the adapter'); + $baseOptions = $this->getOptions(); + if (!$baseOptions->getReadable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; + $result = $this->memcached->get($internalKey); + if ($result===false) { + if (!$options['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + } + } else { + $result = array(); + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* writing */ @@ -491,9 +522,9 @@ public function replaceItem($key, $value, array $options = array()) "Key '{$internalKey}' doesn't exist" ); } - + $result = $this->memcached->replace($internalKey, $value, $options['ttl']); - + if ($result === false) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( @@ -547,16 +578,16 @@ public function removeItem($key, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - + $result = $this->memcached->delete($internalKey); - + if ($result === false) { if (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } } $result = true; - + return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -613,7 +644,7 @@ public function incrementItem($key, $value, array $options = array()) "Key '{$internalKey}' not found" ); } - + $this->addItem($key, $value, $options); $newValue = $value; } @@ -728,7 +759,7 @@ public function fetch() $result['key'] = substr($result['key'], $prefixL); } } - } + } return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { @@ -738,22 +769,22 @@ public function fetch() /** * FetchAll - * + * * @throws Exception - * @return array + * @return array */ public function fetchAll() { $prefixL = strlen($this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator()); - + $result = $this->memcached->fetchAll(); - + if ($result === false) { throw new Exception\RuntimeException("Memcached::fetchAll() failed"); } - + $select = $this->stmtOptions['select']; - + foreach ($result as &$elem) { if (in_array('key', $select)) { $elem['key'] = substr($elem['key'], $prefixL); @@ -761,10 +792,10 @@ public function fetchAll() unset($elem['key']); } } - + return $result; } - + /* cleaning */ /** @@ -807,7 +838,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } $result = $this->memcached->flush(); - + return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -919,7 +950,7 @@ public function getDelayed(array $keys, array $options = array()) } $this->stmtIterator = $this->memcached->getDelayed($search); - + $this->stmtActive = true; $this->stmtOptions = &$options; @@ -936,7 +967,7 @@ public function getDelayed(array $keys, array $options = array()) return $this->triggerException(__FUNCTION__, $args, $e); } } - + /** * Get storage capacity. * @@ -971,5 +1002,5 @@ public function getCapacity(array $options = array()) } /* internal */ - + } diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 88875528a..551cd1bd3 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -245,35 +245,36 @@ public function testGetItemReturnsFalseIfNonReadable() $this->assertFalse($this->_storage->getItem('key')); } + public function testGetItemsReturnsEmptyArrayIfNonReadable() + { + $this->_options->setReadable(false); + + $this->assertTrue($this->_storage->setItem('key', 'value')); + $this->assertEquals(array(), $this->_storage->getItems(array('key'))); + } + public function testGetMetadata() { $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - + $supportedMetadatas = $capabilities->getSupportedMetadata(); + $this->assertTrue($this->_storage->setItem('key', 'value')); - $this->assertInternalType('array', $this->_storage->getMetadata('key')); + $metadata = $this->_storage->getMetadata('key'); + + $this->assertInternalType('array', $metadata); + foreach ($supportedMetadatas as $supportedMetadata) { + $this->assertArrayHasKey($supportedMetadata, $metadata); + } } public function testGetMetadataReturnsFalseIfIgnoreMissingItemsEnabled() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - $this->_options->setIgnoreMissingItems(true); $this->assertFalse($this->_storage->getMetadata('unknown')); } public function testGetMetadataThrowsItemNotFoundExceptionIfIgnoreMissingItemsDisabled() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - $this->_options->setIgnoreMissingItems(false); $this->setExpectedException('Zend\Cache\Exception\ItemNotFoundException'); @@ -282,11 +283,6 @@ public function testGetMetadataThrowsItemNotFoundExceptionIfIgnoreMissingItemsDi public function testGetMetadataReturnsFalseIfNonReadable() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); @@ -296,10 +292,8 @@ public function testGetMetadataReturnsFalseIfNonReadable() public function testGetMetadatas() { $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - + $supportedMetadatas = $capabilities->getSupportedMetadata(); + $items = array( 'key1' => 'value1', 'key2' => 'value2' @@ -309,42 +303,20 @@ public function testGetMetadatas() $metadatas = $this->_storage->getMetadatas(array_keys($items)); $this->assertInternalType('array', $metadatas); $this->assertSame(count($items), count($metadatas)); - foreach ($metadatas as $k => $info) { - $this->assertTrue(isset($items[$k])); - $this->assertInternalType('array', $info); + foreach ($metadatas as $k => $metadata) { + $this->assertInternalType('array', $metadata); + foreach ($supportedMetadatas as $supportedMetadata) { + $this->assertArrayHasKey($supportedMetadata, $metadata); + } } } public function testGetMetadatasReturnsEmptyArrayIfNonReadable() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - $this->_options->setReadable(false); $this->assertTrue($this->_storage->setItem('key', 'value')); - $this->assertEquals(array(), $this->_storage->getItems(array('key'))); - } - - public function testGetMetadataAgainstMetadataCapabilities() - { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getSupportedMetadata()) { - $this->markTestSkipped("Metadata are not supported by the adapter"); - } - - $capabilities = $this->_storage->getCapabilities(); - - $this->assertTrue($this->_storage->setItem('key', 'value')); - - $metadata = $this->_storage->getMetadata('key'); - $this->assertInternalType('array', $metadata); - - foreach ($capabilities->getSupportedMetadata() as $property) { - $this->assertArrayHasKey($property, $metadata); - } + $this->assertEquals(array(), $this->_storage->getMetadatas(array('key'))); } public function testSetGetHasAndRemoveItem() @@ -833,14 +805,14 @@ public function testGetDelayedAndFetchAllWithSelectInfo() ))); $fetchedItems = $this->_storage->fetchAll(); - + $this->assertEquals(count($items), count($fetchedItems)); foreach ($fetchedItems as $item) { if (is_array($capabilities->getSupportedMetadata())) { foreach ($capabilities->getSupportedMetadata() as $selectProperty) { $this->assertArrayHasKey($selectProperty, $item); } - } + } } } From 301eb060244db690b8558c73a057bb51e0f2870a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 21:43:57 +0100 Subject: [PATCH 154/311] better getDelayed of memcached adapter - use third argument of Memcached::getDelayed to call given callback - better handling of given select option - added phpdoc for available options --- src/Storage/Adapter/AbstractAdapter.php | 14 +- src/Storage/Adapter/Memcached.php | 207 +++++++++++++++--------- 2 files changed, 141 insertions(+), 80 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 593bf85c6..14f52c077 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -739,6 +739,19 @@ public function decrementItems(array $keyValuePairs, array $options = array()) /** * Get delayed * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - select optional + * - An array of the information the returned item contains + * (Default: array('key', 'value')) + * - callback optional + * - An result callback will be invoked for each item in the result set. + * - The first argument will be the item array. + * - The callback does not have to return anything. + * * @param array $keys * @param array $options * @return bool @@ -758,7 +771,6 @@ public function getDelayed(array $keys, array $options = array()) } $this->normalizeOptions($options); - if (!isset($options['select'])) { $options['select'] = array('key', 'value'); } diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index b6867cab7..7767bf546 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -718,6 +718,115 @@ public function decrementItem($key, $value, array $options = array()) /* non-blocking */ + /** + * Get items that were marked to delay storage for purposes of removing blocking + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - select optional + * - An array of the information the returned item contains + * (Default: array('key', 'value')) + * - callback optional + * - An result callback will be invoked for each item in the result set. + * - The first argument will be the item array. + * - The callback does not have to return anything. + * + * @param array $keys + * @param array $options + * @return bool + * @throws Exception + * + * @triggers getDelayed.pre(PreEvent) + * @triggers getDelayed.post(PostEvent) + * @triggers getDelayed.exception(ExceptionEvent) + */ + public function getDelayed(array $keys, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($this->stmtActive) { + throw new Exception\RuntimeException('Statement already in use'); + } elseif (!$baseOptions->getReadable()) { + return false; + } elseif (!$keys) { + return true; + } + + $this->normalizeOptions($options); + if (isset($options['callback']) && !is_callable($options['callback'], false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } + if (!isset($options['select'])) { + $options['select'] = array('key', 'value'); + } + + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); + + // init search keys + $search = array(); + foreach ($keys as $key) { + $search[] = $prefix.$key; + } + + // we don't need the CAS token + $withCas = false; + + // redirect callback + if (isset($options['callback'])) { + $cb = function (MemcachedResource $memc, array &$item) use (&$options, $baseOptions) { + $select = & $options['select']; + + // handle selected key + if (in_array('key', $select)) { + $namespaceSeparator = $baseOptions->getNamespaceSeparator(); + $prefixL = strlen($options['namespace'] . $namespaceSeparator); + $item['key'] = substr($item['key'], $prefixL); + } else { + unset($item['key']); + } + + // handle selected value + if (!in_array('value', $select)) { + unset($item['value']); + } + + call_user_func($options['callback'], $item); + }; + + if (!$this->memcached->getDelayed($search, false, $cb)) { + throw new Exception\RuntimeException( + 'Memcached::getDelayed(, false, ) failed' + ); + } + } else { + if (!$this->memcached->getDelayed($search)) { + throw new Exception\RuntimeException( + 'Memcached::getDelayed() failed' + ); + } + + $this->stmtActive = true; + $this->stmtOptions = &$options; + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + /** * Fetches the next item from result set * @@ -742,23 +851,28 @@ public function fetch() return $eventRs->last(); } - $prefixL = strlen($this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator()); + $result = $this->memcached->fetch(); + if (!empty($result)) { + $select = & $this->stmtOptions['select']; + + // handle selected key + if (in_array('key', $select)) { + $namespaceSeparator = $this->getOptions()->getNamespaceSeparator(); + $prefixL = strlen($this->stmtOptions['namespace'] . $namespaceSeparator); + $result['key'] = substr($result['key'], $prefixL); + } else { + unset($result['key']); + } - if (!$this->stmtIterator) { - // clear stmt - $this->stmtActive = false; - $this->stmtIterator = null; - $this->stmtOptions = null; + // handle selected value + if (!in_array('value', $select)) { + unset($result['value']); + } - $result = false; } else { - $result = $this->memcached->fetch(); - if (!empty($result)) { - $select = $this->stmtOptions['select']; - if (in_array('key', $select)) { - $result['key'] = substr($result['key'], $prefixL); - } - } + // clear stmt + $this->stmtActive = false; + $this->stmtOptions = null; } return $this->triggerPost(__FUNCTION__, $args, $result); @@ -903,71 +1017,6 @@ public function getCapabilities() } } - /** - * Get items that were marked to delay storage for purposes of removing blocking - * - * @param array $keys - * @param array $options - * @return bool - * @throws Exception - * - * @triggers getDelayed.pre(PreEvent) - * @triggers getDelayed.post(PostEvent) - * @triggers getDelayed.exception(ExceptionEvent) - */ - public function getDelayed(array $keys, array $options = array()) - { - $baseOptions = $this->getOptions(); - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } elseif (!$baseOptions->getReadable()) { - return false; - } elseif (!$keys) { - return true; - } - - $this->normalizeOptions($options); - if (isset($options['callback']) && !is_callable($options['callback'], false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - - $search = array(); - foreach ($keys as $key) { - $search[] = $prefix.$key; - } - - $this->stmtIterator = $this->memcached->getDelayed($search); - - $this->stmtActive = true; - $this->stmtOptions = &$options; - - if (isset($options['callback'])) { - $callback = $options['callback']; - while (($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } - } - /** * Get storage capacity. * From b5dd8a3384196aa5897b36e47065ae8bb724a03d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 21:51:16 +0100 Subject: [PATCH 155/311] fixed documented options of memcached adapter - ttl is only available on set, add and replace item(s) - tags are not supported --- src/Storage/Adapter/Memcached.php | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 7767bf546..9b6699bb7 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -125,15 +125,12 @@ public function getOptions() return $this->options; } - /* reading */ /** * Get an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional @@ -190,8 +187,6 @@ public function getItem($key, array $options = array()) * Get multiple items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -252,8 +247,6 @@ public function getItems(array $keys, array $options = array()) * Get metadata of an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional @@ -310,10 +303,10 @@ public function getMetadata($key, array $options = array()) * Store an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param string $key * @param mixed $value @@ -365,10 +358,10 @@ public function setItem($key, $value, array $options = array()) * Store multiple items. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param array $keyValuePairs * @param array $options @@ -421,10 +414,10 @@ public function setItems(array $keyValuePairs, array $options = array()) * Add an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param string $key * @param mixed $value @@ -480,10 +473,10 @@ public function addItem($key, $value, array $options = array()) * Replace an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param string $key * @param mixed $value @@ -916,11 +909,7 @@ public function fetchAll() * Clear items off all namespaces. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * - No options available for this adapter * * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) * @param array $options From 3bb8ff57337c26c2e3b7c9d198ce8bf628642d99 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 22:12:13 +0100 Subject: [PATCH 156/311] Zend\Cache\Storage\Adapter::getPlugins returns a simple list of plugins to not allow editing the plugin registry outside of the adapter --- src/Storage/Adapter/AbstractAdapter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 14f52c077..264004a5c 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -344,11 +344,11 @@ public function removePlugin(Plugin $plugin) /** * Get all registered plugins * - * @return SplObjectStorage + * @return Plugin[] */ public function getPlugins() { - return $this->getPluginRegistry(); + return iterator_to_array($this->getPluginRegistry(), false); } /* reading */ From 05d8d478c87ce56e933de392e82a268f79ee59be Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 22:22:33 +0100 Subject: [PATCH 157/311] allow to set options on all adapter constructors --- src/Storage/Adapter/AbstractAdapter.php | 14 +++++++++ src/Storage/Adapter/Apc.php | 10 ++++--- src/Storage/Adapter/Memcached.php | 10 +++---- src/Storage/Adapter/WinCache.php | 38 +++++++++++++------------ 4 files changed, 44 insertions(+), 28 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 264004a5c..de7cfa345 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -100,6 +100,20 @@ abstract class AbstractAdapter implements Adapter */ protected $stmtOptions = null; + /** + * Constructor + * + * @param null|array|Traversable|AdapterOptions $options + * @throws Exception + * @return void + */ + public function __construct($options = null) + { + if ($options) { + $this->setOptions($options); + } + } + /** * Destructor * diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 23d23ba52..32f2838fc 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -64,11 +64,11 @@ class Apc extends AbstractAdapter /** * Constructor * - * @param array $options Option + * @param null|array|Traversable|ApcOptions $options * @throws Exception * @return void */ - public function __construct() + public function __construct($options = null) { if (version_compare('3.1.6', phpversion('apc')) > 0) { throw new Exception\ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); @@ -103,6 +103,8 @@ public function __construct() 'internal_key' => \APC_ITER_KEY, ); } + + parent::__construct($options); } /* options */ @@ -116,8 +118,8 @@ public function __construct() */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable + if (!is_array($options) + && !$options instanceof Traversable && !$options instanceof ApcOptions ) { throw new Exception\InvalidArgumentException(sprintf( diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 9b6699bb7..d718d3bb3 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -48,7 +48,7 @@ class Memcached extends AbstractAdapter /** * Constructor * - * @param array $options Option + * @param null|array|Traversable|MemcachedOptions $options * @throws Exception * @return void */ @@ -60,11 +60,9 @@ public function __construct($options = null) $this->memcached= new MemcachedResource(); - if (!empty($options)) { - $this->setOptions($options); - } + parent::__construct($options); - $options= $this->getOptions(); + $options = $this->getOptions(); $this->memcached->addServer($options->getServer(), $options->getPort()); } @@ -74,7 +72,7 @@ public function __construct($options = null) /** * Set options. * - * @param string|Traversable|MemcachedOptions $options + * @param array|Traversable|MemcachedOptions $options * @return Memcached * @see getOptions() */ diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 8bc97f04e..c8b4ce0fc 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -46,7 +46,7 @@ class WinCache extends AbstractAdapter /** * Constructor * - * @param array $options Option + * @param array|Traversable|WinCacheOptions $options * @throws Exception * @return void */ @@ -55,7 +55,7 @@ public function __construct() if (!extension_loaded('wincache')) { throw new Exception\ExtensionNotLoadedException("WinCache extension is not loaded"); } - + $enabled = ini_get('wincache.ucenabled'); if (PHP_SAPI == 'cli') { $enabled = $enabled && (bool) ini_get('wincache.enablecli'); @@ -66,6 +66,8 @@ public function __construct() "WinCache is disabled - see 'wincache.ucenabled' and 'wincache.enablecli'" ); } + + parent::__construct($options); } /* options */ @@ -73,15 +75,15 @@ public function __construct() /** * Set options. * - * @param stringTraversable|WinCacheOptions $options + * @param array|Traversable|WinCacheOptions $options * @return WinCache * @see getOptions() */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof WinCacheOptions + if (!is_array($options) + && !$options instanceof Traversable + && !$options instanceof WinCacheOptions ) { throw new Exception\InvalidArgumentException(sprintf( '%s expects an array, a Traversable object; ' @@ -322,15 +324,15 @@ public function hasItems(array $keys, array $options = array()) foreach ($keys as $key) { $internalKeys[] = $options['namespace'] . $namespaceSep . $key; } - + $prefixL = strlen($options['namespace'] . $namespaceSep); $result = array(); foreach ($internalKeys as $key) { if (wincache_ucache_exists($key)) { $result[] = substr($key, $prefixL); - } + } } - + return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -382,7 +384,7 @@ public function getMetadata($key, array $options = array()) $info = wincache_ucache_info(true, $internalKey); if (isset($info['ucache_entries'][1])) { $metadata = $info['ucache_entries'][1]; - } + } if (empty($metadata)) { if (!$options['ignore_missing_items']) { @@ -429,9 +431,9 @@ public function getMetadatas(array $keys, array $options = array()) if ($eventRs->stopped()) { return $eventRs->last(); } - + $result= array(); - + foreach ($keys as $key) { $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; @@ -448,7 +450,7 @@ public function getMetadatas(array $keys, array $options = array()) $result[ substr($internalKey, $prefixL) ] = & $metadata; } } - + if (!$options['ignore_missing_items']) { if (count($keys) != count($result)) { $missing = implode("', '", array_diff($keys, array_keys($result))); @@ -860,7 +862,7 @@ public function incrementItem($key, $value, array $options = array()) "Key '{$internalKey}' not found" ); } - + $this->addItem($key, $value, $options); $newValue = $value; } @@ -977,7 +979,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } $result= wincache_ucache_clear(); - + return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1093,17 +1095,17 @@ protected function normalizeMetadata(array &$metadata) $metadata['num_hits'] = $metadata['hitcount']; unset($metadata['hitcount']); } - + if (isset($metadata['ttl_seconds'])) { $metadata['ttl'] = $metadata['ttl_seconds']; unset($metadata['ttl_seconds']); } - + if (isset($metadata['value_size'])) { $metadata['mem_size'] = $metadata['value_size']; unset($metadata['value_size']); } - + // remove namespace prefix if (isset($metadata['key_name'])) { $pos = strpos($metadata['key_name'], $this->getOptions()->getNamespaceSeparator()); From 7c4ef6bf4c0c6123d7423b7b0931511dec7794f6 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 22:31:34 +0100 Subject: [PATCH 158/311] allow to set options on WinCache adapter constructor --- src/Storage/Adapter/WinCache.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index c8b4ce0fc..a4c0086fc 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -50,7 +50,7 @@ class WinCache extends AbstractAdapter * @throws Exception * @return void */ - public function __construct() + public function __construct($options = null) { if (!extension_loaded('wincache')) { throw new Exception\ExtensionNotLoadedException("WinCache extension is not loaded"); @@ -110,7 +110,6 @@ public function getOptions() return $this->options; } - /* reading */ /** From d2c470e62e5d222f383de935ba54ed1b8d49715c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 22:33:27 +0100 Subject: [PATCH 159/311] Don't throw an exception on remove a not registered plugin (talked with matthiew) --- src/Storage/Adapter/AbstractAdapter.php | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index de7cfa345..0e01b10f8 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -345,13 +345,8 @@ public function removePlugin(Plugin $plugin) $registry = $this->getPluginRegistry(); if ($registry->contains($plugin)) { $plugin->detach($this->events()); - } else { - throw new Exception\LogicException(sprintf( - 'Plugin of type "%s" already removed', - get_class($plugin) - )); + $registry->detach($plugin); } - $registry->detach($plugin); return $this; } From e06c623225fd72b33cc710796a9376ea66c5d80b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 23:03:57 +0100 Subject: [PATCH 160/311] - use build-in functionality of CAS of ext/memcached - fixed phpdocs of checkAndSetItem --- src/Storage/Adapter/AbstractAdapter.php | 8 ++-- src/Storage/Adapter/Filesystem.php | 42 ++++++++++---------- src/Storage/Adapter/Memcached.php | 53 ++++++++++++++++++++++--- 3 files changed, 72 insertions(+), 31 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 0e01b10f8..d499dd24f 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -566,10 +566,10 @@ public function replaceItems(array $keyValuePairs, array $options = array()) /** * Check and set item * - * @param string $token - * @param string|int $key - * @param mixed $value - * @param array $options + * @param mixed $token + * @param string $key + * @param mixed $value + * @param array $options * @return bool */ public function checkAndSetItem($token, $key, $value, array $options = array()) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 049a5ab72..62ead9122 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -80,8 +80,8 @@ class Filesystem extends AbstractAdapter */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable + if (!is_array($options) + && !$options instanceof Traversable && !$options instanceof FilesystemOptions ) { throw new Exception\InvalidArgumentException(sprintf( @@ -648,10 +648,10 @@ public function addItems(array $keyValuePairs, array $options = array()) /** * check and set item * - * @param $token - * @param $key - * @param $value - * @param array $options + * @param string $token + * @param string $key + * @param mixed $value + * @param array $options * @return bool|mixed * @throws ItemNotFoundException */ @@ -1320,7 +1320,7 @@ protected function internalHasItem($key, array &$options) * @return array|bool * @throws ItemNotFoundException */ - protected function internalGetMetadata($key, array &$options) + protected function internalGetMetadata($key, array &$options) { $keyInfo = $this->getKeyInfo($key, $options['namespace']); if (!$keyInfo) { @@ -1537,7 +1537,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { - if (!isset($info['tags']) + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0 ) { continue; @@ -1545,7 +1545,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_NO_TAGS mode -> check if no given tag available in current cache } elseif(($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS) { - if (isset($info['tags']) + if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags']) ) { continue; @@ -1553,7 +1553,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { - if (!isset($info['tags']) + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags']) ) { continue; @@ -1686,7 +1686,7 @@ protected function getFileSpec($key, $ns) * @return array|boolean The info array or false if file wasn't found * @throws Exception\RuntimeException */ - protected function readInfoFile($file) + protected function readInfoFile($file) { if (!file_exists($file)) { return false; @@ -1718,10 +1718,10 @@ protected function getFileContent($file) if ($this->getOptions()->getFileLocking()) { set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { $message = sprintf( - 'Error getting contents from file "%s" (in %s@%d): %s', - $file, - $errfile, - $errline, + 'Error getting contents from file "%s" (in %s@%d): %s', + $file, + $errfile, + $errline, $errstr ); throw new Exception\RuntimeException($message, $errno); @@ -1730,17 +1730,17 @@ protected function getFileContent($file) restore_error_handler(); if ($fp === false) { throw new Exception\RuntimeException(sprintf( - 'Unknown error getting contents from file "%s"', + 'Unknown error getting contents from file "%s"', $file )); } set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { $message = sprintf( - 'Error locking file "%s" (in %s@%d): %s', - $file, - $errfile, - $errline, + 'Error locking file "%s" (in %s@%d): %s', + $file, + $errfile, + $errline, $errstr ); throw new Exception\RuntimeException($message, $errno); @@ -1859,7 +1859,7 @@ protected function putFileContent($file, $data) * @return void * @throw RuntimeException */ - protected function unlink($file) + protected function unlink($file) { // If file does not exist, nothing to do if (!file_exists($file)) { diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index d718d3bb3..5f91a82fe 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -164,15 +164,16 @@ public function getItem($key, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = $this->memcached->get($internalKey); - if ($result===false) { + if (array_key_exists('token', $options)) { + $result = $this->memcached->get($internalKey, null, $options['token']); + } else { + $result = $this->memcached->get($internalKey); + } + + if ($result === false) { if (!$options['ignore_missing_items']) { throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - } else { - if (array_key_exists('token', $options)) { - $options['token'] = $result; - } } return $this->triggerPost(__FUNCTION__, $args, $result); @@ -529,6 +530,46 @@ public function replaceItem($key, $value, array $options = array()) } } + /** + * Check and set item + * + * @param float $token + * @param string $key + * @param mixed $value + * @param array $options + * @return bool + */ + public function checkAndSetItem($token, $key, $value, array $options = array()) + { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'token' => & $token, + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; + $result = $this->memcached->cas($token, $internalKey, $value, $options['ttl']); + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + /** * Remove an item. * From d1fbf87e3eed5f23e3e20f386b6b60ffcfbb248b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 23:10:32 +0100 Subject: [PATCH 161/311] added capability 'maxKeyLength' => 255 to memcached adapter --- src/Storage/Adapter/Memcached.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 5f91a82fe..7c31ce22e 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -1030,6 +1030,7 @@ public function getCapabilities() 'ttlPrecision' => 1, 'useRequestTime' => false, 'expiredRead' => false, + 'maxKeyLength' => 255, 'namespaceIsPrefix' => true, 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), 'iterable' => false, From 5317ad5095032dbca1fe2c6524f32c8c5871417f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 21 Dec 2011 23:22:38 +0100 Subject: [PATCH 162/311] fixed ttl vs. expiration time on memcached adapter --- src/Storage/Adapter/Memcached.php | 45 ++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 7c31ce22e..8dc24da67 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -339,10 +339,11 @@ public function setItem($key, $value, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!$this->memcached->set($internalKey, $value, $options['ttl'])) { + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->set($internalKey, $value, $expiration)) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "Memcached::set('{$internalKey}', <{$type}>, {$options['ttl']}) failed" + "Memcached::set('{$internalKey}', <{$type}>, {$expiration}) failed" ); } @@ -397,9 +398,10 @@ public function setItems(array $keyValuePairs, array $options = array()) $internalKeyValuePairs[$internalKey] = &$value; } - $errKeys = $this->memcached->setMulti($internalKeyValuePairs, $options['ttl']); + $expiration = $this->expirationTime($options['ttl']); + $errKeys = $this->memcached->setMulti($internalKeyValuePairs, $expiration); if ($errKeys==false) { - throw new Exception\RuntimeException("Memcached::setMulti(, {$options['ttl']}) failed"); + throw new Exception\RuntimeException("Memcached::setMulti(, {$expiration}) failed"); } $result = true; @@ -450,14 +452,15 @@ public function addItem($key, $value, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!$this->memcached->add($internalKey, $value, $options['ttl'])) { + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->add($internalKey, $value, $expiration)) { if ($this->memcached->get($internalKey)!==false) { throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); } $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "Memcached::add('{$internalKey}', <{$type}>, {$options['ttl']}) failed" + "Memcached::add('{$internalKey}', <{$type}>, {$expiration}) failed" ); } @@ -515,12 +518,13 @@ public function replaceItem($key, $value, array $options = array()) ); } - $result = $this->memcached->replace($internalKey, $value, $options['ttl']); + $expiration = $this->expirationTime($options['ttl']); + $result = $this->memcached->replace($internalKey, $value, $expiration); if ($result === false) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "Memcached::replace('{$internalKey}', <{$type}>, {$options['ttl']}) failed" + "Memcached::replace('{$internalKey}', <{$type}>, {$expiration}) failed" ); } @@ -562,7 +566,8 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = $this->memcached->cas($token, $internalKey, $value, $options['ttl']); + $expiration = $this->expirationTime($options['ttl']); + $result = $this->memcached->cas($token, $internalKey, $value, $expiration); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { @@ -1081,4 +1086,26 @@ public function getCapacity(array $options = array()) /* internal */ + /** + * Get expiration time by ttl + * + * Some storage commands involve sending an expiration value (relative to + * an item or to an operation requested by the client) to the server. In + * all such cases, the actual value sent may either be Unix time (number of + * seconds since January 1, 1970, as an integer), or a number of seconds + * starting from current time. In the latter case, this number of seconds + * may not exceed 60*60*24*30 (number of seconds in 30 days); if the + * expiration value is larger than that, the server will consider it to be + * real Unix time value rather than an offset from current time. + * + * @param int $ttl + * @return int + */ + protected function expirationTime($ttl) + { + if ($ttl > 2592000) { + return time() + $ttl; + } + return $ttl; + } } From 5be8384a045894870f0a8d12d65b6c4d1351c307 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 22 Dec 2011 00:05:05 +0100 Subject: [PATCH 163/311] use Memcached::getResult[Code|Message] to generate exception and to check if it's an ItemNotFound error --- src/Storage/Adapter/Memcached.php | 154 +++++++++++++++++------------- 1 file changed, 90 insertions(+), 64 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 8dc24da67..c225ac3c5 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -171,8 +171,10 @@ public function getItem($key, array $options = array()) } if ($result === false) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + if (($rsCode = $this->memcached->getResultCode()) != 0 + && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) + ) { + throw $this->getExceptionByResultCode($rsCode); } } @@ -224,9 +226,8 @@ public function getItems(array $keys, array $options = array()) } $fetch = $this->memcached->getMulti($internalKeys); - - if ($fetch===false) { - throw new Exception\ItemNotFoundException('Memcached::getMulti() failed'); + if ($fetch === false) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } // remove namespace prefix @@ -282,9 +283,12 @@ public function getMetadata($key, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $result = $this->memcached->get($internalKey); - if ($result===false) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + + if ($result === false) { + if (($rsCode = $this->memcached->getResultCode()) != 0 + && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) + ) { + throw $this->getExceptionByResultCode($rsCode); } } else { $result = array(); @@ -341,10 +345,7 @@ public function setItem($key, $value, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $expiration = $this->expirationTime($options['ttl']); if (!$this->memcached->set($internalKey, $value, $expiration)) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "Memcached::set('{$internalKey}', <{$type}>, {$expiration}) failed" - ); + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } $result = true; @@ -399,9 +400,8 @@ public function setItems(array $keyValuePairs, array $options = array()) } $expiration = $this->expirationTime($options['ttl']); - $errKeys = $this->memcached->setMulti($internalKeyValuePairs, $expiration); - if ($errKeys==false) { - throw new Exception\RuntimeException("Memcached::setMulti(, {$expiration}) failed"); + if (!$this->memcached->setMulti($internalKeyValuePairs, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } $result = true; @@ -454,14 +454,7 @@ public function addItem($key, $value, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $expiration = $this->expirationTime($options['ttl']); if (!$this->memcached->add($internalKey, $value, $expiration)) { - if ($this->memcached->get($internalKey)!==false) { - throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); - } - - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "Memcached::add('{$internalKey}', <{$type}>, {$expiration}) failed" - ); + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } $result = true; @@ -512,22 +505,12 @@ public function replaceItem($key, $value, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!$this->memcached->get($internalKey)) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' doesn't exist" - ); - } - - $expiration = $this->expirationTime($options['ttl']); - $result = $this->memcached->replace($internalKey, $value, $expiration); - - if ($result === false) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "Memcached::replace('{$internalKey}', <{$type}>, {$expiration}) failed" - ); + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->replace($internalKey, $value, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -567,7 +550,15 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $expiration = $this->expirationTime($options['ttl']); - $result = $this->memcached->cas($token, $internalKey, $value, $expiration); + $result = $this->memcached->cas($token, $internalKey, $value, $expiration); + + if ($result === false) { + $rsCode = $this->memcached->getResultCode(); + if ($rsCode !== 0 && $rsCode != MemcachedResource::RES_DATA_EXISTS) { + throw $this->getExceptionByResultCode($rsCode); + } + } + return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { @@ -615,16 +606,17 @@ public function removeItem($key, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = $this->memcached->delete($internalKey); if ($result === false) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + if (($rsCode = $this->memcached->getResultCode()) != 0 + && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) + ) { + throw $this->getExceptionByResultCode($rsCode); } } - $result = true; + $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -673,16 +665,19 @@ public function incrementItem($key, $value, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $value = (int)$value; $newValue = $this->memcached->increment($internalKey, $value); + if ($newValue === false) { - if ($this->memcached->get($internalKey)!==false) { - throw new Exception\RuntimeException("Memcached::increment('{$internalKey}', {$value}) failed"); - } elseif (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); + if (($rsCode = $this->memcached->getResultCode()) != 0 + && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) + ) { + throw $this->getExceptionByResultCode($rsCode); + } + + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->add($internalKey, $value, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } - $this->addItem($key, $value, $options); $newValue = $value; } @@ -734,16 +729,19 @@ public function decrementItem($key, $value, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; $value = (int)$value; $newValue = $this->memcached->decrement($internalKey, $value); + if ($newValue === false) { - if ($this->memcached->get($internalKey)!==false) { - throw new Exception\RuntimeException("Memcached::decrement('{$internalKey}', {$value}) failed"); - } elseif (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); + if (($rsCode = $this->memcached->getResultCode()) != 0 + && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) + ) { + throw $this->getExceptionByResultCode($rsCode); + } + + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->add($internalKey, -$value, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } - $this->addItem($key, -$value, $options); $newValue = -$value; } @@ -842,15 +840,11 @@ public function getDelayed(array $keys, array $options = array()) }; if (!$this->memcached->getDelayed($search, false, $cb)) { - throw new Exception\RuntimeException( - 'Memcached::getDelayed(, false, ) failed' - ); + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } } else { if (!$this->memcached->getDelayed($search)) { - throw new Exception\RuntimeException( - 'Memcached::getDelayed() failed' - ); + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } $this->stmtActive = true; @@ -984,8 +978,11 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) return $eventRs->last(); } - $result = $this->memcached->flush(); + if (!$this->memcached->flush()) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } + $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1073,7 +1070,12 @@ public function getCapacity(array $options = array()) return $eventRs->last(); } - $mem = array_pop($this->memcached->getStats()); + $stats = $this->memcached->getStats(); + if ($stats === false) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } + + $mem = array_pop($stats); $result = array( 'free' => $mem['limit_maxbytes'] - $mem['bytes'], 'total' => $mem['limit_maxbytes'], @@ -1108,4 +1110,28 @@ protected function expirationTime($ttl) } return $ttl; } + + /** + * Generate exception based of memcached result code + * + * @param int $code + * @return Exception\RuntimeException|Exception\ItemNotFoundException + * @throws Exception\InvalidArgumentException On success code + */ + protected function getExceptionByResultCode($code) + { + switch ($code) { + case \Memcached::RES_SUCCESS: + throw new Exception\InvalidArgumentException( + "The result code '{$code}' (SUCCESS) isn't an error" + ); + + case \Memcached::RES_NOTFOUND: + case \Memcached::RES_NOTSTORED: + return new Exception\ItemNotFoundException($this->memcached->getResultMessage()); + + default: + return new Exception\RuntimeException($this->memcached->getResultMessage()); + } + } } From bfdf39fcfdf3361a9c15e62f9be85f0dad246a36 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 22 Dec 2011 00:37:15 +0100 Subject: [PATCH 164/311] make static class Zend\Cache\Utils abstract --- src/Utils.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Utils.php b/src/Utils.php index 632b66e01..16b8afe3e 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -26,7 +26,7 @@ * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Utils +abstract class Utils { /** * Get disk capacity From e7ba72516440a5b2d9ad1b567641dd9eb5d0dfc5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 14:41:34 +0100 Subject: [PATCH 165/311] options argument of Zend\Cache\StorageFactory::adapterFactory can be null --- src/StorageFactory.php | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 05a86ce9b..f558e9651 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -128,7 +128,7 @@ public static function factory($cfg) // set adapter or plugin options if (isset($cfg['options'])) { - if (!is_array($cfg['options']) + if (!is_array($cfg['options']) && !$cfg['options'] instanceof Traversable ) { throw new Exception\InvalidArgumentException( @@ -150,20 +150,23 @@ public static function factory($cfg) * Instantiate a storage adapter * * @param string|Storage\Adapter $adapterName - * @param array|Traversable|Storage\Adapter\AdapterOptions $options + * @param null|array|Traversable|Storage\Adapter\AdapterOptions $options * @return Storage\Adapter * @throws Exception\RuntimeException */ - public static function adapterFactory($adapterName, $options = array()) + public static function adapterFactory($adapterName, $options = null) { if ($adapterName instanceof Storage\Adapter) { // $adapterName is already an adapter object - $adapterName->setOptions($options); - return $adapterName; + $adapter = $adapterName; + } else { + $adapter = static::getAdapterBroker()->load($adapterName); + } + + if ($options !== null) { + $adapter->setOptions($options); } - $adapter = static::getAdapterBroker()->load($adapterName); - $adapter->setOptions($options); return $adapter; } From bef4230ed635b2bd50e88fc763dcb33ecf8b7cc5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 14:42:42 +0100 Subject: [PATCH 166/311] fixed phpdoc of Zend\Cache\Storage\Adapter\Filesystem::setOptions --- src/Storage/Adapter/Filesystem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 62ead9122..5f6df9b94 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -75,7 +75,7 @@ class Filesystem extends AbstractAdapter * Set options. * * @param array|Traversable|FilesystemOptions $options - * @return FilesystemAdapter + * @return Filesystem * @see getOptions() */ public function setOptions($options) From 3a0341dd36b67f4c895faaf2577a78b968c057a1 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 15:19:02 +0100 Subject: [PATCH 167/311] implemented memory limit for memory adapter: - added option memory_limit (default: PHP memorylimit / 2) - now the memory adapter has on own options class - set Zend\Cache\Utils::bytesFromString() public to be callable by memory adapter - added OutOfCapacityException --- src/Exception/OutOfCapacityException.php | 33 ++++++++ src/Storage/Adapter/Memory.php | 97 +++++++++++++++++++++++- src/Storage/Adapter/MemoryOptions.php | 82 ++++++++++++++++++++ src/Utils.php | 2 +- test/Storage/Adapter/MemoryTest.php | 11 ++- 5 files changed, 222 insertions(+), 3 deletions(-) create mode 100644 src/Exception/OutOfCapacityException.php create mode 100644 src/Storage/Adapter/MemoryOptions.php diff --git a/src/Exception/OutOfCapacityException.php b/src/Exception/OutOfCapacityException.php new file mode 100644 index 000000000..8c81c8ff3 --- /dev/null +++ b/src/Exception/OutOfCapacityException.php @@ -0,0 +1,33 @@ +options = $options; + return $this; + } + + /** + * Get options. + * + * @return MemoryOptions + * @see setOptions() + */ + public function getOptions() + { + if (!$this->options) { + $this->setOptions(new MemoryOptions()); + } + return $this->options; + } + /* reading */ /** @@ -332,6 +376,13 @@ public function setItem($key, $value, array $options = array()) return $eventRs->last(); } + if (!$this->hasFreeCapacity()) { + $memoryLimit = $baseOptions->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); + } + $ns = $options['namespace']; $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); @@ -379,6 +430,13 @@ public function setItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } + if (!$this->hasFreeCapacity()) { + $memoryLimit = $baseOptions->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); + } + $ns = $options['namespace']; if (!isset($this->data[$ns])) { $this->data[$ns] = array(); @@ -436,6 +494,13 @@ public function addItem($key, $value, array $options = array()) return $eventRs->last(); } + if (!$this->hasFreeCapacity()) { + $memoryLimit = $baseOptions->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); + } + $ns = $options['namespace']; if (isset($this->data[$ns][$key])) { throw new Exception\RuntimeException("Key '{$key}' already exists within namespace '$ns'"); @@ -486,6 +551,13 @@ public function addItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } + if (!$this->hasFreeCapacity()) { + $memoryLimit = $baseOptions->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); + } + $ns = $options['namespace']; if (!isset($this->data[$ns])) { $this->data[$ns] = array(); @@ -1276,7 +1348,7 @@ public function getCapabilities() 'resource' => true, ), 'supportedMetadata' => array( - 'mtime', + 'mtime', 'tags', ), 'maxTtl' => PHP_INT_MAX, @@ -1319,6 +1391,13 @@ public function getCapacity(array $options = array()) return $eventRs->last(); } + $total = $this->getOptions()->getMemoryLimit(); + $free = $total - (float) memory_get_usage(true); + $result = array( + 'total' => $total, + 'free' => ($free >= 0) ? $free : 0, + ); + $result = Utils::getPhpMemoryCapacity(); return $this->triggerPost(__FUNCTION__, $args, $result); @@ -1326,6 +1405,22 @@ public function getCapacity(array $options = array()) /* internal */ + /** + * Has the memory adapter storage free capacity + * to store items + * + * Similar logic as getCapacity() but without triggering + * events and returns boolean. + * + * @return boolean + */ + protected function hasFreeCapacity() + { + $total = $this->getOptions()->getMemoryLimit(); + $free = $total - (float) memory_get_usage(true); + return ($free > 0); + } + /** * Internal method to check if an key exists * and if it isn't expired. diff --git a/src/Storage/Adapter/MemoryOptions.php b/src/Storage/Adapter/MemoryOptions.php new file mode 100644 index 000000000..ed78409eb --- /dev/null +++ b/src/Storage/Adapter/MemoryOptions.php @@ -0,0 +1,82 @@ +memoryLimit = (int) $bytes; + return $this; + } + + /** + * Get memory limit + * + * If the used memory of PHP exceeds this limit an OutOfCapacityException + * will be thrown. + * + * @return int + */ + public function getMemoryLimit() + { + if ($this->memoryLimit === null) { + $memoryLimit = Utils::bytesFromString(ini_get('memory_limit')); + if ($memoryLimit >= 0) { + $this->memoryLimit = floor($memoryLimit / 2); + } else { + // use a hard memory limit of 32M if php memory limit is disabled + $this->memoryLimit = 33554432; + } + } + + return $this->memoryLimit; + } +} diff --git a/src/Utils.php b/src/Utils.php index 16b8afe3e..696740aa7 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -224,7 +224,7 @@ static public function getHashAlgos() * @return float * @throws Exception\RuntimeException */ - static protected function bytesFromString($memStr) + static public function bytesFromString($memStr) { if (!preg_match('/\s*([\-\+]?\d+)\s*(\w*)\s*/', $memStr, $matches)) { throw new Exception\RuntimeException("Can't detect bytes of string '{$memStr}'"); diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index d5b3f3a33..42a599ab2 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -37,10 +37,19 @@ class MemoryTest extends CommonAdapterTest public function setUp() { // instantiate memory adapter - $this->_options = new Cache\Storage\Adapter\AdapterOptions(); + $this->_options = new Cache\Storage\Adapter\MemoryOptions(); $this->_storage = new Cache\Storage\Adapter\Memory(); $this->_storage->setOptions($this->_options); parent::setUp(); } + + public function testThrowOutOfCapacityException() + { + $this->_options->setMemoryLimit(memory_get_usage(true) + 5); + + $this->setExpectedException('Zend\Cache\Exception\OutOfCapacityException'); + $this->_storage->addItem('test', 'test'); + } + } From 6eb84e89a6276f35e19e3f62fc7b4361dd63b4e5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 16:24:46 +0100 Subject: [PATCH 168/311] use of Memcached::deleteMulti since ext/memcached 2.0.0 version check of ext/memcached >= 1.0.0 --- src/Storage/Adapter/Memcached.php | 83 +++++++++++++++++++++++++++++-- 1 file changed, 80 insertions(+), 3 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index c225ac3c5..8b161fc68 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -38,6 +38,13 @@ */ class Memcached extends AbstractAdapter { + /** + * Major version of ext/memcached + * + * @var null|int + */ + protected static $extMemcachedMajorVersion; + /** * Memcached instance * @@ -54,11 +61,16 @@ class Memcached extends AbstractAdapter */ public function __construct($options = null) { - if (!extension_loaded('memcached')) { - throw new Exception\ExtensionNotLoadedException("Memcached extension is not loaded"); + if (static::$extMemcachedMajorVersion === null) { + $v = (string) phpversion('memcached'); + static::$extMemcachedMajorVersion = ($v !== '') ? (int)$v[0] : 0; + } + + if (static::$extMemcachedMajorVersion < 1) { + throw new Exception\ExtensionNotLoadedException('Need ext/memcached version >= 1.0.0'); } - $this->memcached= new MemcachedResource(); + $this->memcached = new MemcachedResource(); parent::__construct($options); @@ -623,6 +635,71 @@ public function removeItem($key, array $options = array()) } } + /** + * Remove items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers removeItems.pre(PreEvent) + * @triggers removeItems.post(PostEvent) + * @triggers removeItems.exception(ExceptionEvent) + */ + public function removeItems(array $keys, array $options = array()) + { + $baseOptions = $this->getOptions(); + if (!$baseOptions->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $rsCodes = array(); + + if (method_exists($this->memcached, 'deleteMulti')) { + $rsCodes = $this->memcached->deleteMulti($keys); + } else { + foreach ($keys as $key) { + $rs = $this->memcached->delete($key); + if ($rs === false) { + $rsCodes[$key] = $this->memcached->getResultCode(); + } + } + } + + $missingKeys = null; + foreach ($rsCodes as $key => $rsCode) { + if ($rsCode !== true && $rsCode != 0) { + if ($rsCode != MemcachedResource::RES_NOTFOUND) { + throw $this->getExceptionByResultCode($rsCode); + } elseif (!$options['ignore_missing_items']) { + $missingKeys[] = $key; + } + } + } + if ($missingKeys) { + throw new Exception\ItemNotFoundException( + "Keys '" . implode("','", $missingKeys) . "' not found" + ); + } + + return true; + } catch (\MemcachedException $e) { + throw new RuntimeException($e->getMessage(), 0, $e); + } + } + /** * Increment an item. * From d479bdd770a4ad9b48ad87444077cd09047d889a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 22:56:23 +0100 Subject: [PATCH 169/311] fixed event params of memcached adapter check of Memcached::deleteMulti by version to minize calls of method_exists --- src/Storage/Adapter/Memcached.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 8b161fc68..54ce107ff 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -607,7 +607,6 @@ public function removeItem($key, array $options = array()) $this->normalizeKey($key); $args = new ArrayObject(array( 'key' => & $key, - 'value' => & $value, 'options' => & $options, )); @@ -667,7 +666,7 @@ public function removeItems(array $keys, array $options = array()) try { $rsCodes = array(); - if (method_exists($this->memcached, 'deleteMulti')) { + if (static::$extMemcachedMajorVersion >= 2) { $rsCodes = $this->memcached->deleteMulti($keys); } else { foreach ($keys as $key) { @@ -730,6 +729,7 @@ public function incrementItem($key, $value, array $options = array()) $this->normalizeKey($key); $args = new ArrayObject(array( 'key' => & $key, + 'value' => & $value, 'options' => & $options, )); @@ -794,6 +794,7 @@ public function decrementItem($key, $value, array $options = array()) $this->normalizeKey($key); $args = new ArrayObject(array( 'key' => & $key, + 'value' => & $value, 'options' => & $options, )); @@ -873,7 +874,7 @@ public function getDelayed(array $keys, array $options = array()) } $args = new ArrayObject(array( - 'key' => & $key, + 'keys' => & $keys, 'options' => & $options, )); From 171f2320276c38000788c7c0cf2d1495e954136e Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 23:48:48 +0100 Subject: [PATCH 170/311] use of Memcached::OPT_PREFIX_KEY as namespace - add length check of namespace to be lower than 128 characters - redirect [set|get]PrefixKey to [get|set]Namespace - set internal option Memcached::OPT_PREFIX_KEY before each read/write operation - removed option namespace_separator - removed prefix_key from options map --- src/Storage/Adapter/Memcached.php | 125 +++++--------- src/Storage/Adapter/MemcachedOptions.php | 207 ++++++++++------------- 2 files changed, 139 insertions(+), 193 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 54ce107ff..561f0f28d 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -175,11 +175,11 @@ public function getItem($key, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); if (array_key_exists('token', $options)) { - $result = $this->memcached->get($internalKey, null, $options['token']); + $result = $this->memcached->get($key, null, $options['token']); } else { - $result = $this->memcached->get($internalKey); + $result = $this->memcached->get($key); } if ($result === false) { @@ -231,24 +231,12 @@ public function getItems(array $keys, array $options = array()) return $eventRs->last(); } - $namespaceSep = $baseOptions->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $namespaceSep . $key; - } - - $fetch = $this->memcached->getMulti($internalKeys); - if ($fetch === false) { + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + $result = $this->memcached->getMulti($keys); + if ($result === false) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } - // remove namespace prefix - $prefixL = strlen($options['namespace'] . $namespaceSep); - $result = array(); - foreach ($fetch as $internalKey => &$value) { - $result[ substr($internalKey, $prefixL) ] = $value; - } - return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -293,8 +281,8 @@ public function getMetadata($key, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = $this->memcached->get($internalKey); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + $result = $this->memcached->get($key); if ($result === false) { if (($rsCode = $this->memcached->getResultCode()) != 0 @@ -354,9 +342,10 @@ public function setItem($key, $value, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->set($internalKey, $value, $expiration)) { + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->set($key, $value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -404,15 +393,10 @@ public function setItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - $internalKeyValuePairs = array(); - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - foreach ($keyValuePairs as $key => &$value) { - $internalKey = $prefix . $key; - $internalKeyValuePairs[$internalKey] = &$value; - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->setMulti($internalKeyValuePairs, $expiration)) { + if (!$this->memcached->setMulti($keyValuePairs, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -463,9 +447,10 @@ public function addItem($key, $value, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->add($internalKey, $value, $expiration)) { + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->add($key, $value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -516,9 +501,10 @@ public function replaceItem($key, $value, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->replace($internalKey, $value, $expiration)) { + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + + $expiration = $this->expirationTime($options['ttl']); + if (!$this->memcached->replace($key, $value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -560,9 +546,10 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $expiration = $this->expirationTime($options['ttl']); - $result = $this->memcached->cas($token, $internalKey, $value, $expiration); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + + $expiration = $this->expirationTime($options['ttl']); + $result = $this->memcached->cas($token, $key, $value, $expiration); if ($result === false) { $rsCode = $this->memcached->getResultCode(); @@ -616,8 +603,8 @@ public function removeItem($key, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = $this->memcached->delete($internalKey); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + $result = $this->memcached->delete($key); if ($result === false) { if (($rsCode = $this->memcached->getResultCode()) != 0 @@ -664,8 +651,9 @@ public function removeItems(array $keys, array $options = array()) )); try { - $rsCodes = array(); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + $rsCodes = array(); if (static::$extMemcachedMajorVersion >= 2) { $rsCodes = $this->memcached->deleteMulti($keys); } else { @@ -739,9 +727,10 @@ public function incrementItem($key, $value, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $value = (int)$value; - $newValue = $this->memcached->increment($internalKey, $value); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + + $value = (int)$value; + $newValue = $this->memcached->increment($key, $value); if ($newValue === false) { if (($rsCode = $this->memcached->getResultCode()) != 0 @@ -751,7 +740,7 @@ public function incrementItem($key, $value, array $options = array()) } $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->add($internalKey, $value, $expiration)) { + if (!$this->memcached->add($key, $value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -804,9 +793,10 @@ public function decrementItem($key, $value, array $options = array()) return $eventRs->last(); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $value = (int)$value; - $newValue = $this->memcached->decrement($internalKey, $value); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + + $value = (int)$value; + $newValue = $this->memcached->decrement($key, $value); if ($newValue === false) { if (($rsCode = $this->memcached->getResultCode()) != 0 @@ -816,7 +806,7 @@ public function decrementItem($key, $value, array $options = array()) } $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->add($internalKey, -$value, $expiration)) { + if (!$this->memcached->add($key, -$value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -884,16 +874,7 @@ public function getDelayed(array $keys, array $options = array()) return $eventRs->last(); } - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - - // init search keys - $search = array(); - foreach ($keys as $key) { - $search[] = $prefix.$key; - } - - // we don't need the CAS token - $withCas = false; + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); // redirect callback if (isset($options['callback'])) { @@ -901,11 +882,7 @@ public function getDelayed(array $keys, array $options = array()) $select = & $options['select']; // handle selected key - if (in_array('key', $select)) { - $namespaceSeparator = $baseOptions->getNamespaceSeparator(); - $prefixL = strlen($options['namespace'] . $namespaceSeparator); - $item['key'] = substr($item['key'], $prefixL); - } else { + if (!in_array('key', $select)) { unset($item['key']); } @@ -917,11 +894,11 @@ public function getDelayed(array $keys, array $options = array()) call_user_func($options['callback'], $item); }; - if (!$this->memcached->getDelayed($search, false, $cb)) { + if (!$this->memcached->getDelayed($keys, false, $cb)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } } else { - if (!$this->memcached->getDelayed($search)) { + if (!$this->memcached->getDelayed($keys)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -965,11 +942,7 @@ public function fetch() $select = & $this->stmtOptions['select']; // handle selected key - if (in_array('key', $select)) { - $namespaceSeparator = $this->getOptions()->getNamespaceSeparator(); - $prefixL = strlen($this->stmtOptions['namespace'] . $namespaceSeparator); - $result['key'] = substr($result['key'], $prefixL); - } else { + if (!in_array('key', $select)) { unset($result['key']); } @@ -998,10 +971,7 @@ public function fetch() */ public function fetchAll() { - $prefixL = strlen($this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator()); - $result = $this->memcached->fetchAll(); - if ($result === false) { throw new Exception\RuntimeException("Memcached::fetchAll() failed"); } @@ -1009,9 +979,7 @@ public function fetchAll() $select = $this->stmtOptions['select']; foreach ($result as &$elem) { - if (in_array('key', $select)) { - $elem['key'] = substr($elem['key'], $prefixL); - } else { + if (!in_array('key', $select)) { unset($elem['key']); } } @@ -1112,7 +1080,6 @@ public function getCapabilities() 'expiredRead' => false, 'maxKeyLength' => 255, 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), 'iterable' => false, 'clearAllNamespaces' => true, 'clearByNamespace' => false, diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index 6dbebb322..0db7a4d6b 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -37,7 +37,7 @@ class MemcachedOptions extends AdapterOptions { /** * Map of option keys to \Memcached options - * + * * @var array */ private $optionsMap = array( @@ -51,7 +51,6 @@ class MemcachedOptions extends AdapterOptions 'libketama_compatible' => MemcachedResource::OPT_LIBKETAMA_COMPATIBLE, 'no_block' => MemcachedResource::OPT_NO_BLOCK, 'poll_timeout' => MemcachedResource::OPT_POLL_TIMEOUT, - 'prefix_key' => MemcachedResource::OPT_PREFIX_KEY, 'recv_timeout' => MemcachedResource::OPT_RECV_TIMEOUT, 'retry_timeout' => MemcachedResource::OPT_RETRY_TIMEOUT, 'send_timeout' => MemcachedResource::OPT_SEND_TIMEOUT, @@ -60,176 +59,188 @@ class MemcachedOptions extends AdapterOptions 'socket_recv_size' => MemcachedResource::OPT_SOCKET_RECV_SIZE, 'socket_send_size' => MemcachedResource::OPT_SOCKET_SEND_SIZE, 'tcp_nodelay' => MemcachedResource::OPT_TCP_NODELAY, + + // The prefix_key act as namespace an will be set directly + // 'prefix_key' => MemcachedResource::OPT_PREFIX_KEY, ); /** * Memcached server address - * - * @var string + * + * @var string */ protected $server = 'localhost'; - + /** * Memcached port - * + * * @var integer */ protected $port = 11211; - + /** * Whether or not to enable binary protocol for communication with server - * + * * @var bool */ protected $binaryProtocol = false; /** * Enable or disable buffered I/O - * + * * @var bool */ protected $bufferWrites = false; /** * Whether or not to cache DNS lookups - * + * * @var bool */ protected $cacheLookups = false; /** * Whether or not to use compression - * + * * @var bool */ protected $compression = true; /** * Time at which to issue connection timeout, in ms - * + * * @var int */ protected $connectTimeout = 1000; /** * Server distribution algorithm - * + * * @var int */ protected $distribution = MemcachedResource::DISTRIBUTION_MODULA; /** * Hashing algorithm to use - * + * * @var int */ protected $hash = MemcachedResource::HASH_DEFAULT; /** * Whether or not to enable compatibility with libketama-like behavior. - * + * * @var bool */ protected $libketamaCompatible = false; - /** - * Namespace separator - * - * @var string - */ - protected $namespaceSeparator = ':'; - /** * Whether or not to enable asynchronous I/O - * + * * @var bool */ protected $noBlock = false; /** * Timeout for connection polling, in ms - * + * * @var int */ protected $pollTimeout = 0; - /** - * Prefix to use with keys - * - * @var string - */ - protected $prefixKey = ''; - /** * Maximum allowed time for a recv operation, in ms - * + * * @var int */ protected $recvTimeout = 0; /** * Time to wait before retrying a connection, in seconds - * + * * @var int */ protected $retryTimeout = 0; /** * Maximum allowed time for a send operation, in ms - * + * * @var int */ protected $sendTimeout = 0; /** * Serializer to use - * + * * @var int */ protected $serializer = MemcachedResource::SERIALIZER_PHP; /** * Maximum number of server connection errors - * + * * @var int */ protected $serverFailureLimit = 0; /** * Maximum socket send buffer in bytes - * + * * @var int */ protected $socketSendSize; /** * Maximum socket recv buffer in bytes - * + * * @var int */ protected $socketRecvSize; /** * Whether or not to enable no-delay feature for connecting sockets - * + * * @var bool */ protected $tcpNodelay = false; + /** + * Set namespace. + * + * The option Memcached::OPT_PREFIX_KEY will be used as the namespace. + * It can't be longer than 128 characters. + * + * @see AdapterOptions::setNamespace() + * @see MemcachedOptions::setPrefixKey() + */ + public function setNamespace($namespace) + { + $namespace = (string)$namespace; + + if (128 < strlen($namespace)) { + throw new Exception\InvalidArgumentException(sprintf( + '%s expects a prefix key of no longer than 128 characters', + __METHOD__ + )); + } + + return parent::setNamespace($namespace); + } + public function setServer($server) { $this->server= $server; return $this; } - + public function getServer() { return $this->server; } - + public function setPort($port) { - if ((!is_int($port) && !is_numeric($port)) + if ((!is_int($port) && !is_numeric($port)) || 0 > $port ) { throw new Exception\InvalidArgumentException(sprintf( @@ -237,18 +248,18 @@ public function setPort($port) __METHOD__ )); } - + $this->port= $port; return $this; } - + public function getPort() { return $this->port; } - + /** - * Set flag indicating whether or not to enable binary protocol for + * Set flag indicating whether or not to enable binary protocol for * communication with server * * @param bool $binaryProtocol @@ -259,7 +270,7 @@ public function setBinaryProtocol($binaryProtocol) $this->binaryProtocol = (bool) $binaryProtocol; return $this; } - + /** * Whether or not to enable binary protocol for communication with server * @@ -281,7 +292,7 @@ public function setBufferWrites($bufferWrites) $this->bufferWrites = (bool) $bufferWrites; return $this; } - + /** * Whether or not buffered I/O is enabled * @@ -303,7 +314,7 @@ public function setCacheLookups($cacheLookups) $this->cacheLookups = (bool) $cacheLookups; return $this; } - + /** * Whether or not to cache DNS lookups * @@ -325,7 +336,7 @@ public function setCompression($compression) $this->compression = (bool) $compression; return $this; } - + /** * Whether or not compression is enabled * @@ -344,7 +355,7 @@ public function getCompression() */ public function setConnectTimeout($connectTimeout) { - if ((!is_int($connectTimeout) && !is_numeric($connectTimeout)) + if ((!is_int($connectTimeout) && !is_numeric($connectTimeout)) || 0 > $connectTimeout ) { throw new Exception\InvalidArgumentException(sprintf( @@ -356,7 +367,7 @@ public function setConnectTimeout($connectTimeout) $this->connectTimeout = (int) $connectTimeout; return $this; } - + /** * Get connection timeout value * @@ -388,7 +399,7 @@ public function setDistribution($distribution) $this->distribution = $distribution; return $this; } - + /** * Get server distribution algorithm * @@ -427,7 +438,7 @@ public function setHash($hash) $this->hash = $hash; return $this; } - + /** * Get hash algorithm * @@ -449,7 +460,7 @@ public function setLibketamaCompatible($libketamaCompatible) $this->libketamaCompatible = (bool) $libketamaCompatible; return $this; } - + /** * Whether or not to enable libketama compatibility * @@ -460,28 +471,6 @@ public function getLibketamaCompatible() return $this->libketamaCompatible; } - /** - * Set namespace separator - * - * @param string $separator - * @return MemcachedOptions - */ - public function setNamespaceSeparator($separator) - { - $this->namespaceSeparator = (string) $separator; - return $this; - } - - /** - * Get namespace separator - * - * @return string - */ - public function getNamespaceSeparator() - { - return $this->namespaceSeparator; - } - /** * Set flag indicating whether or not to enable asynchronous I/O * @@ -493,7 +482,7 @@ public function setNoBlock($noBlock) $this->noBlock = (bool) $noBlock; return $this; } - + /** * Whether or not to enable asynchronous I/O * @@ -512,7 +501,7 @@ public function getNoBlock() */ public function setPollTimeout($pollTimeout) { - if ((!is_int($pollTimeout) && !is_numeric($pollTimeout)) + if ((!is_int($pollTimeout) && !is_numeric($pollTimeout)) || 0 > $pollTimeout ) { throw new Exception\InvalidArgumentException(sprintf( @@ -524,7 +513,7 @@ public function setPollTimeout($pollTimeout) $this->pollTimeout = (int) $pollTimeout; return $this; } - + /** * Get connection polling timeout value * @@ -538,36 +527,26 @@ public function getPollTimeout() /** * Set prefix for keys * + * The prefix key act as namespace. + * * @param string $prefixKey * @return MemcachedOptions */ public function setPrefixKey($prefixKey) { - if (!is_string($prefixKey)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a string', - __METHOD__ - )); - } - if (128 < strlen($prefixKey)) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a prefix key of no longer than 128 characters', - __METHOD__ - )); - } - - $this->prefixKey = $prefixKey; - return $this; + return $this->setNamespace($prefixKey); } - + /** * Get prefix key * + * The prefix key act as namespace. + * * @return string */ public function getPrefixKey() { - return $this->prefixKey; + return $this->getNamespace(); } /** @@ -578,7 +557,7 @@ public function getPrefixKey() */ public function setRecvTimeout($recvTimeout) { - if ((!is_int($recvTimeout) && !is_numeric($recvTimeout)) + if ((!is_int($recvTimeout) && !is_numeric($recvTimeout)) || 0 > $recvTimeout ) { throw new Exception\InvalidArgumentException(sprintf( @@ -590,7 +569,7 @@ public function setRecvTimeout($recvTimeout) $this->recvTimeout = (int) $recvTimeout; return $this; } - + /** * Get recv timeout value * @@ -609,7 +588,7 @@ public function getRecvTimeout() */ public function setRetryTimeout($retryTimeout) { - if ((!is_int($retryTimeout) && !is_numeric($retryTimeout)) + if ((!is_int($retryTimeout) && !is_numeric($retryTimeout)) || 0 > $retryTimeout ) { throw new Exception\InvalidArgumentException(sprintf( @@ -621,7 +600,7 @@ public function setRetryTimeout($retryTimeout) $this->retryTimeout = (int) $retryTimeout; return $this; } - + /** * Get retry timeout value, in seconds * @@ -640,7 +619,7 @@ public function getRetryTimeout() */ public function setSendTimeout($sendTimeout) { - if ((!is_int($sendTimeout) && !is_numeric($sendTimeout)) + if ((!is_int($sendTimeout) && !is_numeric($sendTimeout)) || 0 > $sendTimeout ) { throw new Exception\InvalidArgumentException(sprintf( @@ -652,7 +631,7 @@ public function setSendTimeout($sendTimeout) $this->sendTimeout = (int) $sendTimeout; return $this; } - + /** * Get send timeout value * @@ -703,7 +682,7 @@ public function setSerializer($serializer) $this->serializer = $serializer; return $this; } - + /** * Get serializer * @@ -722,7 +701,7 @@ public function getSerializer() */ public function setServerFailureLimit($serverFailureLimit) { - if ((!is_int($serverFailureLimit) && !is_numeric($serverFailureLimit)) + if ((!is_int($serverFailureLimit) && !is_numeric($serverFailureLimit)) || 0 > $serverFailureLimit ) { throw new Exception\InvalidArgumentException(sprintf( @@ -734,7 +713,7 @@ public function setServerFailureLimit($serverFailureLimit) $this->serverFailureLimit = (int) $serverFailureLimit; return $this; } - + /** * Get maximum server failures allowed * @@ -756,8 +735,8 @@ public function setSocketSendSize($socketSendSize) if ($socketSendSize === null) { return $this; } - - if ((!is_int($socketSendSize) && !is_numeric($socketSendSize)) + + if ((!is_int($socketSendSize) && !is_numeric($socketSendSize)) || 0 > $socketSendSize ) { throw new Exception\InvalidArgumentException(sprintf( @@ -769,7 +748,7 @@ public function setSocketSendSize($socketSendSize) $this->socketSendSize = (int) $socketSendSize; return $this; } - + /** * Get maximum socket send buffer in bytes * @@ -791,8 +770,8 @@ public function setSocketRecvSize($socketRecvSize) if ($socketRecvSize === null) { return $this; } - - if ((!is_int($socketRecvSize) && !is_numeric($socketRecvSize)) + + if ((!is_int($socketRecvSize) && !is_numeric($socketRecvSize)) || 0 > $socketRecvSize ) { throw new Exception\InvalidArgumentException(sprintf( @@ -804,7 +783,7 @@ public function setSocketRecvSize($socketRecvSize) $this->socketRecvSize = (int) $socketRecvSize; return $this; } - + /** * Get maximum socket recv buffer in bytes * @@ -826,7 +805,7 @@ public function setTcpNodelay($tcpNodelay) $this->tcpNodelay = (bool) $tcpNodelay; return $this; } - + /** * Whether or not to enable no-delay feature when connecting sockets * @@ -839,7 +818,7 @@ public function getTcpNodelay() /** * Get map of option keys to \Memcached constants - * + * * @return array */ public function getOptionsMap() From f8948e4f5020dfcff1b99a5c27e29e3eda0a901c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 23 Dec 2011 23:55:09 +0100 Subject: [PATCH 171/311] fixed AdapterOptions::setNamespace --- src/Storage/Adapter/AdapterOptions.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 20bb0101a..6db8295f2 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -86,7 +86,7 @@ class AdapterOptions extends Options /** * Cast to array - * + * * @return array */ public function toArray() @@ -178,7 +178,7 @@ public function getKeyPattern() */ public function setNamespace($namespace) { - $nameapace = (string)$namespace; + $namespace = (string)$namespace; if ($namespace === '') { throw new Exception\InvalidArgumentException('No namespace given'); } From 7295bb100032075aecb3245c19c8b9a12db4ca33 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 24 Dec 2011 00:03:53 +0100 Subject: [PATCH 172/311] fixed MemoryTest::testThrowOutOfCapacityException --- test/Storage/Adapter/MemoryTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index 42a599ab2..d999f40d6 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -46,7 +46,7 @@ public function setUp() public function testThrowOutOfCapacityException() { - $this->_options->setMemoryLimit(memory_get_usage(true) + 5); + $this->_options->setMemoryLimit(memory_get_usage(true) - 8); $this->setExpectedException('Zend\Cache\Exception\OutOfCapacityException'); $this->_storage->addItem('test', 'test'); From 27690213bb739a9fab4a048f4894cc5cce4dae5a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 24 Dec 2011 01:36:04 +0100 Subject: [PATCH 173/311] added plug-in IgnoreUserAbort --- src/Storage/Plugin/IgnoreUserAbort.php | 183 ++++++++++++++++++++ src/Storage/Plugin/PluginOptions.php | 29 ++++ src/Storage/Plugin/Serializer.php | 16 +- src/Storage/PluginLoader.php | 8 +- test/Storage/Plugin/IgnoreUserAbortTest.php | 130 ++++++++++++++ 5 files changed, 354 insertions(+), 12 deletions(-) create mode 100644 src/Storage/Plugin/IgnoreUserAbort.php create mode 100644 test/Storage/Plugin/IgnoreUserAbortTest.php diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php new file mode 100644 index 000000000..98cef221e --- /dev/null +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -0,0 +1,183 @@ +handles[$index])) { + throw new Exception\LogicException('Plugin already attached'); + } + + $handles = array(); + $this->handles[$index] = & $handles; + + $cbOnBefore = array($this, 'onBefore'); + $cbOnAfter = array($this, 'onAfter'); + + $handles[] = $events->attach('setItem.pre', $cbOnBefore); + $handles[] = $events->attach('setItem.post', $cbOnAfter); + $handles[] = $events->attach('setItem.exception', $cbOnAfter); + + $handles[] = $events->attach('setItems.pre', $cbOnBefore); + $handles[] = $events->attach('setItems.post', $cbOnAfter); + $handles[] = $events->attach('setItems.exception', $cbOnAfter); + + $handles[] = $events->attach('addItem.pre', $cbOnBefore); + $handles[] = $events->attach('addItem.post', $cbOnAfter); + $handles[] = $events->attach('addItem.exception', $cbOnAfter); + + $handles[] = $events->attach('addItems.pre', $cbOnBefore); + $handles[] = $events->attach('addItems.post', $cbOnAfter); + $handles[] = $events->attach('addItems.exception', $cbOnAfter); + + $handles[] = $events->attach('replaceItem.pre', $cbOnBefore); + $handles[] = $events->attach('replaceItem.post', $cbOnAfter); + $handles[] = $events->attach('replaceItem.exception', $cbOnAfter); + + $handles[] = $events->attach('replaceItems.pre', $cbOnBefore); + $handles[] = $events->attach('replaceItems.post', $cbOnAfter); + $handles[] = $events->attach('replaceItems.exception', $cbOnAfter); + + $handles[] = $events->attach('checkAndSetItem.pre', $cbOnBefore); + $handles[] = $events->attach('checkAndSetItem.post', $cbOnAfter); + $handles[] = $events->attach('checkAndSetItem.exception', $cbOnAfter); + + // increment / decrement item(s) + $handles[] = $events->attach('incrementItem.pre', $cbOnBefore); + $handles[] = $events->attach('incrementItem.post', $cbOnAfter); + $handles[] = $events->attach('incrementItem.exception', $cbOnAfter); + + $handles[] = $events->attach('incrementItems.pre', $cbOnBefore); + $handles[] = $events->attach('incrementItems.post', $cbOnAfter); + $handles[] = $events->attach('incrementItems.exception', $cbOnAfter); + + $handles[] = $events->attach('decrementItem.pre', $cbOnBefore); + $handles[] = $events->attach('decrementItem.post', $cbOnAfter); + $handles[] = $events->attach('decrementItem.exception', $cbOnAfter); + + $handles[] = $events->attach('decrementItems.pre', $cbOnBefore); + $handles[] = $events->attach('decrementItems.post', $cbOnAfter); + $handles[] = $events->attach('decrementItems.exception', $cbOnAfter); + + return $this; + } + + /** + * Detach + * + * @param EventCollection $events + * @return Serializer + * @throws Exception\LogicException + */ + public function detach(EventCollection $events) + { + $index = spl_object_hash($events); + if (!isset($this->handles[$index])) { + throw new Exception\LogicException('Plugin not attached'); + } + + // detach all handles of this index + foreach ($this->handles[$index] as $handle) { + $events->detach($handle); + } + + // remove all detached handles + unset($this->handles[$index]); + + return $this; + } + + /** + * Activate ignore_user_abort if not already done + * and save the target who activated it. + * + * @param Event $event + * @return void + */ + public function onBefore(Event $event) + { + if ($this->activatedTarget === null && !ignore_user_abort(true)) { + $this->activatedTarget = $event->getTarget(); + } + } + + /** + * Reset ignore_user_abort if it's activated and if it's the same target + * who activated it. + * + * If exit_on_abort is enabled and the connection has been aborted + * exit the script. + * + * @param Event $event + * @return void + */ + public function onAfter(Event $event) + { + if ($this->activatedTarget === $event->getTarget()) { + // exit if connection aborted + if ($this->getOptions()->getExitOnAbort() && connection_aborted()) { + exit; + } + + // reset ignore_user_abort + ignore_user_abort(false); + + // remove activated target + $this->activatedTarget = null; + } + } +} diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index 61ac53e5a..df3992c4e 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -56,6 +56,13 @@ class PluginOptions extends Options */ protected $exceptionCallback; + /** + * Used by: + * - IgnoreUserAbort + * @var boolean + */ + protected $exitOnAbort = true; + /** * Used by: * - OptimizeByFactor @@ -171,6 +178,28 @@ public function getExceptionCallback() return $this->exceptionCallback; } + /** + * Exit if connection aborted and ignore_user_abort is disabled. + * + * @param boolean $exitOnAbort + * @return PluginOptions + */ + public function setExitOnAbort($exitOnAbort) + { + $this->exitOnAbort = (bool) $exitOnAbort; + return $this; + } + + /** + * Exit if connection aborted and ignore_user_abort is disabled. + * + * @return boolean + */ + public function getExitOnAbort() + { + return $this->exitOnAbort; + } + /** * Set automatic optimizing factor * diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 135a439ab..f0c37bf5f 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -237,13 +237,13 @@ public function onIncrementItemPre(Event $event) $params = $event->getParams(); $token = null; $oldValue = $cache->getItem( - $params['key'], + $params['key'], array('token' => &$token) + $params['options'] ); return $cache->checkAndSetItem( - $token, - $oldValue + $params['value'], - $params['key'], + $token, + $oldValue + $params['value'], + $params['key'], $params['options'] ); } @@ -285,13 +285,13 @@ public function onDecrementItemPre(Event $event) $params = $event->getParams(); $token = null; $oldValue = $cache->getItem( - $params['key'], + $params['key'], array('token' => &$token) + $params['options'] ); return $cache->checkAndSetItem( - $token, - $oldValue - $params['value'], - $params['key'], + $token, + $oldValue - $params['value'], + $params['key'], $params['options'] ); } diff --git a/src/Storage/PluginLoader.php b/src/Storage/PluginLoader.php index 6a3c01519..147ec86f9 100644 --- a/src/Storage/PluginLoader.php +++ b/src/Storage/PluginLoader.php @@ -42,11 +42,11 @@ class PluginLoader extends PluginClassLoader protected $plugins = array( 'clear_by_factor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', 'clearbyfactor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', - //'exception_handler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', - //'exceptionhandler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', + 'exception_handler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', + 'exceptionhandler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', //'filter' => 'Zend\Cache\Storage\Plugin\Filter', - //'ignore_user_abort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', - //'ignoreuserabort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', + 'ignore_user_abort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', + 'ignoreuserabort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', //'key_filter' => 'Zend\Cache\Storage\Plugin\KeyFilter', //'keyfilter' => 'Zend\Cache\Storage\Plugin\KeyFilter', //'levels' => 'Zend\Cache\Storage\Plugin\Levels', diff --git a/test/Storage/Plugin/IgnoreUserAbortTest.php b/test/Storage/Plugin/IgnoreUserAbortTest.php new file mode 100644 index 000000000..97b8235c5 --- /dev/null +++ b/test/Storage/Plugin/IgnoreUserAbortTest.php @@ -0,0 +1,130 @@ +_adapter = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); + $this->_options = new Cache\Storage\Plugin\PluginOptions(); + $this->_plugin = new Cache\Storage\Plugin\IgnoreUserAbort(); + $this->_plugin->setOptions($this->_options); + } + + public function testAddPlugin() + { + $this->_adapter->addPlugin($this->_plugin); + + // check attached callbacks + $expectedListeners = array( + 'setItem.pre' => 'onBefore', + 'setItem.post' => 'onAfter', + 'setItem.exception' => 'onAfter', + + 'setItems.pre' => 'onBefore', + 'setItems.post' => 'onAfter', + 'setItems.exception' => 'onAfter', + + 'addItem.pre' => 'onBefore', + 'addItem.post' => 'onAfter', + 'addItem.exception' => 'onAfter', + + 'addItems.pre' => 'onBefore', + 'addItems.post' => 'onAfter', + 'addItems.exception' => 'onAfter', + + 'replaceItem.pre' => 'onBefore', + 'replaceItem.post' => 'onAfter', + 'replaceItem.exception' => 'onAfter', + + 'replaceItems.pre' => 'onBefore', + 'replaceItems.post' => 'onAfter', + 'replaceItems.exception' => 'onAfter', + + 'checkAndSetItem.pre' => 'onBefore', + 'checkAndSetItem.post' => 'onAfter', + 'checkAndSetItem.exception' => 'onAfter', + + 'incrementItem.pre' => 'onBefore', + 'incrementItem.post' => 'onAfter', + 'incrementItem.exception' => 'onAfter', + + 'incrementItems.pre' => 'onBefore', + 'incrementItems.post' => 'onAfter', + 'incrementItems.exception' => 'onAfter', + + 'decrementItem.pre' => 'onBefore', + 'decrementItem.post' => 'onAfter', + 'decrementItem.exception' => 'onAfter', + + 'decrementItems.pre' => 'onBefore', + 'decrementItems.post' => 'onAfter', + 'decrementItems.exception' => 'onAfter', + ); + foreach ($expectedListeners as $eventName => $expectedCallbackMethod) { + $listeners = $this->_adapter->events()->getListeners($eventName); + + // event should attached only once + $this->assertSame(1, $listeners->count()); + + // check expected callback method + $cb = $listeners->top()->getCallback(); + $this->assertArrayHasKey(0, $cb); + $this->assertSame($this->_plugin, $cb[0]); + $this->assertArrayHasKey(1, $cb); + $this->assertSame($expectedCallbackMethod, $cb[1]); + } + } + + public function testRemovePlugin() + { + $this->_adapter->addPlugin($this->_plugin); + $this->_adapter->removePlugin($this->_plugin); + + // no events should be attached + $this->assertEquals(0, count($this->_adapter->events()->getEvents())); + } + +} From 346099630dd866645475712135a3bcd52951140a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 2 Jan 2012 23:18:43 +0100 Subject: [PATCH 174/311] filesystem cache adapter: - the option file_blocking isn't available on windows - small speed-up on overwrite a file on disabled file_blocking by only truncate file to the length of new data - don't get fileatime & filectime on getKeyInfo, instead get this in internalGetMetadata - don't buffer the last used metadata, only the result of getKeyInfo --- src/Storage/Adapter/Filesystem.php | 79 ++++++++++------------- src/Storage/Adapter/FilesystemOptions.php | 38 +++++++---- test/Storage/Adapter/FilesystemTest.php | 47 ++++++++++++-- 3 files changed, 103 insertions(+), 61 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 049a5ab72..71c145c65 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -53,18 +53,15 @@ class Filesystem extends AbstractAdapter protected $stmtMatch = null; /** - * Buffer vars + * Last buffered identified of internal method getKeyInfo() * * @var string|null */ protected $lastInfoId = null; /** - * @var array|bool|null - */ - protected $lastInfoAll = null; - - /** + * Buffered result of internal method getKeyInfo() + * * @var array|null */ protected $lastInfo = null; @@ -80,8 +77,8 @@ class Filesystem extends AbstractAdapter */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable + if (!is_array($options) + && !$options instanceof Traversable && !$options instanceof FilesystemOptions ) { throw new Exception\InvalidArgumentException(sprintf( @@ -319,13 +316,7 @@ public function getMetadata($key, array $options = array()) clearstatcache(); } - $lastInfoId = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if ($this->lastInfoId == $lastInfoId && $this->lastInfoAll) { - return $this->lastInfoAll; - } - - $this->lastInfoAll = $result = $this->internalGetMetadata($key, $options); - + $result = $this->internalGetMetadata($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); @@ -1320,9 +1311,10 @@ protected function internalHasItem($key, array &$options) * @return array|bool * @throws ItemNotFoundException */ - protected function internalGetMetadata($key, array &$options) + protected function internalGetMetadata($key, array &$options) { - $keyInfo = $this->getKeyInfo($key, $options['namespace']); + $baseOptions = $this->getOptions(); + $keyInfo = $this->getKeyInfo($key, $options['namespace']); if (!$keyInfo) { if ($options['ignore_missing_items']) { return false; @@ -1331,6 +1323,14 @@ protected function internalGetMetadata($key, array &$options) } } + if (!$baseOptions->getNoCtime()) { + $keyInfo['ctime'] = filectime($keyInfo['filespec'] . '.dat'); + } + + if (!$baseOptions->getNoAtime()) { + $keyInfo['atime'] = fileatime($keyInfo['filespec'] . '.dat'); + } + if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) ) { return $keyInfo + $info; } @@ -1537,7 +1537,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { - if (!isset($info['tags']) + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) > 0 ) { continue; @@ -1545,7 +1545,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_NO_TAGS mode -> check if no given tag available in current cache } elseif(($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS) { - if (isset($info['tags']) + if (isset($info['tags']) && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags']) ) { continue; @@ -1553,7 +1553,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { - if (!isset($info['tags']) + if (!isset($info['tags']) || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags']) ) { continue; @@ -1633,20 +1633,11 @@ protected function getKeyInfo($key, $ns) } $this->lastInfoId = $lastInfoId; - $this->lastInfoAll = null; $this->lastInfo = array( 'filespec' => $filespec, 'mtime' => $filemtime, ); - if (!$options->getNoCtime()) { - $this->lastInfo['ctime'] = filectime($filespec . '.dat'); - } - - if (!$options->getNoAtime()) { - $this->lastInfo['atime'] = fileatime($filespec . '.dat'); - } - return $this->lastInfo; } @@ -1686,7 +1677,7 @@ protected function getFileSpec($key, $ns) * @return array|boolean The info array or false if file wasn't found * @throws Exception\RuntimeException */ - protected function readInfoFile($file) + protected function readInfoFile($file) { if (!file_exists($file)) { return false; @@ -1718,10 +1709,10 @@ protected function getFileContent($file) if ($this->getOptions()->getFileLocking()) { set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { $message = sprintf( - 'Error getting contents from file "%s" (in %s@%d): %s', - $file, - $errfile, - $errline, + 'Error getting contents from file "%s" (in %s@%d): %s', + $file, + $errfile, + $errline, $errstr ); throw new Exception\RuntimeException($message, $errno); @@ -1730,17 +1721,17 @@ protected function getFileContent($file) restore_error_handler(); if ($fp === false) { throw new Exception\RuntimeException(sprintf( - 'Unknown error getting contents from file "%s"', + 'Unknown error getting contents from file "%s"', $file )); } set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { $message = sprintf( - 'Error locking file "%s" (in %s@%d): %s', - $file, - $errfile, - $errline, + 'Error locking file "%s" (in %s@%d): %s', + $file, + $errfile, + $errline, $errstr ); throw new Exception\RuntimeException($message, $errno); @@ -1822,14 +1813,14 @@ protected function putFileContent($file, $data) return false; } - if (!ftruncate($fp, 0)) { - throw new Exception\RuntimeException('Unable to truncate cache file'); - } - if (!fwrite($fp, $data)) { throw new Exception\RuntimeException('Unable to write cache file'); } + if (!ftruncate($fp, strlen($data))) { + throw new Exception\RuntimeException('Unable to truncate cache file'); + } + flock($fp, \LOCK_UN); fclose($fp); } else { @@ -1859,7 +1850,7 @@ protected function putFileContent($file, $data) * @return void * @throw RuntimeException */ - protected function unlink($file) + protected function unlink($file) { // If file does not exist, nothing to do if (!file_exists($file)) { diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index c09ce6aae..d1dbc4664 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -37,7 +37,7 @@ class FilesystemOptions extends AdapterOptions { /** * The adapter using these options - * + * * @var null|Filesystem */ protected $adapter; @@ -74,8 +74,9 @@ class FilesystemOptions extends AdapterOptions /** * Block writing files until writing by another process finished. * - * NOTE1: this only attempts if fileLocking is enabled - * NOTE3: if disabled writing operations return false in part of a locked file + * NOTE: this only attempts if fileLocking is enabled + * NOTE: if disabled writing operations return false in part of a locked file + * NOTE: This option can't be disabled on windows * * @var boolean */ @@ -152,8 +153,8 @@ class FilesystemOptions extends AdapterOptions /** * Filesystem adapter using this instance - * - * @param Filesystem $filesystem + * + * @param Filesystem $filesystem * @return FilesystemOptions */ public function setAdapter(Filesystem $filesystem) @@ -316,19 +317,34 @@ public function getDirUmask() } /** - * Set file blocking + * Set block writing files until writing by another process finished. + * + * NOTE: this only attempts if fileLocking is enabled + * NOTE: if disabled writing operations return false in part of a locked file + * NOTE: This option can't be disabled on windows * * @param bool $flag * @return FilesystemOptions */ public function setFileBlocking($flag) { + $flag = (bool) $flag; + if ($flag && substr(\PHP_OS, 0, 3) == 'WIN') { + throw new Exception\InvalidArgumentException( + "This option can't be disabled on windows" + ); + } + $this->fileBlocking = (bool) $flag; return $this; } /** - * Get file blocking + * Get block writing files until writing by another process finished. + * + * NOTE: this only attempts if fileLocking is enabled + * NOTE: if disabled writing operations return false in part of a locked file + * NOTE: This option can't be disabled on windows * * @return bool */ @@ -542,9 +558,9 @@ public function getReadControlAlgo() /** * Normalize a umask and optionally apply a callback to it - * - * @param int|string $umask - * @param callable $callback + * + * @param int|string $umask + * @param callable $callback * @return int */ protected function normalizeUmask($umask, $callback = null) @@ -566,7 +582,7 @@ protected function normalizeUmask($umask, $callback = null) * Update target capabilities * * Returns immediately if no adapter is present. - * + * * @return void */ protected function updateCapabilities() diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 7c406a81e..6ed19a8c5 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -264,25 +264,60 @@ public function testSetReadControlAlgoInvalidException() public function testDisabledFileBlocking() { + if (substr(\PHP_OS, 0, 3) == 'WIN') { + $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); + } + $this->_options->setFileLocking(true); $this->_options->setFileBlocking(false); // create cache item and get data file $this->assertTrue($this->_storage->setItem('key', 'value')); - $info = $this->_storage->getMetadata('key'); - $this->assertInternalType('array', $info); - $this->assertArrayHasKey('filespec', $info); - $file = $info['filespec'] . '.dat'; + $meta = $this->_storage->getMetadata('key'); + $this->assertInternalType('array', $meta); + $this->assertArrayHasKey('filespec', $meta); + $file = $meta['filespec'] . '.dat'; + + /****************** + * first test failed on a locked item + */ - // open file and create a write lock - $fp = @fopen($file, 'w+'); + // open file and create a lock + $fp = @fopen($file, 'cb'); $this->assertInternalType('resource', $fp); flock($fp, LOCK_EX); // rewriting file should fail in part of open lock $this->assertFalse($this->_storage->setItem('key', 'lock')); + // close the lock flock($fp, LOCK_UN); fclose($fp); } + + public function testGetMetadataWithCtime() + { + $this->_options->setNoCtime(false); + + $this->assertTrue($this->_storage->setItem('test', 'v')); + + $meta = $this->_storage->getMetadata('test'); + $this->assertInternalType('array', $meta); + + $expectedCtime = filectime($meta['filespec'] . '.dat'); + $this->assertEquals($expectedCtime, $meta['ctime']); + } + + public function testGetMetadataWithAtime() + { + $this->_options->setNoAtime(false); + + $this->assertTrue($this->_storage->setItem('test', 'v')); + + $meta = $this->_storage->getMetadata('test'); + $this->assertInternalType('array', $meta); + + $expectedAtime = fileatime($meta['filespec'] . '.dat'); + $this->assertEquals($expectedAtime, $meta['atime']); + } } From 91f1a0a56a38223abb6909dcd32a261b6f34b800 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 3 Jan 2012 15:20:07 -0600 Subject: [PATCH 175/311] Minor edits, per comments in pull request - s/life/live/g - Import MemcachedException, and use aliases at all times - Remove obsolte call to Utils::getPhpMemoryCapacity() --- src/Storage/Adapter/AbstractAdapter.php | 2 +- src/Storage/Adapter/Memcached.php | 17 +++++++++-------- src/Storage/Adapter/Memory.php | 2 -- 3 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index d499dd24f..d09fca958 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -750,7 +750,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) * * Options: * - ttl optional - * - The time-to-life (Default: ttl of object) + * - The time-to-live (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - select optional diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 561f0f28d..98b6931f7 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -23,6 +23,7 @@ use ArrayObject, Memcached as MemcachedResource, + MemcachedException, stdClass, Traversable, Zend\Cache\Exception, @@ -307,7 +308,7 @@ public function getMetadata($key, array $options = array()) * * Options: * - ttl optional - * - The time-to-life (Default: ttl of object) + * - The time-to-live (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -361,7 +362,7 @@ public function setItem($key, $value, array $options = array()) * * Options: * - ttl optional - * - The time-to-life (Default: ttl of object) + * - The time-to-live (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -412,7 +413,7 @@ public function setItems(array $keyValuePairs, array $options = array()) * * Options: * - ttl optional - * - The time-to-life (Default: ttl of object) + * - The time-to-live (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -466,7 +467,7 @@ public function addItem($key, $value, array $options = array()) * * Options: * - ttl optional - * - The time-to-life (Default: ttl of object) + * - The time-to-live (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -682,7 +683,7 @@ public function removeItems(array $keys, array $options = array()) } return true; - } catch (\MemcachedException $e) { + } catch (MemcachedException $e) { throw new RuntimeException($e->getMessage(), 0, $e); } } @@ -1166,13 +1167,13 @@ protected function expirationTime($ttl) protected function getExceptionByResultCode($code) { switch ($code) { - case \Memcached::RES_SUCCESS: + case MemcachedResource::RES_SUCCESS: throw new Exception\InvalidArgumentException( "The result code '{$code}' (SUCCESS) isn't an error" ); - case \Memcached::RES_NOTFOUND: - case \Memcached::RES_NOTSTORED: + case MemcachedResource::RES_NOTFOUND: + case MemcachedResource::RES_NOTSTORED: return new Exception\ItemNotFoundException($this->memcached->getResultMessage()); default: diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 75d7daa6c..8d470e0df 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -1398,8 +1398,6 @@ public function getCapacity(array $options = array()) 'free' => ($free >= 0) ? $free : 0, ); - $result = Utils::getPhpMemoryCapacity(); - return $this->triggerPost(__FUNCTION__, $args, $result); } From ee1b97921394c23ee1e709097506a109dcf10fee Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 3 Jan 2012 15:22:19 -0600 Subject: [PATCH 176/311] Revert conversion of plugin registry to array - Slow operation, which may be used at different times in cache lifecycle. --- src/Storage/Adapter/AbstractAdapter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index d09fca958..d4bad582d 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -353,11 +353,11 @@ public function removePlugin(Plugin $plugin) /** * Get all registered plugins * - * @return Plugin[] + * @return SplObjectStorage */ public function getPlugins() { - return iterator_to_array($this->getPluginRegistry(), false); + return $this->getPluginRegistry(); } /* reading */ From 34fe76f5be6c07a321f6884f327a8430e2e04b03 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 3 Jan 2012 22:39:36 +0100 Subject: [PATCH 177/311] throw LockedException on write items of a loacked file if file_blocking is disabled --- src/Exception/LockedException.php | 31 +++++++++++++++ src/Storage/Adapter/Filesystem.php | 10 +++-- src/Storage/Adapter/FilesystemOptions.php | 6 +-- test/Storage/Adapter/FilesystemTest.php | 46 ++++++++++++++++++++--- 4 files changed, 82 insertions(+), 11 deletions(-) create mode 100644 src/Exception/LockedException.php diff --git a/src/Exception/LockedException.php b/src/Exception/LockedException.php new file mode 100644 index 000000000..ec0a3df8c --- /dev/null +++ b/src/Exception/LockedException.php @@ -0,0 +1,31 @@ + abort writing + if(!flock($fp, \LOCK_EX | \LOCK_NB, $wouldblock)) { fclose($fp); - return false; + + if ($wouldblock) { + throw new Exception\LockedException("File '{$file}' locked"); + } else { + throw new Exception\RuntimeException("Can't lock file '{$file}'"); + } } if (!fwrite($fp, $data)) { diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index d1dbc4664..f15102ad9 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -75,7 +75,7 @@ class FilesystemOptions extends AdapterOptions * Block writing files until writing by another process finished. * * NOTE: this only attempts if fileLocking is enabled - * NOTE: if disabled writing operations return false in part of a locked file + * NOTE: if disabled writing operations can throw a LockedException * NOTE: This option can't be disabled on windows * * @var boolean @@ -320,7 +320,7 @@ public function getDirUmask() * Set block writing files until writing by another process finished. * * NOTE: this only attempts if fileLocking is enabled - * NOTE: if disabled writing operations return false in part of a locked file + * NOTE: if disabled writing operations can throw a LockedException * NOTE: This option can't be disabled on windows * * @param bool $flag @@ -343,7 +343,7 @@ public function setFileBlocking($flag) * Get block writing files until writing by another process finished. * * NOTE: this only attempts if fileLocking is enabled - * NOTE: if disabled writing operations return false in part of a locked file + * NOTE: if disabled writing operations can throw a LockedException * NOTE: This option can't be disabled on windows * * @return bool diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 6ed19a8c5..2c96244bf 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -279,7 +279,7 @@ public function testDisabledFileBlocking() $file = $meta['filespec'] . '.dat'; /****************** - * first test failed on a locked item + * first test with exclusive lock */ // open file and create a lock @@ -288,11 +288,47 @@ public function testDisabledFileBlocking() flock($fp, LOCK_EX); // rewriting file should fail in part of open lock - $this->assertFalse($this->_storage->setItem('key', 'lock')); + try { + $this->_storage->setItem('key', 'lock'); + + // close + flock($fp, LOCK_UN); + fclose($fp); + + $this->fail('Missing expected exception Zend\Cache\Exception\LockedException'); + } catch (\Zend\Cache\Exception\LockedException $e) { + // expected exception was thrown + + // close + flock($fp, LOCK_UN); + fclose($fp); + } - // close the lock - flock($fp, LOCK_UN); - fclose($fp); + /****************** + * second test with shared lock + */ + + // open file and create a lock + $fp = @fopen($file, 'rb'); + $this->assertInternalType('resource', $fp); + flock($fp, LOCK_SH); + + // rewriting file should fail in part of open lock + try { + $this->_storage->setItem('key', 'lock'); + + // close + flock($fp, LOCK_UN); + fclose($fp); + + $this->fail('Missing expected exception Zend\Cache\Exception\LockedException'); + } catch (\Zend\Cache\Exception\LockedException $e) { + // expected exception was thrown + + // close + flock($fp, LOCK_UN); + fclose($fp); + } } public function testGetMetadataWithCtime() From bccde5a0e88d9a9ed86b74aa676b489f03beb1d8 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 3 Jan 2012 22:51:25 +0100 Subject: [PATCH 178/311] removed unlock + fclose of a not opened file --- src/Storage/Adapter/Filesystem.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 7f4bc211f..5fe83029d 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1766,8 +1766,6 @@ protected function getFileContent($file) // if file locking disabled -> file_get_contents can be used } else { set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - flock($fp, \LOCK_UN); - fclose($fp); $message = sprintf('Error getting file contents for file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); throw new Exception\RuntimeException($message, $errno); }, E_WARNING); From b51dd3a9f60c794ea6c72eace84462412e7a51c9 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 3 Jan 2012 22:54:00 +0100 Subject: [PATCH 179/311] removed wrong reset of old umask --- src/Storage/Adapter/Filesystem.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 5fe83029d..be5e0a286 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1795,7 +1795,6 @@ protected function putFileContent($file, $data) if ($locking && !$blocking) { set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - umask($oldUmask); $message = sprintf('Error opening file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); throw new Exception\RuntimeException($message, $errno); }, E_WARNING); From 6eb551dcd5a2a9a6303f20b22507958720398a3a Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Thu, 5 Jan 2012 14:48:34 -0600 Subject: [PATCH 180/311] [2012] Updated copyrights from 2011 to 2012 - Happy new year! --- src/Exception.php | 4 ++-- src/Exception/BadMethodCallException.php | 4 ++-- src/Exception/ExtensionNotLoadedException.php | 4 ++-- src/Exception/InvalidArgumentException.php | 4 ++-- src/Exception/ItemNotFoundException.php | 4 ++-- src/Exception/LogicException.php | 4 ++-- src/Exception/MissingDependencyException.php | 4 ++-- src/Exception/MissingKeyException.php | 4 ++-- src/Exception/OutOfCapacityException.php | 4 ++-- src/Exception/RuntimeException.php | 4 ++-- src/Exception/UnexpectedValueException.php | 4 ++-- src/Exception/UnsupportedMethodCallException.php | 4 ++-- src/Pattern.php | 4 ++-- src/Pattern/AbstractPattern.php | 4 ++-- src/Pattern/CallbackCache.php | 4 ++-- src/Pattern/CaptureCache.php | 4 ++-- src/Pattern/ClassCache.php | 4 ++-- src/Pattern/ObjectCache.php | 4 ++-- src/Pattern/OutputCache.php | 4 ++-- src/Pattern/PatternOptions.php | 4 ++-- src/PatternBroker.php | 4 ++-- src/PatternFactory.php | 4 ++-- src/PatternLoader.php | 4 ++-- src/Storage/Adapter.php | 4 ++-- src/Storage/Adapter/AbstractAdapter.php | 4 ++-- src/Storage/Adapter/AdapterOptions.php | 4 ++-- src/Storage/Adapter/Apc.php | 4 ++-- src/Storage/Adapter/ApcOptions.php | 4 ++-- src/Storage/Adapter/Filesystem.php | 4 ++-- src/Storage/Adapter/FilesystemOptions.php | 4 ++-- src/Storage/Adapter/Memcached.php | 4 ++-- src/Storage/Adapter/MemcachedOptions.php | 4 ++-- src/Storage/Adapter/Memory.php | 4 ++-- src/Storage/Adapter/MemoryOptions.php | 4 ++-- src/Storage/Adapter/WinCache.php | 4 ++-- src/Storage/Adapter/WinCacheOptions.php | 4 ++-- src/Storage/AdapterBroker.php | 4 ++-- src/Storage/AdapterLoader.php | 4 ++-- src/Storage/Capabilities.php | 4 ++-- src/Storage/Event.php | 4 ++-- src/Storage/ExceptionEvent.php | 4 ++-- src/Storage/Plugin.php | 4 ++-- src/Storage/Plugin/AbstractPlugin.php | 4 ++-- src/Storage/Plugin/ClearByFactor.php | 4 ++-- src/Storage/Plugin/ExceptionHandler.php | 4 ++-- src/Storage/Plugin/IgnoreUserAbort.php | 4 ++-- src/Storage/Plugin/OptimizeByFactor.php | 4 ++-- src/Storage/Plugin/PluginOptions.php | 4 ++-- src/Storage/Plugin/Serializer.php | 4 ++-- src/Storage/PluginBroker.php | 4 ++-- src/Storage/PluginLoader.php | 4 ++-- src/Storage/PostEvent.php | 4 ++-- src/StorageFactory.php | 4 ++-- src/Utils.php | 4 ++-- 54 files changed, 108 insertions(+), 108 deletions(-) diff --git a/src/Exception.php b/src/Exception.php index 27fc3e5b4..975155251 100644 --- a/src/Exception.php +++ b/src/Exception.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Exception diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index 6de22de90..8e5264a89 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class BadMethodCallException extends \BadMethodCallException implements Exception diff --git a/src/Exception/ExtensionNotLoadedException.php b/src/Exception/ExtensionNotLoadedException.php index 37e524798..83ba408c8 100644 --- a/src/Exception/ExtensionNotLoadedException.php +++ b/src/Exception/ExtensionNotLoadedException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ExtensionNotLoadedException extends RuntimeException implements Exception diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index dfb5879b1..883905dde 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class InvalidArgumentException extends \InvalidArgumentException implements Exception diff --git a/src/Exception/ItemNotFoundException.php b/src/Exception/ItemNotFoundException.php index 40bf67bef..0ba6d2e75 100644 --- a/src/Exception/ItemNotFoundException.php +++ b/src/Exception/ItemNotFoundException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ItemNotFoundException extends RuntimeException diff --git a/src/Exception/LogicException.php b/src/Exception/LogicException.php index bc32a0d56..51cad0b89 100644 --- a/src/Exception/LogicException.php +++ b/src/Exception/LogicException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class LogicException extends \LogicException implements Exception diff --git a/src/Exception/MissingDependencyException.php b/src/Exception/MissingDependencyException.php index 0fe855520..41d82b839 100644 --- a/src/Exception/MissingDependencyException.php +++ b/src/Exception/MissingDependencyException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class MissingDependencyException extends RuntimeException diff --git a/src/Exception/MissingKeyException.php b/src/Exception/MissingKeyException.php index 9a2707540..8dc0d70c0 100644 --- a/src/Exception/MissingKeyException.php +++ b/src/Exception/MissingKeyException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class MissingKeyException extends RuntimeException diff --git a/src/Exception/OutOfCapacityException.php b/src/Exception/OutOfCapacityException.php index 8c81c8ff3..1ee0dcd00 100644 --- a/src/Exception/OutOfCapacityException.php +++ b/src/Exception/OutOfCapacityException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class OutOfCapacityException extends \OverflowException implements Exception diff --git a/src/Exception/RuntimeException.php b/src/Exception/RuntimeException.php index 3750490bd..e51c3e585 100644 --- a/src/Exception/RuntimeException.php +++ b/src/Exception/RuntimeException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class RuntimeException extends \RuntimeException implements Exception diff --git a/src/Exception/UnexpectedValueException.php b/src/Exception/UnexpectedValueException.php index d570d768e..05376f649 100644 --- a/src/Exception/UnexpectedValueException.php +++ b/src/Exception/UnexpectedValueException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class UnexpectedValueException extends \UnexpectedValueException implements Exception diff --git a/src/Exception/UnsupportedMethodCallException.php b/src/Exception/UnsupportedMethodCallException.php index 534e25cda..67f46347b 100644 --- a/src/Exception/UnsupportedMethodCallException.php +++ b/src/Exception/UnsupportedMethodCallException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class UnsupportedMethodCallException extends \BadMethodCallException implements Exception diff --git a/src/Pattern.php b/src/Pattern.php index c52341b10..e24022373 100644 --- a/src/Pattern.php +++ b/src/Pattern.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Pattern diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index 888a2929c..1b319858d 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class AbstractPattern implements Pattern diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index 62eed3458..148555d9b 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class CallbackCache extends AbstractPattern diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index d43f9907a..f0176417e 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -28,7 +28,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class CaptureCache extends AbstractPattern diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index 93c599d5c..34f0e7a6d 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ClassCache extends CallbackCache diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index dbcea9547..00089903b 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ObjectCache extends CallbackCache diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index 952a60c16..396bbc987 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class OutputCache extends AbstractPattern diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 0804a891f..1955c510b 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Pattern - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PatternOptions extends Options diff --git a/src/PatternBroker.php b/src/PatternBroker.php index 5b1fe91b8..77292d73a 100644 --- a/src/PatternBroker.php +++ b/src/PatternBroker.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PatternBroker extends PluginBroker diff --git a/src/PatternFactory.php b/src/PatternFactory.php index adf01f084..b07f3781f 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PatternFactory diff --git a/src/PatternLoader.php b/src/PatternLoader.php index dfa355891..b8c3a8462 100644 --- a/src/PatternLoader.php +++ b/src/PatternLoader.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PatternLoader extends PluginClassLoader diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index d4ccc34a6..94dacc043 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -25,7 +25,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Adapter diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index d4bad582d..c75025e82 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -39,7 +39,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class AbstractAdapter implements Adapter diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 6db8295f2..46daef1d2 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class AdapterOptions extends Options diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 32f2838fc..601aa29a2 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -32,7 +32,7 @@ * @package Zend_Cache * @subpackage Zend_Cache_Storage * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Apc extends AbstractAdapter diff --git a/src/Storage/Adapter/ApcOptions.php b/src/Storage/Adapter/ApcOptions.php index 43683fecf..adf39b5f5 100644 --- a/src/Storage/Adapter/ApcOptions.php +++ b/src/Storage/Adapter/ApcOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ApcOptions extends AdapterOptions diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 5f6df9b94..5e0c3f3fb 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -33,7 +33,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Filesystem extends AbstractAdapter diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index c09ce6aae..0f4513d99 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class FilesystemOptions extends AdapterOptions diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 98b6931f7..d216e0931 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -33,7 +33,7 @@ * @package Zend_Cache * @subpackage Zend_Cache_Storage * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @todo Implement the find() method */ diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index 0db7a4d6b..868b4b121 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class MemcachedOptions extends AdapterOptions diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 8d470e0df..00bbc26ea 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -32,7 +32,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Memory extends AbstractAdapter diff --git a/src/Storage/Adapter/MemoryOptions.php b/src/Storage/Adapter/MemoryOptions.php index ed78409eb..f9c7f81ee 100644 --- a/src/Storage/Adapter/MemoryOptions.php +++ b/src/Storage/Adapter/MemoryOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class MemoryOptions extends AdapterOptions diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index a4c0086fc..9f6cd9e2a 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @package Zend_Cache * @subpackage Zend_Cache_Storage * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @todo Implement the find() method */ diff --git a/src/Storage/Adapter/WinCacheOptions.php b/src/Storage/Adapter/WinCacheOptions.php index 171ad9666..e2256e953 100644 --- a/src/Storage/Adapter/WinCacheOptions.php +++ b/src/Storage/Adapter/WinCacheOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class WinCacheOptions extends AdapterOptions diff --git a/src/Storage/AdapterBroker.php b/src/Storage/AdapterBroker.php index bcfe8c64f..a35f7de36 100644 --- a/src/Storage/AdapterBroker.php +++ b/src/Storage/AdapterBroker.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class AdapterBroker extends PluginBroker diff --git a/src/Storage/AdapterLoader.php b/src/Storage/AdapterLoader.php index fed0b0a3e..993dbf8d4 100644 --- a/src/Storage/AdapterLoader.php +++ b/src/Storage/AdapterLoader.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class AdapterLoader extends PluginClassLoader diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 5703be8f9..8c13165ce 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Capabilities diff --git a/src/Storage/Event.php b/src/Storage/Event.php index 4ec07c27e..2bdaebf10 100644 --- a/src/Storage/Event.php +++ b/src/Storage/Event.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -28,7 +28,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Event extends BaseEvent diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index 61668414e..b4c471436 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -28,7 +28,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ExceptionEvent extends Event diff --git a/src/Storage/Plugin.php b/src/Storage/Plugin.php index 3c79127ee..00ce3a46c 100644 --- a/src/Storage/Plugin.php +++ b/src/Storage/Plugin.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -38,7 +38,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ interface Plugin extends ListenerAggregate diff --git a/src/Storage/Plugin/AbstractPlugin.php b/src/Storage/Plugin/AbstractPlugin.php index 1b6d8dd90..b833144c0 100644 --- a/src/Storage/Plugin/AbstractPlugin.php +++ b/src/Storage/Plugin/AbstractPlugin.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class AbstractPlugin implements Plugin diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 1471af3c0..3856058fd 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -31,7 +31,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ClearByFactor extends AbstractPlugin diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 6ec5630b6..6aea248e7 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class ExceptionHandler extends AbstractPlugin diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php index 98cef221e..0fe2f8402 100644 --- a/src/Storage/Plugin/IgnoreUserAbort.php +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class IgnoreUserAbort extends AbstractPlugin diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index d57227022..359ca4ce8 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class OptimizeByFactor extends AbstractPlugin diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index df3992c4e..2afa59ae9 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PluginOptions extends Options diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index f0c37bf5f..69bb72c38 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -33,7 +33,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Serializer extends AbstractPlugin diff --git a/src/Storage/PluginBroker.php b/src/Storage/PluginBroker.php index 930c95e36..40c4b7bcc 100644 --- a/src/Storage/PluginBroker.php +++ b/src/Storage/PluginBroker.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -30,7 +30,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PluginBroker extends BasePluginBroker diff --git a/src/Storage/PluginLoader.php b/src/Storage/PluginLoader.php index 147ec86f9..5f79c9210 100644 --- a/src/Storage/PluginLoader.php +++ b/src/Storage/PluginLoader.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PluginLoader extends PluginClassLoader diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index ff48e7a4f..787ac4288 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -27,7 +27,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class PostEvent extends Event diff --git a/src/StorageFactory.php b/src/StorageFactory.php index f558e9651..82d6bc80f 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -15,7 +15,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -29,7 +29,7 @@ * @category Zend * @package Zend_Cache * @subpackage Storage - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class StorageFactory diff --git a/src/Utils.php b/src/Utils.php index 696740aa7..ef9d097ee 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Utils From 7521514cfcece5590786d5742072e586859358ce Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 6 Jan 2012 16:10:10 +0100 Subject: [PATCH 181/311] use exception aliases all over the time (Zend\Cache\Exception -> Exception | Exception -> BaseException) --- src/Storage/Adapter/Filesystem.php | 71 +++++++++++++++--------------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index be5e0a286..e9bd06d6d 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -24,6 +24,7 @@ use ArrayObject, GlobIterator, stdClass, + Exception as BaseException, Zend\Cache\Exception, Zend\Cache\Storage, Zend\Cache\Storage\Capabilities, @@ -153,7 +154,7 @@ public function getItem($key, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -199,7 +200,7 @@ public function getItems(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -237,7 +238,7 @@ public function hasItem($key, array $options = array()) $result = $this->internalHasItem($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -280,7 +281,7 @@ public function hasItems(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -318,7 +319,7 @@ public function getMetadata($key, array $options = array()) $result = $this->internalGetMetadata($key, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -365,7 +366,7 @@ public function getMetadatas(array $keys, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -409,7 +410,7 @@ public function setItem($key, $value, array $options = array()) $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -450,7 +451,7 @@ public function setItems(array $keyValuePairs, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -495,7 +496,7 @@ public function replaceItem($key, $value, array $options = array()) $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -540,7 +541,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -585,7 +586,7 @@ public function addItem($key, $value, array $options = array()) $result = $this->internalSetItem($key, $value, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -631,7 +632,7 @@ public function addItems(array $keyValuePairs, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -689,7 +690,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -730,7 +731,7 @@ public function touchItem($key, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -768,7 +769,7 @@ public function touchItems(array $keys, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -805,7 +806,7 @@ public function removeItem($key, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -843,7 +844,7 @@ public function removeItems(array $keys, array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -898,13 +899,13 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) $this->stmtGlob = $glob; $this->stmtMatch = $mode; $this->stmtOptions = $options; - } catch (\Exception $e) { + } catch (BaseException $e) { throw new Exception\RuntimeException('Instantiating glob iterator failed', 0, $e); } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -943,7 +944,7 @@ public function fetch() } return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -974,7 +975,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $result = $this->clearByPrefix('', $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1004,7 +1005,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $prefix = $options['namespace'] . $this->getOptions()->getNamespaceSeparator(); $result = $this->clearByPrefix($prefix, $mode, $options); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1040,7 +1041,7 @@ public function optimize(array $options = array()) $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1098,7 +1099,7 @@ public function getCapabilities() $result = $this->capabilities; return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1121,7 +1122,7 @@ public function getCapacity(array $options = array()) $result = Utils::getDiskCapacity($this->getOptions()->getCacheDir()); return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { + } catch (Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } } @@ -1202,7 +1203,7 @@ protected function internalSetItem($key, $value, array &$options) return $ret; - } catch (\Exception $e) { + } catch (Exception $e) { // reset umask on exception umask($oldUmask); throw $e; @@ -1235,7 +1236,7 @@ protected function internalRemoveItem($key, array &$options) * @param $key * @param array $options * @return bool|string - * @throws \Exception|ItemNotFoundException|UnexpectedValueException + * @throws Exception\ItemNotFoundException|Exception\UnexpectedValueException */ protected function internalGetItem($key, array &$options) { @@ -1258,23 +1259,21 @@ protected function internalGetItem($key, array &$options) if ($baseOptions->getReadControl()) { if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) && isset($info['hash'], $info['algo']) + && Utils::generateHash($info['algo'], $data, true) != $info['hash'] ) { - $hashData = Utils::generateHash($info['algo'], $data, true); - if ($hashData != $info['hash']) { - throw new Exception\UnexpectedValueException( - 'ReadControl: Stored hash and computed hash don\'t match' - ); - } + throw new Exception\UnexpectedValueException( + 'ReadControl: Stored hash and computed hash don\'t match' + ); } } return $data; - } catch (\Exception $e) { + } catch (Exception $e) { try { // remove cache file on exception $this->internalRemoveItem($key, $options); - } catch (\Exception $tmp) {} // do not throw remove exception on this point + } catch (Exception $tmp) {} // do not throw remove exception on this point throw $e; } @@ -1498,7 +1497,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $baseOptions->getDirLevel()) . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; $glob = new GlobIterator($find); - } catch (\Exception $e) { + } catch (BaseException $e) { throw new Exception\RuntimeException('Instantiating GlobIterator failed', 0, $e); } From d14bc57b8ac1a17a96656141cbcfeb99242c332b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 6 Jan 2012 19:54:10 +0100 Subject: [PATCH 182/311] quotes --- src/Storage/Adapter/Filesystem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index e9bd06d6d..c5a3b92bc 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1262,7 +1262,7 @@ protected function internalGetItem($key, array &$options) && Utils::generateHash($info['algo'], $data, true) != $info['hash'] ) { throw new Exception\UnexpectedValueException( - 'ReadControl: Stored hash and computed hash don\'t match' + "ReadControl: Stored hash and computed hash don't match" ); } } From 678232dbaef04b9e362fc27bd0beaa96a5aa6bf8 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 6 Jan 2012 13:21:00 -0600 Subject: [PATCH 183/311] Updated copyright from 2011 to 2012 --- src/Exception/LockedException.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Exception/LockedException.php b/src/Exception/LockedException.php index ec0a3df8c..5c2101286 100644 --- a/src/Exception/LockedException.php +++ b/src/Exception/LockedException.php @@ -14,7 +14,7 @@ * * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ @@ -23,7 +23,7 @@ /** * @category Zend * @package Zend_Cache - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) + * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class LockedException extends RuntimeException From 6b358d57b00761b83abfee3443c3f09d7b405ce8 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 14:26:14 +0100 Subject: [PATCH 184/311] initial ZendServer cache adapters --- src/Storage/Adapter/AbstractZendServer.php | 350 ++++++++++++++++++ src/Storage/Adapter/ZendServerDisk.php | 79 ++++ src/Storage/Adapter/ZendServerShm.php | 83 +++++ test/Storage/Adapter/AbstractAdapterTest.php | 1 + .../Adapter/AbstractZendServerTest.php | 234 ++++++++++++ test/Storage/Adapter/ZendServerDiskTest.php | 63 ++++ test/Storage/Adapter/ZendServerShmTest.php | 63 ++++ 7 files changed, 873 insertions(+) create mode 100644 src/Storage/Adapter/AbstractZendServer.php create mode 100644 src/Storage/Adapter/ZendServerDisk.php create mode 100644 src/Storage/Adapter/ZendServerShm.php create mode 100644 test/Storage/Adapter/AbstractZendServerTest.php create mode 100644 test/Storage/Adapter/ZendServerDiskTest.php create mode 100644 test/Storage/Adapter/ZendServerShmTest.php diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php new file mode 100644 index 000000000..4b9eee521 --- /dev/null +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -0,0 +1,350 @@ +getOptions()->getReadable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + + $rs = $this->zdcFetch($key); + if ($rs === false) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found"); + } + + $rs = false; + } + + if (array_key_exists('token', $options)) { + $options['token'] = $rs; + } + + return $rs; + } + + public function getItems(array $keys, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return array(); + } + + $this->normalizeOptions($options); + foreach ($keys as &$key) { + $this->normalizeKey($key); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + } + + $rs = $this->zdcFetch($keys); + if ($rs === false) { + throw new RuntimeException("Failed to fetch keys"); + } + + // remove namespace + $nsl = strlen($options['namespace']) + strlen(self::NAMESPACE_SEPARATOR); + $rsItems = array(); + foreach ($rs as $k => &$v) { + $rsItems[ substr($k, $nsl) ] = $v; + } + + return $rsItems; + } + + public function hasItem($key, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + + return ($this->zdcFetch($key) !== false); + } + + public function hasItems(array $keys, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return array(); + } + + $this->normalizeOptions($options); + foreach ($keys as &$key) { + $this->normalizeKey($key); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + } + + $rs = $this->zdcFetch($keys); + if ($rs === false) { + throw new RuntimeException("Failed to fetch keys"); + } + + $rsExists = array(); + $nsl = strlen($options['namespace']) + strlen(self::NAMESPACE_SEPARATOR); + foreach ($rs as $k => $v) { + $k = substr($k, $nsl); + $rsExists[$k] = true; + } + + return $rsExists; + } + + public function getMetadata($key, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + + $rs = $this->zdcFetch($key); + if ($rs === false) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found"); + } + + return false; + } + + return array(); + } + + public function getMetadatas(array $keys, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return array(); + } + + $this->normalizeOptions($options); + foreach ($keys as &$key) { + $this->normalizeKey($key); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + } + + $rs = $this->zdcFetch($keys); + if ($rs === false) { + throw new RuntimeException("Failed to fetch keys"); + } + + $rsInfo = array(); + $nsl = strlen($options['namespace']) + strlen(self::NAMESPACE_SEPARATOR); + foreach ($rs as $k => $v) { + $k = substr($k, $nsl); + $rsInfo[$k] = array(); + } + + return $rsInfo; + } + + /* writing */ + + public function setItem($key, $value, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + + return $this->zdcStore($key, $value, $options['ttl']); + } + + public function removeItem($key, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + + if (!$this->zdcDelete($key)) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$key}' not found"); + } + } + + return true; + } + + /* cleaning */ + + public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + + // clear all + if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $rs = $this->zdcClear(); + if ($rs === false) { + throw new RuntimeException("Clearing failed"); + } + } + + // expired items will be deleted automatic + + return true; + } + + public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + + // clear all + if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $rs = $this->zdcClearByNamespace($options['namespace']); + if ($rs === false) { + throw new RuntimeException("Clearing failed"); + } + } + + // expired items will be deleted automatic + + return true; + } + + /* status */ + + public function getCapabilities() + { + if ($this->capabilities === null) { + $this->capabilityMarker = new \stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array(), + 'maxTtl' => 0, + 'staticTtl' => false, + 'tagging' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => false, + 'expiredRead' => false, + 'maxKeyLength' => 0, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, + 'iterable' => false, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); + } + + return $this->capabilities; + } + + /* internal wrapper of zend_[disk|shm]_cache_* functions */ + + /** + * Store data into Zend Data Cache (zdc) + * + * @param string $internalKey + * @param mixed $value + * @param int $ttl + * @return boolean + * @throws Zend\Cache\Exception + */ + abstract protected function zdcStore($internalKey, $value, $ttl); + + /** + * Fetch data from Zend Data Cache (zdc) + * + * @param string $internalKey + * @return mixed The stored value or FALSE if item wasn't found + * @throws Zend\Cache\Exception + */ + abstract protected function zdcFetch($internalKey); + + /** + * Delete data from Zend Data Cache (zdc) + * + * @param string $internalKey + * @return boolean + */ + abstract protected function zdcDelete($internalKey); + + /** + * Clear items of all namespaces from Zend Data Cache (zdc) + * + * @return boolean + */ + abstract protected function zdcClear(); + + /** + * Clear items of the given namespace from Zend Data Cache (zdc) + * + * @param string $namespace + * @return boolean + */ + abstract protected function zdcClearByNamespace($namespace); + +} diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php new file mode 100644 index 000000000..281e7b2e6 --- /dev/null +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -0,0 +1,79 @@ + Byte + return array( + 'total' => $total, + // TODO: How to get free capacity status + ); + } + + protected function zdcStore($key, $value, $ttl) + { + return zend_shm_cache_store($key, $value, $ttl); + } + + protected function zdcFetch($key) + { + return zend_shm_cache_fetch($key); + } + + protected function zdcDelete($key) + { + return zend_shm_cache_delete($key); + } + + protected function zdcClear() + { + return zend_shm_cache_clear(); + } + + protected function zdcClearByNamespace($namespace) + { + return zend_shm_cache_clear($namespace); + } + +} diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 88ce3c714..68e68a5a0 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -47,6 +47,7 @@ public function setUp() { $this->_options = new Cache\Storage\Adapter\AdapterOptions(); $this->_storage = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); + $this->_storage->setOptions($this->_options); $this->_storage->expects($this->any()) ->method('getOptions') ->will($this->returnValue($this->_options)); diff --git a/test/Storage/Adapter/AbstractZendServerTest.php b/test/Storage/Adapter/AbstractZendServerTest.php new file mode 100644 index 000000000..cbcd5d5b8 --- /dev/null +++ b/test/Storage/Adapter/AbstractZendServerTest.php @@ -0,0 +1,234 @@ +_options = new AdapterOptions(); + $this->_storage = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractZendServer'); + $this->_storage->setOptions($this->_options); + $this->_storage->expects($this->any()) + ->method('getOptions') + ->will($this->returnValue($this->_options)); + } + + public function testGetOptions() + { + $options = $this->_storage->getOptions(); + $this->assertInstanceOf('Zend\Cache\Storage\Adapter\AdapterOptions', $options); + $this->assertInternalType('boolean', $options->getWritable()); + $this->assertInternalType('boolean', $options->getReadable()); + $this->assertInternalType('integer', $options->getTtl()); + $this->assertInternalType('string', $options->getNamespace()); + $this->assertInternalType('string', $options->getNamespacePattern()); + $this->assertInternalType('string', $options->getKeyPattern()); + $this->assertInternalType('boolean', $options->getIgnoreMissingItems()); + } + + public function testGetWithDefaultNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcFetch') + ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue('value')); + + $this->assertEquals('value', $this->_storage->getItem('key')); + } + + public function testGetWithArgNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcFetch') + ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue('value')); + + $this->assertEquals('value', $this->_storage->getItem('key', array('namespace' => 'argns'))); + } + + public function testInfoWithDefaultNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcFetch') + ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue('value')); + + $this->assertEquals(array(), $this->_storage->getMetadata('key')); + } + + public function testInfoWithArgNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcFetch') + ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue('value')); + + $this->assertEquals(array(), $this->_storage->getMetadata('key', array('namespace' => 'argns'))); + } + + public function testExistsWithDefaultNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcFetch') + ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue('value')); + + $this->assertEquals(true, $this->_storage->hasItem('key')); + } + + public function testExistsWithArgNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcFetch') + ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue('value')); + + $this->assertEquals(true, $this->_storage->hasItem('key', array('namespace' => 'argns'))); + } + + public function testSetWithDefaultNamespaceAndTtl() + { + $this->_options->setTtl(10); + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcStore') + ->with( + $this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key'), + $this->equalTo('value'), + $this->equalTo(10) + ) + ->will($this->returnValue(true)); + + $this->assertEquals(true, $this->_storage->setItem('key', 'value')); + } + + public function testSetWithArgNamespaceAndTtl() + { + $this->_options->setTtl(10); + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcStore') + ->with( + $this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key'), + $this->equalTo('value'), + $this->equalTo(100) + ) + ->will($this->returnValue(true)); + + $this->assertEquals(true, $this->_storage->setItem('key', 'value', array('namespace' => 'argns', 'ttl' => 100))); + } + + public function testRemoveWithDefaultNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcDelete') + ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue(true)); + + $this->assertEquals(true, $this->_storage->removeItem('key')); + } + + public function testRemoveWithArgNamespace() + { + $this->_options->setNamespace('defaultns'); + + $this->_storage->expects($this->once()) + ->method('zdcDelete') + ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->will($this->returnValue(true)); + + $this->assertEquals(true, $this->_storage->removeItem('key', array('namespace' => 'argns'))); + } + + public function testClearExpired() + { + $this->_storage->expects($this->never()) + ->method('zdcClear'); + + $this->assertEquals(true, $this->_storage->clear(Adapter::MATCH_EXPIRED)); + } + + public function testClearActive() + { + $this->_storage->expects($this->once()) + ->method('zdcClear') + ->will($this->returnValue(true)); + + $rs = $this->_storage->clear(Adapter::MATCH_ACTIVE); + $this->assertEquals(true, $rs); + } + + public function testClearActiveByDefaultNamespace() + { + $this->_storage->expects($this->once()) + ->method('zdcClearByNamespace') + ->with($this->equalTo($this->_options->getNamespace())) + ->will($this->returnValue(true)); + + $rs = $this->_storage->clearByNamespace(Adapter::MATCH_ACTIVE); + $this->assertEquals(true, $rs); + } + + public function testClearActiveByArgNamespace() + { + $ns = 'namespace'; + $this->_storage->expects($this->once()) + ->method('zdcClearByNamespace') + ->with($this->equalTo($ns)) + ->will($this->returnValue(true)); + + $rs = $this->_storage->clearByNamespace(Adapter::MATCH_ACTIVE, array('namespace' => $ns)); + $this->assertEquals(true, $rs); + } + +} diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php new file mode 100644 index 000000000..0b560d6bf --- /dev/null +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -0,0 +1,63 @@ +fail("Missing expected ExtensionNotLoadedException"); + } catch (Exception\ExtensionNotLoadedException $e) { + $this->markTestSkipped($e->getMessage()); + } + } + + $this->_storage = new Cache\Storage\Adapter\ZendServerDisk(); + parent::setUp(); + } + + public function tearDown() + { + if (function_exists('zend_disk_cache_clear')) { + zend_disk_cache_clear(); + } + + parent::tearDown(); + } + +} diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php new file mode 100644 index 000000000..13ce92070 --- /dev/null +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -0,0 +1,63 @@ +fail("Missing expected ExtensionNotLoadedException"); + } catch (Exception\ExtensionNotLoadedException $e) { + $this->markTestSkipped($e->getMessage()); + } + } + + $this->_storage = new Cache\Storage\Adapter\ZendServerShm(); + parent::setUp(); + } + + public function tearDown() + { + if (function_exists('zend_shm_cache_clear')) { + zend_shm_cache_clear(); + } + + parent::tearDown(); + } + +} From 9233d2f51022c41654321cb96d5654ec04fbe13f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 14:30:50 +0100 Subject: [PATCH 185/311] removed $ --- test/Pattern/CallbackCacheTest.php | 1 - test/Pattern/CaptureCacheTest.php | 1 - test/Pattern/ClassCacheTest.php | 1 - test/Pattern/CommonPatternTest.php | 1 - test/Pattern/ObjectCacheTest.php | 1 - test/Pattern/OutputCacheTest.php | 1 - test/PatternFactoryTest.php | 1 - test/Storage/Adapter/AbstractAdapterTest.php | 1 - test/Storage/Adapter/AbstractZendServerTest.php | 1 - test/Storage/Adapter/CommonAdapterTest.php | 1 - test/Storage/Adapter/MemoryTest.php | 1 - test/Storage/Adapter/ZendServerDiskTest.php | 1 - test/Storage/Adapter/ZendServerShmTest.php | 1 - test/Storage/CapabilitiesTest.php | 1 - test/Storage/Plugin/CommonPluginTest.php | 1 - test/Storage/Plugin/IgnoreUserAbortTest.php | 1 - test/Storage/Plugin/SerializerTest.php | 1 - test/StorageFactoryTest.php | 1 - 18 files changed, 18 deletions(-) diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index 9788f2c54..9234ef7db 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Pattern; diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php index f48a9b785..54e715767 100644 --- a/test/Pattern/CaptureCacheTest.php +++ b/test/Pattern/CaptureCacheTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Pattern; diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 109ebcf24..6fb1ccbfb 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Pattern; diff --git a/test/Pattern/CommonPatternTest.php b/test/Pattern/CommonPatternTest.php index 6cf0d84db..a480a815b 100644 --- a/test/Pattern/CommonPatternTest.php +++ b/test/Pattern/CommonPatternTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Pattern; diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index 262723a2d..19796a737 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Pattern; diff --git a/test/Pattern/OutputCacheTest.php b/test/Pattern/OutputCacheTest.php index 2f931347a..af5a05081 100644 --- a/test/Pattern/OutputCacheTest.php +++ b/test/Pattern/OutputCacheTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Pattern; diff --git a/test/PatternFactoryTest.php b/test/PatternFactoryTest.php index 88db84ffb..4009aaa0e 100644 --- a/test/PatternFactoryTest.php +++ b/test/PatternFactoryTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache; diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 68e68a5a0..b374590cc 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; diff --git a/test/Storage/Adapter/AbstractZendServerTest.php b/test/Storage/Adapter/AbstractZendServerTest.php index cbcd5d5b8..e65dc373f 100644 --- a/test/Storage/Adapter/AbstractZendServerTest.php +++ b/test/Storage/Adapter/AbstractZendServerTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 551cd1bd3..0ee6c396d 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index d999f40d6..fb08aea7a 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php index 0b560d6bf..c0002748b 100644 --- a/test/Storage/Adapter/ZendServerDiskTest.php +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index 13ce92070..68a0c21a8 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Adapter; diff --git a/test/Storage/CapabilitiesTest.php b/test/Storage/CapabilitiesTest.php index 3f86a6f34..2409546fc 100644 --- a/test/Storage/CapabilitiesTest.php +++ b/test/Storage/CapabilitiesTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage; diff --git a/test/Storage/Plugin/CommonPluginTest.php b/test/Storage/Plugin/CommonPluginTest.php index 216ac846a..5db34f585 100644 --- a/test/Storage/Plugin/CommonPluginTest.php +++ b/test/Storage/Plugin/CommonPluginTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Plugin; diff --git a/test/Storage/Plugin/IgnoreUserAbortTest.php b/test/Storage/Plugin/IgnoreUserAbortTest.php index 97b8235c5..714dbb847 100644 --- a/test/Storage/Plugin/IgnoreUserAbortTest.php +++ b/test/Storage/Plugin/IgnoreUserAbortTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Plugin; diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index 997c7b4f1..7b28f364b 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache\Storage\Plugin; diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index 9f7a3f3b2..9e06cc596 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -17,7 +17,6 @@ * @subpackage UnitTests * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id$ */ namespace ZendTest\Cache; From 45d917832ea505bfde49b038889ea7e22fedcdc4 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 15:02:53 +0100 Subject: [PATCH 186/311] trigger events on zend server cache adapter --- src/Storage/Adapter/AbstractZendServer.php | 404 ++++++++++++++------- src/Storage/Adapter/ZendServerDisk.php | 16 +- src/Storage/Adapter/ZendServerShm.php | 27 +- 3 files changed, 313 insertions(+), 134 deletions(-) diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 4b9eee521..9674a3089 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -21,7 +21,8 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache, +use ArrayObject, + stdClass, Zend\Cache\Storage\Capabilities, Zend\Cache\Exception\RuntimeException, Zend\Cache\Exception\ItemNotFoundException; @@ -35,7 +36,11 @@ */ abstract class AbstractZendServer extends AbstractAdapter { - + /** + * The namespace separator used on Zend Data Cache functions + * + * @var string + */ const NAMESPACE_SEPARATOR = '::'; /* reading */ @@ -48,23 +53,33 @@ public function getItem($key, array $options = array()) $this->normalizeKey($key); $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $result = $this->zdcFetch($internalKey); + if ($result === false) { + if (!$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$internalKey}' not found"); + } - $rs = $this->zdcFetch($key); - if ($rs === false) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found"); + $result = false; + } elseif (array_key_exists('token', $options)) { + $options['token'] = $result; } - $rs = false; - } - - if (array_key_exists('token', $options)) { - $options['token'] = $rs; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - return $rs; } public function getItems(array $keys, array $options = array()) @@ -74,24 +89,39 @@ public function getItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - foreach ($keys as &$key) { - $this->normalizeKey($key); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - } + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $rs = $this->zdcFetch($keys); - if ($rs === false) { - throw new RuntimeException("Failed to fetch keys"); - } + $internalKeys = array(); + foreach ($keys as &$key) { + $this->normalizeKey($key); + $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + } - // remove namespace - $nsl = strlen($options['namespace']) + strlen(self::NAMESPACE_SEPARATOR); - $rsItems = array(); - foreach ($rs as $k => &$v) { - $rsItems[ substr($k, $nsl) ] = $v; - } + $fetch = $this->zdcFetch($internalKeys); + if ($fetch === false) { + throw new RuntimeException("Failed to fetch keys"); + } + + // remove namespace + $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); + $result = array(); + foreach ($fetch as $k => &$v) { + $result[ substr($k, $prefixL) ] = $v; + } - return $rsItems; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function hasItem($key, array $options = array()) @@ -102,9 +132,24 @@ public function hasItem($key, array $options = array()) $this->normalizeKey($key); $this->normalizeOptions($options); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - return ($this->zdcFetch($key) !== false); + $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $result = ($this->zdcFetch($internalKey) !== false); + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function hasItems(array $keys, array $options = array()) @@ -114,24 +159,38 @@ public function hasItems(array $keys, array $options = array()) } $this->normalizeOptions($options); - foreach ($keys as &$key) { - $this->normalizeKey($key); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - } + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $rs = $this->zdcFetch($keys); - if ($rs === false) { - throw new RuntimeException("Failed to fetch keys"); - } + $internalKeys = array(); + foreach ($keys as &$key) { + $this->normalizeKey($key); + $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + } - $rsExists = array(); - $nsl = strlen($options['namespace']) + strlen(self::NAMESPACE_SEPARATOR); - foreach ($rs as $k => $v) { - $k = substr($k, $nsl); - $rsExists[$k] = true; - } + $fetch = $this->zdcFetch($internalKeys); + if ($fetch === false) { + throw new RuntimeException("Failed to fetch keys"); + } + + $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); + $result = array(); + foreach ($fetch as $k => &$v) { + $result[] = substr($k, $prefixL); + } - return $rsExists; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function getMetadata($key, array $options = array()) @@ -142,18 +201,24 @@ public function getMetadata($key, array $options = array()) $this->normalizeKey($key); $this->normalizeOptions($options); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - - $rs = $this->zdcFetch($key); - if ($rs === false) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found"); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - return false; - } + $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $result = ($this->zdcFetch($internalKey) !== false) ? array() : false; - return array(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function getMetadatas(array $keys, array $options = array()) @@ -163,24 +228,38 @@ public function getMetadatas(array $keys, array $options = array()) } $this->normalizeOptions($options); - foreach ($keys as &$key) { - $this->normalizeKey($key); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - } + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $rs = $this->zdcFetch($keys); - if ($rs === false) { - throw new RuntimeException("Failed to fetch keys"); - } + $internalKeys = array(); + foreach ($keys as &$key) { + $this->normalizeKey($key); + $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + } - $rsInfo = array(); - $nsl = strlen($options['namespace']) + strlen(self::NAMESPACE_SEPARATOR); - foreach ($rs as $k => $v) { - $k = substr($k, $nsl); - $rsInfo[$k] = array(); - } + $fetch = $this->zdcFetch($internalKeys); + if ($fetch === false) { + throw new RuntimeException("Failed to fetch keys"); + } - return $rsInfo; + $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); + $result = array(); + foreach ($fetch as $k => &$v) { + $result[ substr($k, $prefixL) ] = array(); + } + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* writing */ @@ -193,9 +272,30 @@ public function setItem($key, $value, array $options = array()) $this->normalizeKey($key); $this->normalizeOptions($options); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - return $this->zdcStore($key, $value, $options['ttl']); + $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + if (!$this->zdcStore($internalKey, $value, $options['ttl'])) { + throw new RuntimeException( + "zend_xxx_cache_store($internalKey, , {$options['ttl']}) failed" + ); + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function removeItem($key, array $options = array()) @@ -206,15 +306,28 @@ public function removeItem($key, array $options = array()) $this->normalizeKey($key); $this->normalizeOptions($options); - $key = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - if (!$this->zdcDelete($key)) { - if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$key}' not found"); + $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; + if (!$this->zdcDelete($internalKey) && !$options['ignore_missing_items']) { + throw new ItemNotFoundException("Key '{$internalKey}' not found"); } - } - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* cleaning */ @@ -227,18 +340,31 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - // clear all - if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $rs = $this->zdcClear(); - if ($rs === false) { - throw new RuntimeException("Clearing failed"); + // clear all + if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + if (!$this->zdcClear()) { + throw new RuntimeException("Clearing failed"); + } } - } - // expired items will be deleted automatic + // expired items will be deleted automatic - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) @@ -249,57 +375,82 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $this->normalizeOptions($options); $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - // clear all - if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $rs = $this->zdcClearByNamespace($options['namespace']); - if ($rs === false) { - throw new RuntimeException("Clearing failed"); + // clear all + if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $rs = $this->zdcClearByNamespace($options['namespace']); + if ($rs === false) { + throw new RuntimeException("Clearing failed"); + } } - } - // expired items will be deleted automatic + // expired items will be deleted automatic - return true; + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* status */ public function getCapabilities() { - if ($this->capabilities === null) { - $this->capabilityMarker = new \stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'maxTtl' => 0, - 'staticTtl' => false, - 'tagging' => false, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 0, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, - ) - ); - } + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - return $this->capabilities; + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array(), + 'maxTtl' => 0, + 'staticTtl' => false, + 'tagging' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => false, + 'expiredRead' => false, + 'maxKeyLength' => 0, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, + 'iterable' => false, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); + } + + return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /* internal wrapper of zend_[disk|shm]_cache_* functions */ @@ -346,5 +497,4 @@ abstract protected function zdcClear(); * @return boolean */ abstract protected function zdcClearByNamespace($namespace); - } diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index 281e7b2e6..c3a7165be 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -48,7 +48,21 @@ public function __construct($options = array()) public function getCapacity(array $options = array()) { - return Utils::getDiskCapacity(ini_get('zend_datacache.disk.save_path')); + $args = new ArrayObject(array( + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = Utils::getDiskCapacity(ini_get('zend_datacache.disk.save_path')); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } protected function zdcStore($key, $value, $ttl) diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index c98b1a1b6..3e930a896 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -47,12 +47,27 @@ public function __construct($options = array()) public function getCapacity(array $options = array()) { - $total = (int)ini_get('zend_datacache.shm.memory_cache_size'); - $total*= 1048576; // MB -> Byte - return array( - 'total' => $total, - // TODO: How to get free capacity status - ); + $args = new ArrayObject(array( + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $total = (int)ini_get('zend_datacache.shm.memory_cache_size'); + $total*= 1048576; // MB -> Byte + $result = array( + 'total' => $total, + // TODO: How to get free capacity status + ); + + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } protected function zdcStore($key, $value, $ttl) From 5364d9b41ece32fde376eb7ce20a003c3397cd13 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 15:23:22 +0100 Subject: [PATCH 187/311] simplified the use of exceptions on zend server cache adapters --- src/Storage/Adapter/AbstractZendServer.php | 70 +++++++++------------- src/Storage/Adapter/ZendServerDisk.php | 38 +++++++++--- src/Storage/Adapter/ZendServerShm.php | 37 +++++++++--- 3 files changed, 87 insertions(+), 58 deletions(-) diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 9674a3089..649212962 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -24,8 +24,7 @@ use ArrayObject, stdClass, Zend\Cache\Storage\Capabilities, - Zend\Cache\Exception\RuntimeException, - Zend\Cache\Exception\ItemNotFoundException; + Zend\Cache\Exception; /** * @category Zend @@ -68,7 +67,7 @@ public function getItem($key, array $options = array()) $result = $this->zdcFetch($internalKey); if ($result === false) { if (!$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$internalKey}' not found"); + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } $result = false; @@ -106,12 +105,7 @@ public function getItems(array $keys, array $options = array()) $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; } - $fetch = $this->zdcFetch($internalKeys); - if ($fetch === false) { - throw new RuntimeException("Failed to fetch keys"); - } - - // remove namespace + $fetch = $this->zdcFetchMulti($internalKeys); $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); $result = array(); foreach ($fetch as $k => &$v) { @@ -176,11 +170,7 @@ public function hasItems(array $keys, array $options = array()) $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; } - $fetch = $this->zdcFetch($internalKeys); - if ($fetch === false) { - throw new RuntimeException("Failed to fetch keys"); - } - + $fetch = $this->zdcFetchMulti($internalKeys); $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); $result = array(); foreach ($fetch as $k => &$v) { @@ -245,11 +235,7 @@ public function getMetadatas(array $keys, array $options = array()) $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; } - $fetch = $this->zdcFetch($internalKeys); - if ($fetch === false) { - throw new RuntimeException("Failed to fetch keys"); - } - + $fetch = $this->zdcFetchMulti($internalKeys); $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); $result = array(); foreach ($fetch as $k => &$v) { @@ -285,11 +271,7 @@ public function setItem($key, $value, array $options = array()) } $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - if (!$this->zdcStore($internalKey, $value, $options['ttl'])) { - throw new RuntimeException( - "zend_xxx_cache_store($internalKey, , {$options['ttl']}) failed" - ); - } + $this->zdcStore($internalKey, $value, $options['ttl']); $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); @@ -320,7 +302,7 @@ public function removeItem($key, array $options = array()) $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; if (!$this->zdcDelete($internalKey) && !$options['ignore_missing_items']) { - throw new ItemNotFoundException("Key '{$internalKey}' not found"); + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } $result = true; @@ -353,9 +335,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) // clear all if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - if (!$this->zdcClear()) { - throw new RuntimeException("Clearing failed"); - } + $this->zdcClear(); } // expired items will be deleted automatic @@ -388,10 +368,7 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a // clear all if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $rs = $this->zdcClearByNamespace($options['namespace']); - if ($rs === false) { - throw new RuntimeException("Clearing failed"); - } + $this->zdcClearByNamespace($options['namespace']); } // expired items will be deleted automatic @@ -458,16 +435,16 @@ public function getCapabilities() /** * Store data into Zend Data Cache (zdc) * - * @param string $internalKey - * @param mixed $value - * @param int $ttl - * @return boolean - * @throws Zend\Cache\Exception + * @param string $internalKey + * @param mixed $value + * @param int $ttl + * @return void + * @throws Exception\RuntimeException */ abstract protected function zdcStore($internalKey, $value, $ttl); /** - * Fetch data from Zend Data Cache (zdc) + * Fetch a single item from Zend Data Cache (zdc) * * @param string $internalKey * @return mixed The stored value or FALSE if item wasn't found @@ -475,6 +452,15 @@ abstract protected function zdcStore($internalKey, $value, $ttl); */ abstract protected function zdcFetch($internalKey); + /** + * Fetch a multiple items from Zend Data Cache (zdc) + * + * @param array $internalKeys + * @return array All found items + * @throws Exception\RuntimeException + */ + abstract protected function zdcFetchMulti(array $internalKeys); + /** * Delete data from Zend Data Cache (zdc) * @@ -486,15 +472,17 @@ abstract protected function zdcDelete($internalKey); /** * Clear items of all namespaces from Zend Data Cache (zdc) * - * @return boolean + * @return void + * @throws Exception\RuntimeException */ abstract protected function zdcClear(); /** * Clear items of the given namespace from Zend Data Cache (zdc) * - * @param string $namespace - * @return boolean + * @param string $namespace + * @return void + * @throws Exception\RuntimeException */ abstract protected function zdcClearByNamespace($namespace); } diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index c3a7165be..e5c01fae4 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -22,8 +22,7 @@ namespace Zend\Cache\Storage\Adapter; use Zend\Cache\Utils, - Zend\Cache\Exception\ExtensionNotLoadedException, - Zend\Cache\Exception\RuntimeException; + Zend\Cache\Exception; /** * @category Zend @@ -38,9 +37,9 @@ class ZendServerDisk extends AbstractZendServer public function __construct($options = array()) { if (!function_exists('zend_disk_cache_store')) { - throw new ExtensionNotLoadedException("Missing 'zend_disk_cache_*' functions"); + throw new Exception\ExtensionNotLoadedException("Missing 'zend_disk_cache_*' functions"); } elseif (PHP_SAPI == 'cli') { - throw new ExtensionNotLoadedException("Zend server data cache isn't available on cli"); + throw new Exception\ExtensionNotLoadedException("Zend server data cache isn't available on cli"); } parent::__construct($options); @@ -67,12 +66,26 @@ public function getCapacity(array $options = array()) protected function zdcStore($key, $value, $ttl) { - return zend_disk_cache_store($key, $value, $ttl); + if (!zend_disk_cache_store($key, $value, $ttl)) { + $valueType = gettype($value); + throw new Exception\RuntimeException( + "zend_disk_cache_store($internalKey, <{$valueType}>, {$options['ttl']}) failed" + ); + } } protected function zdcFetch($key) { - return zend_disk_cache_fetch($key); + return zend_disk_cache_fetch((string)$key); + } + + protected function zdcFetchMulti(array $internalKeys) + { + $items = zend_disk_cache_fetch($internalKeys); + if ($items === false) { + throw new Exception\RuntimeException("zend_disk_cache_fetch() failed"); + } + return $items; } protected function zdcDelete($key) @@ -82,12 +95,19 @@ protected function zdcDelete($key) protected function zdcClear() { - return zend_disk_cache_clear(); + if (!zend_disk_cache_clear()) { + throw new Exception\RuntimeException( + 'zend_disk_cache_clear() failed' + ); + } } protected function zdcClearByNamespace($namespace) { - return zend_disk_cache_clear($namespace); + if (!zend_disk_cache_clear($namespace)) { + throw new Exception\RuntimeException( + "zend_disk_cache_clear({$namespace}) failed" + ); + } } - } diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 3e930a896..1a563f71e 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -21,8 +21,7 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception\ExtensionNotLoadedException, - Zend\Cache\Exception\RuntimeException; +use Zend\Cache\Exception; /** * @category Zend @@ -37,9 +36,9 @@ class ZendServerShm extends AbstractZendServer public function __construct($options = array()) { if (!function_exists('zend_shm_cache_store')) { - throw new ExtensionNotLoadedException("Missing 'zend_shm_cache_*' functions"); + throw new Exception\ExtensionNotLoadedException("Missing 'zend_shm_cache_*' functions"); } elseif (PHP_SAPI == 'cli') { - throw new ExtensionNotLoadedException("Zend server data cache isn't available on cli"); + throw new Exception\ExtensionNotLoadedException("Zend server data cache isn't available on cli"); } parent::__construct($options); @@ -72,12 +71,26 @@ public function getCapacity(array $options = array()) protected function zdcStore($key, $value, $ttl) { - return zend_shm_cache_store($key, $value, $ttl); + if (!zend_shm_cache_store($key, $value, $ttl)) { + $valueType = gettype($value); + throw new Exception\RuntimeException( + "zend_disk_cache_store($internalKey, <{$valueType}>, {$options['ttl']}) failed" + ); + } } protected function zdcFetch($key) { - return zend_shm_cache_fetch($key); + return zend_shm_cache_fetch((string)$key); + } + + protected function zdcFetchMulti(array $internalKeys) + { + $items = zend_shm_cache_fetch($internalKeys); + if ($items === false) { + throw new Exception\RuntimeException("zend_shm_cache_fetch() failed"); + } + return $items; } protected function zdcDelete($key) @@ -87,12 +100,20 @@ protected function zdcDelete($key) protected function zdcClear() { - return zend_shm_cache_clear(); + if (!zend_shm_cache_clear()) { + throw new Exception\RuntimeException( + 'zend_shm_cache_clear() failed' + ); + } } protected function zdcClearByNamespace($namespace) { - return zend_shm_cache_clear($namespace); + if (!zend_shm_cache_clear($namespace)) { + throw new Exception\RuntimeException( + "zend_shm_cache_clear({$namespace}) failed" + ); + } } } From b019ef02e68ba00eace02891fa250e03532825fb Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 15:36:41 +0100 Subject: [PATCH 188/311] phpdoc of zend server cache adapters --- src/Storage/Adapter/AbstractZendServer.php | 185 ++++++++++++++++++++- src/Storage/Adapter/ZendServerDisk.php | 60 +++++++ src/Storage/Adapter/ZendServerShm.php | 61 ++++++- 3 files changed, 301 insertions(+), 5 deletions(-) diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 649212962..105f4edc8 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -44,6 +44,24 @@ abstract class AbstractZendServer extends AbstractAdapter /* reading */ + /** + * Get an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return mixed Value on success and false on failure + * @throws Exception + * + * @triggers getItem.pre(PreEvent) + * @triggers getItem.post(PostEvent) + * @triggers getItem.exception(ExceptionEvent) + */ public function getItem($key, array $options = array()) { if (!$this->getOptions()->getReadable()) { @@ -81,6 +99,22 @@ public function getItem($key, array $options = array()) } } + /** + * Get multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return array Assoziative array of existing keys and values or false on failure + * @throws Exception + * + * @triggers getItems.pre(PreEvent) + * @triggers getItems.post(PostEvent) + * @triggers getItems.exception(ExceptionEvent) + */ public function getItems(array $keys, array $options = array()) { if (!$this->getOptions()->getReadable()) { @@ -118,6 +152,22 @@ public function getItems(array $keys, array $options = array()) } } + /** + * Test if an item exists. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers hasItem.pre(PreEvent) + * @triggers hasItem.post(PostEvent) + * @triggers hasItem.exception(ExceptionEvent) + */ public function hasItem($key, array $options = array()) { if (!$this->getOptions()->getReadable()) { @@ -146,6 +196,22 @@ public function hasItem($key, array $options = array()) } } + /** + * Test if multiple items exists. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers hasItems.pre(PreEvent) + * @triggers hasItems.post(PostEvent) + * @triggers hasItems.exception(ExceptionEvent) + */ public function hasItems(array $keys, array $options = array()) { if (!$this->getOptions()->getReadable()) { @@ -183,6 +249,24 @@ public function hasItems(array $keys, array $options = array()) } } + /** + * Get metadata of an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return array|boolean Metadata or false on failure + * @throws Exception + * + * @triggers getMetadata.pre(PreEvent) + * @triggers getMetadata.post(PostEvent) + * @triggers getMetadata.exception(ExceptionEvent) + */ public function getMetadata($key, array $options = array()) { if (!$this->getOptions()->getReadable()) { @@ -211,6 +295,22 @@ public function getMetadata($key, array $options = array()) } } + /** + * Get metadata for multiple items + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return array + * @throws Exception\ItemNotFoundException + * + * @triggers getMetadatas.pre(PreEvent) + * @triggers getMetadatas.post(PostEvent) + * @triggers getMetadatas.exception(ExceptionEvent) + */ public function getMetadatas(array $keys, array $options = array()) { if (!$this->getOptions()->getReadable()) { @@ -250,6 +350,25 @@ public function getMetadatas(array $keys, array $options = array()) /* writing */ + /** + * Store an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers setItem.pre(PreEvent) + * @triggers setItem.post(PostEvent) + * @triggers setItem.exception(ExceptionEvent) + */ public function setItem($key, $value, array $options = array()) { if (!$this->getOptions()->getWritable()) { @@ -280,6 +399,24 @@ public function setItem($key, $value, array $options = array()) } } + /** + * Remove an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers removeItem.pre(PreEvent) + * @triggers removeItem.post(PostEvent) + * @triggers removeItem.exception(ExceptionEvent) + */ public function removeItem($key, array $options = array()) { if (!$this->getOptions()->getWritable()) { @@ -314,6 +451,19 @@ public function removeItem($key, array $options = array()) /* cleaning */ + /** + * Clear items off all namespaces. + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Exception + * @see clearByNamespace() + * + * @triggers clear.pre(PreEvent) + * @triggers clear.post(PostEvent) + * @triggers clear.exception(ExceptionEvent) + */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) { if (!$this->getOptions()->getWritable()) { @@ -347,6 +497,23 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } } + /** + * Clear items by namespace. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Zend\Cache\Exception + * @see clear() + * + * @triggers clearByNamespace.pre(PreEvent) + * @triggers clearByNamespace.post(PostEvent) + * @triggers clearByNamespace.exception(ExceptionEvent) + */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) { if (!$this->getOptions()->getWritable()) { @@ -382,6 +549,15 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a /* status */ + /** + * Get capabilities + * + * @return Capabilities + * + * @triggers getCapabilities.pre(PreEvent) + * @triggers getCapabilities.post(PostEvent) + * @triggers getCapabilities.exception(ExceptionEvent) + */ public function getCapabilities() { $args = new ArrayObject(); @@ -446,14 +622,14 @@ abstract protected function zdcStore($internalKey, $value, $ttl); /** * Fetch a single item from Zend Data Cache (zdc) * - * @param string $internalKey + * @param string $internalKey * @return mixed The stored value or FALSE if item wasn't found - * @throws Zend\Cache\Exception + * @throws Exception\RuntimeException */ abstract protected function zdcFetch($internalKey); /** - * Fetch a multiple items from Zend Data Cache (zdc) + * Fetch multiple items from Zend Data Cache (zdc) * * @param array $internalKeys * @return array All found items @@ -464,8 +640,9 @@ abstract protected function zdcFetchMulti(array $internalKeys); /** * Delete data from Zend Data Cache (zdc) * - * @param string $internalKey + * @param string $internalKey * @return boolean + * @throws Exception\RuntimeException */ abstract protected function zdcDelete($internalKey); diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index e5c01fae4..fac6cb907 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -34,6 +34,13 @@ class ZendServerDisk extends AbstractZendServer { + /** + * Constructor + * + * @param null|array|Traversable|AdapterOptions $options + * @throws Exception + * @return void + */ public function __construct($options = array()) { if (!function_exists('zend_disk_cache_store')) { @@ -45,6 +52,16 @@ public function __construct($options = array()) parent::__construct($options); } + /** + * Get storage capacity. + * + * @param array $options + * @return array|boolean Capacity as array or false on failure + * + * @triggers getCapacity.pre(PreEvent) + * @triggers getCapacity.post(PostEvent) + * @triggers getCapacity.exception(ExceptionEvent) + */ public function getCapacity(array $options = array()) { $args = new ArrayObject(array( @@ -64,6 +81,15 @@ public function getCapacity(array $options = array()) } } + /** + * Store data into Zend Data Disk Cache + * + * @param string $internalKey + * @param mixed $value + * @param int $ttl + * @return void + * @throws Exception\RuntimeException + */ protected function zdcStore($key, $value, $ttl) { if (!zend_disk_cache_store($key, $value, $ttl)) { @@ -74,11 +100,25 @@ protected function zdcStore($key, $value, $ttl) } } + /** + * Fetch a single item from Zend Data Disk Cache + * + * @param string $internalKey + * @return mixed The stored value or FALSE if item wasn't found + * @throws Exception\RuntimeException + */ protected function zdcFetch($key) { return zend_disk_cache_fetch((string)$key); } + /** + * Fetch multiple items from Zend Data Disk Cache + * + * @param array $internalKeys + * @return array All found items + * @throws Exception\RuntimeException + */ protected function zdcFetchMulti(array $internalKeys) { $items = zend_disk_cache_fetch($internalKeys); @@ -88,11 +128,24 @@ protected function zdcFetchMulti(array $internalKeys) return $items; } + /** + * Delete data from Zend Data Disk Cache + * + * @param string $internalKey + * @return boolean + * @throws Exception\RuntimeException + */ protected function zdcDelete($key) { return zend_disk_cache_delete($key); } + /** + * Clear items of all namespaces from Zend Data Disk Cache + * + * @return void + * @throws Exception\RuntimeException + */ protected function zdcClear() { if (!zend_disk_cache_clear()) { @@ -102,6 +155,13 @@ protected function zdcClear() } } + /** + * Clear items of the given namespace from Zend Data Disk Cache + * + * @param string $namespace + * @return void + * @throws Exception\RuntimeException + */ protected function zdcClearByNamespace($namespace) { if (!zend_disk_cache_clear($namespace)) { diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 1a563f71e..4d71ead47 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -33,6 +33,13 @@ class ZendServerShm extends AbstractZendServer { + /** + * Constructor + * + * @param null|array|Traversable|AdapterOptions $options + * @throws Exception + * @return void + */ public function __construct($options = array()) { if (!function_exists('zend_shm_cache_store')) { @@ -44,6 +51,16 @@ public function __construct($options = array()) parent::__construct($options); } + /** + * Get storage capacity. + * + * @param array $options + * @return array|boolean Capacity as array or false on failure + * + * @triggers getCapacity.pre(PreEvent) + * @triggers getCapacity.post(PostEvent) + * @triggers getCapacity.exception(ExceptionEvent) + */ public function getCapacity(array $options = array()) { $args = new ArrayObject(array( @@ -69,6 +86,15 @@ public function getCapacity(array $options = array()) } } + /** + * Store data into Zend Data SHM Cache + * + * @param string $internalKey + * @param mixed $value + * @param int $ttl + * @return void + * @throws Exception\RuntimeException + */ protected function zdcStore($key, $value, $ttl) { if (!zend_shm_cache_store($key, $value, $ttl)) { @@ -79,11 +105,25 @@ protected function zdcStore($key, $value, $ttl) } } + /** + * Fetch a single item from Zend Data SHM Cache + * + * @param string $internalKey + * @return mixed The stored value or FALSE if item wasn't found + * @throws Exception\RuntimeException + */ protected function zdcFetch($key) { return zend_shm_cache_fetch((string)$key); } + /** + * Fetch multiple items from Zend Data SHM Cache + * + * @param array $internalKeys + * @return array All found items + * @throws Exception\RuntimeException + */ protected function zdcFetchMulti(array $internalKeys) { $items = zend_shm_cache_fetch($internalKeys); @@ -93,11 +133,24 @@ protected function zdcFetchMulti(array $internalKeys) return $items; } + /** + * Delete data from Zend Data SHM Cache + * + * @param string $internalKey + * @return boolean + * @throws Exception\RuntimeException + */ protected function zdcDelete($key) { return zend_shm_cache_delete($key); } + /** + * Clear items of all namespaces from Zend Data SHM Cache + * + * @return void + * @throws Exception\RuntimeException + */ protected function zdcClear() { if (!zend_shm_cache_clear()) { @@ -107,6 +160,13 @@ protected function zdcClear() } } + /** + * Clear items of the given namespace from Zend Data SHM Cache + * + * @param string $namespace + * @return void + * @throws Exception\RuntimeException + */ protected function zdcClearByNamespace($namespace) { if (!zend_shm_cache_clear($namespace)) { @@ -115,5 +175,4 @@ protected function zdcClearByNamespace($namespace) ); } } - } From d0f7abc56ecda5f0e8862e38b96eefdc31fc8e36 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 15:40:02 +0100 Subject: [PATCH 189/311] fixed capability 'static_ttl' of the following adapters: ZendServer, Apc, Memcached, WinCache --- src/Storage/Adapter/AbstractZendServer.php | 2 +- src/Storage/Adapter/Apc.php | 2 +- src/Storage/Adapter/Memcached.php | 2 +- src/Storage/Adapter/WinCache.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 105f4edc8..121fe7424 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -585,7 +585,7 @@ public function getCapabilities() ), 'supportedMetadata' => array(), 'maxTtl' => 0, - 'staticTtl' => false, + 'staticTtl' => true, 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => false, diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 601aa29a2..22187fe61 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -1393,7 +1393,7 @@ public function getCapabilities() 'ttl', ), 'maxTtl' => 0, - 'staticTtl' => false, + 'staticTtl' => true, 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => (bool) ini_get('apc.use_request_time'), diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index d216e0931..43e2b5c46 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -1074,7 +1074,7 @@ public function getCapabilities() ), 'supportedMetadata' => array(), 'maxTtl' => 0, - 'staticTtl' => false, + 'staticTtl' => true, 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => false, diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 9f6cd9e2a..3848634e8 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -1028,7 +1028,7 @@ public function getCapabilities() 'mem_size' ), 'maxTtl' => 0, - 'staticTtl' => false, + 'staticTtl' => true, 'ttlPrecision' => 1, 'useRequestTime' => false, 'expiredRead' => false, From 5488a0642a848c69a6a3fe318118aae77d4fa497 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 15:45:54 +0100 Subject: [PATCH 190/311] fixed options-doc of apc adapter --- src/Storage/Adapter/Apc.php | 67 ++++++++++++++----------------------- 1 file changed, 26 insertions(+), 41 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 22187fe61..c9f4e0bd3 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -159,8 +159,6 @@ public function getOptions() * Get an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional @@ -218,8 +216,6 @@ public function getItem($key, array $options = array()) * Get multiple items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -282,8 +278,6 @@ public function getItems(array $keys, array $options = array()) * Test if an item exists. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -326,11 +320,9 @@ public function hasItem($key, array $options = array()) } /** - * Test if an item exists. + * Test if multiple items exists. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * @@ -387,8 +379,6 @@ public function hasItems(array $keys, array $options = array()) * Get metadata of an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional @@ -450,7 +440,11 @@ public function getMetadata($key, array $options = array()) } /** - * Get all metadata for an item + * Get metadata of multiple items + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keys * @param array $options @@ -522,10 +516,10 @@ public function getMetadatas(array $keys, array $options = array()) * Store an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param string $key * @param mixed $value @@ -577,10 +571,10 @@ public function setItem($key, $value, array $options = array()) * Store multiple items. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param array $keyValuePairs * @param array $options @@ -636,10 +630,10 @@ public function setItems(array $keyValuePairs, array $options = array()) * Add an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param string $key * @param mixed $value @@ -695,10 +689,10 @@ public function addItem($key, $value, array $options = array()) * Add multiple items. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param array $keyValuePairs * @param array $options @@ -754,10 +748,10 @@ public function addItems(array $keyValuePairs, array $options = array()) * Replace an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags * * @param string $key * @param mixed $value @@ -925,6 +919,8 @@ public function removeItems(array $keys, array $options = array()) * Increment an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional @@ -986,6 +982,8 @@ public function incrementItem($key, $value, array $options = array()) * Decrement an item. * * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional @@ -1048,6 +1046,10 @@ public function decrementItem($key, $value, array $options = array()) /** * Get items that were marked to delay storage for purposes of removing blocking * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * * @param array $keys * @param array $options * @return bool @@ -1122,13 +1124,8 @@ public function getDelayed(array $keys, array $options = array()) * Find items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* * * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) * @param array $options @@ -1251,13 +1248,6 @@ public function fetch() /** * Clear items off all namespaces. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* - * * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) * @param array $options * @return boolean @@ -1298,13 +1288,8 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) * Clear items by namespace. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* * * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) * @param array $options @@ -1453,8 +1438,8 @@ public function getCapacity(array $options = array()) * Clear cached items based on key regex * * @param string $regex - * @param int $mode - * @param array $options + * @param int $mode + * @param array $options * @return bool */ protected function clearByRegEx($regex, $mode, array &$options) From 6cc35a4f3e3c7d783e670723da66aed637f459e3 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 8 Jan 2012 16:12:10 +0100 Subject: [PATCH 191/311] refactored all missing tests of cache patterns --- test/Pattern/ClassCacheTest.php | 15 +++++++++------ test/Pattern/ObjectCacheTest.php | 15 +++++++++------ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 109ebcf24..3169ac601 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -99,14 +99,17 @@ public function testCallDisabledCacheOutput() public function testGenerateKey() { - $this->markTestIncomplete(); - $args = array('arg1', 2, 3.33, null); + + $generatedKey = $this->_pattern->generateKey('emptyMethod', $args); + $usedKey = null; + $this->_options->getStorage()->events()->attach('setItem.pre', function ($event) use (&$usedKey) { + $params = $event->getParams(); + $usedKey = $params['key']; + }); + $this->_pattern->call('emptyMethod', $args); - $this->assertEquals( - $this->_storage->getLastKey(), // get the last used key by storage - $this->_pattern->generateKey('emptyMethod', $args) - ); + $this->assertEquals($generatedKey, $usedKey); } public function testCallUnknownMethodException() diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index 262723a2d..22ffb9627 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -113,14 +113,17 @@ public function testCallInvoke() public function testGenerateKey() { - $this->markTestIncomplete(); - $args = array('arg1', 2, 3.33, null); + + $generatedKey = $this->_pattern->generateKey('emptyMethod', $args); + $usedKey = null; + $this->_options->getStorage()->events()->attach('setItem.pre', function ($event) use (&$usedKey) { + $params = $event->getParams(); + $usedKey = $params['key']; + }); + $this->_pattern->call('emptyMethod', $args); - $this->assertEquals( - $this->_storage->getLastKey(), // get the last used key by storage - $this->_pattern->generateKey('emptyMethod', $args) - ); + $this->assertEquals($generatedKey, $usedKey); } public function testGenerateKeyWithPredefinedCallbackAndArgumentKey() From c8c146e9a20e7a7f1f20d0228dcd56ff013e886c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 9 Jan 2012 12:25:35 +0100 Subject: [PATCH 192/311] comment + todo --- src/Storage/Adapter/Memcached.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index d216e0931..a62c7d41c 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -75,9 +75,11 @@ public function __construct($options = null) parent::__construct($options); + // It's ok to add server as soon as possible because + // ext/memcached auto-connects to the server on first use + // TODO: Handle multiple servers $options = $this->getOptions(); $this->memcached->addServer($options->getServer(), $options->getPort()); - } /* options */ From a9cb3163930d0452333f4b12e92d6723c4bbf3ab Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 9 Jan 2012 11:43:09 -0600 Subject: [PATCH 193/311] Skip SHM tests when in CLI - Zend Server SHM does not work in CLI environment --- test/Storage/Adapter/ZendServerShmTest.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index 68a0c21a8..f23b8e041 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -37,6 +37,11 @@ class ZendServerShmTest extends CommonAdapterTest public function setUp() { + if (strtolower(PHP_SAPI) == 'cli') { + $this->markTestSkipped('Zend Server SHM does not work in CLI environment'); + return; + } + if (!function_exists('zend_shm_cache_store')) { try { new Cache\Storage\Adapter\ZendServerShm(); From 963c8b73bfb4f1830264aae002f151aea8d078c4 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 10 Jan 2012 12:38:05 +0100 Subject: [PATCH 194/311] Now the filesystem cache adapter uses Zend\Stdlib\ErrorHandler --- src/Storage/Adapter/Filesystem.php | 249 ++++++++++----------- test/Storage/Adapter/CommonAdapterTest.php | 12 +- 2 files changed, 131 insertions(+), 130 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 3477ba8fc..351b6c512 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -28,7 +28,8 @@ Zend\Cache\Exception, Zend\Cache\Storage, Zend\Cache\Storage\Capabilities, - Zend\Cache\Utils; + Zend\Cache\Utils, + Zend\Stdlib\ErrorHandler; /** * @category Zend @@ -1036,7 +1037,10 @@ public function optimize(array $options = array()) if ( ($dirLevel = $baseOptions->getDirLevel()) ) { // removes only empty directories - $this->rmDir($baseOptions->getCacheDir(), $options['namespace'] . $baseOptions->getNamespaceSeparator()); + $this->rmDir( + $baseOptions->getCacheDir(), + $options['namespace'] . $baseOptions->getNamespaceSeparator() + ); } $result = true; @@ -1153,13 +1157,14 @@ protected function internalSetItem($key, $value, array &$options) $path = dirname($filespec); if (!file_exists($path)) { $oldUmask = umask($baseOptions->getDirUmask()); - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($oldUmask) { - umask($oldUmask); - $message = sprintf('Error creating directory (in %s@%d): %s', $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - mkdir($path, 0777, true); - restore_error_handler(); + ErrorHandler::start(); + $mkdir = mkdir($path, 0777, true); + $error = ErrorHandler::stop(); + if (!$mkdir) { + throw new Exception\RuntimeException( + "Error creating directory '{$file}'", 0, $error + ); + } } } } @@ -1340,8 +1345,8 @@ protected function internalGetMetadata($key, array &$options) /** * Touch a key * - * @param $key - * @param array $options + * @param string $key + * @param array $options * @return bool * @throws ItemNotFoundException|RuntimeException */ @@ -1352,16 +1357,20 @@ protected function internalTouchItem($key, array &$options) if ($options['ignore_missing_items']) { return false; } else { - throw new Exception\ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); + throw new Exception\ItemNotFoundException( + "Key '{$key}' not found within namespace '{$options['namespace']}'" + ); } } - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) { - $message = sprintf('Error touching cache item (in %s@%d): %s', $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - touch($keyInfo['filespec'] . '.dat'); - restore_error_handler(); + ErrorHandler::start(); + $touch = touch($keyInfo['filespec'] . '.dat'); + $error = ErrorHandler::stop(); + if (!$touch) { + throw new Exception\RuntimeException( + "Error touching file '{$file}'", 0, $error + ); + } } /** @@ -1591,15 +1600,17 @@ protected function rmDir($dir, $prefix) $ret = true; foreach ($glob as $subdir) { - // ignore not empty directories // skip removing current directory if removing of sub-directory failed - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) { - // ignore rmdir errors - return true; - }, E_WARNING); - $ret = $this->rmDir($subdir, $prefix) && rmdir($subdir); - restore_error_handler(); + if ($this->rmDir($subdir, $prefix)) { + // ignore not empty directories + ErrorHandler::start(); + $ret = rmdir($subdir) && $ret; + ErrorHandler::stop(); + } else { + $ret = false; + } } + return $ret; } @@ -1613,28 +1624,31 @@ protected function rmDir($dir, $prefix) */ protected function getKeyInfo($key, $ns) { - $options = $this->getOptions(); - $lastInfoId = $ns . $options->getNamespaceSeparator() . $key; + $lastInfoId = $ns . $this->getOptions()->getNamespaceSeparator() . $key; if ($this->lastInfoId == $lastInfoId) { return $this->lastInfo; } $filespec = $this->getFileSpec($key, $ns); + $file = $filespec . '.dat'; - set_error_handler(function($errno, $errstr = '') { - return true; - }, E_WARNING); - $filemtime = filemtime($filespec . '.dat'); - restore_error_handler(); - - if ($filemtime === false) { + if (!file_exists($file)) { return false; } + ErrorHandler::start(); + $mtime = filemtime($file); + $error = ErrorHandler::stop(); + if (!$mtime) { + throw new Exception\RuntimeException( + "Error getting mtime of file '{$file}'", 0, $error + ); + } + $this->lastInfoId = $lastInfoId; $this->lastInfo = array( 'filespec' => $filespec, - 'mtime' => $filemtime, + 'mtime' => $mtime, ); return $this->lastInfo; @@ -1682,17 +1696,18 @@ protected function readInfoFile($file) return false; } - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - $message = sprintf('Corrupted info file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - $info = unserialize($this->getFileContent($file)); - restore_error_handler(); - if (!is_array($info)) { - throw new Exception\RuntimeException("Corrupted info file '{$file}'"); + $content = $this->getFileContent($file); + + ErrorHandler::start(); + $ifo = unserialize($content); + $err = ErrorHandler::stop(); + if (!is_array($ifo)) { + throw new Exception\RuntimeException( + "Corrupted info file '{$file}'", 0, $err + ); } - return $info; + return $ifo; } /** @@ -1704,59 +1719,36 @@ protected function readInfoFile($file) */ protected function getFileContent($file) { + $locking = $this->getOptions()->getFileLocking(); + + ErrorHandler::start(); + // if file locking enabled -> file_get_contents can't be used - if ($this->getOptions()->getFileLocking()) { - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - $message = sprintf( - 'Error getting contents from file "%s" (in %s@%d): %s', - $file, - $errfile, - $errline, - $errstr - ); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); + if ($locking) { $fp = fopen($file, 'rb'); - restore_error_handler(); if ($fp === false) { - throw new Exception\RuntimeException(sprintf( - 'Unknown error getting contents from file "%s"', - $file - )); - } - - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - $message = sprintf( - 'Error locking file "%s" (in %s@%d): %s', - $file, - $errfile, - $errline, - $errstr + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException( + "Error opening file '{$file}'", 0, $err ); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - $res = flock($fp, \LOCK_SH); - restore_error_handler(); - if (!$res) { - throw new Exception\RuntimeException(sprintf( - 'Unknown error locking file "%s"', $file - )); - } - - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($fp) { - if (is_resource($fp)) { - flock($fp, \LOCK_UN); - fclose($fp); - } - $message = sprintf('Error getting stream contents (in %s@%d): %s', $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - $result = stream_get_contents($fp); - restore_error_handler(); - if ($result === false) { + } + + if (!flock($fp, \LOCK_SH)) { + fclose($fp); + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException( + "Error locking file '{$file}'", 0, $err + ); + } + + $res = stream_get_contents($fp); + if ($res === false) { flock($fp, \LOCK_UN); fclose($fp); - throw new Exception\RuntimeException('Unknown error getting stream contents'); + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException( + 'Error getting stream contents', 0, $err + ); } flock($fp, \LOCK_UN); @@ -1764,18 +1756,17 @@ protected function getFileContent($file) // if file locking disabled -> file_get_contents can be used } else { - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - $message = sprintf('Error getting file contents for file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - $result = file_get_contents($file, false); - restore_error_handler(); - if ($result === false) { - throw new Exception\RuntimeException(sprintf('Unknown error getting file contents for file "%s"', $file)); + $res = file_get_contents($file, false); + if ($res === false) { + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException( + "Error getting file contents for file '{$file}'", 0, $err + ); } } - return $result; + ErrorHandler::stop(); + return $res; } /** @@ -1792,33 +1783,36 @@ protected function putFileContent($file, $data) $locking = $options->getFileLocking(); $blocking = $locking ? $options->getFileBlocking() : false; + ErrorHandler::start(); + if ($locking && !$blocking) { - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - $message = sprintf('Error opening file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); $fp = fopen($file, 'cb'); - restore_error_handler(); if (!$fp) { - throw new Exception\RuntimeException(sprintf('Unknown error opening file "%s"', $file)); + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException( + "Error opening file '{$file}'", 0, $err + ); } if(!flock($fp, \LOCK_EX | \LOCK_NB, $wouldblock)) { fclose($fp); - + $err = ErrorHandler::stop(); if ($wouldblock) { - throw new Exception\LockedException("File '{$file}' locked"); + throw new Exception\LockedException("File '{$file}' locked", 0, $err); } else { - throw new Exception\RuntimeException("Can't lock file '{$file}'"); + throw new Exception\RuntimeException("Error locking file '{$file}'", 0, $err); } } if (!fwrite($fp, $data)) { - throw new Exception\RuntimeException('Unable to write cache file'); + fclose($fp); + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException("Error writing file '{$file}'", 0, $err); } if (!ftruncate($fp, strlen($data))) { - throw new Exception\RuntimeException('Unable to truncate cache file'); + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException("Error truncating file '{$file}'", 0, $err); } flock($fp, \LOCK_UN); @@ -1829,17 +1823,16 @@ protected function putFileContent($file, $data) $flags = $flags | \LOCK_EX; } - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) { - $message = sprintf('Error writing file (in %s@%d): %s', $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); - $result = file_put_contents($file, $data, $flags); - restore_error_handler(); - if ($result === false ) { - throw new Exception\RuntimeException(sprintf('Failed to write cache file ("%s") with data "%s"', $file, json_encode($data))); + $bytes = strlen($data); + if (file_put_contents($file, $data, $flags) !== $bytes) { + $err = ErrorHandler::stop(); + throw new Exception\RuntimeException( + "Error putting {$bytes} bytes to file '{$file}'", 0, $err + ); } } + ErrorHandler::stop(); return true; } @@ -1857,17 +1850,15 @@ protected function unlink($file) return; } - set_error_handler(function($errno, $errstr = '', $errfile = '', $errline = 0) use ($file) { - $message = sprintf('Error unlinking file "%s" (in %s@%d): %s', $file, $errfile, $errline, $errstr); - throw new Exception\RuntimeException($message, $errno); - }, E_WARNING); + ErrorHandler::start(); $res = unlink($file); - restore_error_handler(); - if (!$res) { - // only throw exception if file still exists after deleting - if (file_exists($file)) { - throw new Exception\RuntimeException(sprintf('Unknown error unlinking file "%s"; file still exists', $file)); - } + $err = ErrorHandler::stop(); + + // only throw exception if file still exists after deleting + if (!$res && file_exists($file)) { + throw new Exception\RuntimeException( + "Error unlinking file '{$file}'; file still exists", 0, $err + ); } } diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 0ee6c396d..55596271f 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -21,7 +21,8 @@ namespace ZendTest\Cache\Storage\Adapter; use Zend\Cache\Storage\Adapter, - Zend\Cache; + Zend\Cache, + Zend\Stdlib\ErrorHandler; /** * PHPUnit test case @@ -69,6 +70,15 @@ public function setUp() ); } + public function tearDown() + { + // be sure the error handler has been stopped + if (ErrorHandler::started()) { + ErrorHandler::stop(); + $this->fail('ErrorHandler not stopped'); + } + } + public function testOptionNamesValid() { $options = $this->_storage->getOptions()->toArray(); From e96fdefe30218c64c0639a73c6490ebfcd73d57a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 19:14:16 +0100 Subject: [PATCH 195/311] fixed missing use of Zend\Cache\Exception --- src/Storage/Plugin/IgnoreUserAbort.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php index 0fe2f8402..d8607156f 100644 --- a/src/Storage/Plugin/IgnoreUserAbort.php +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -21,7 +21,8 @@ namespace Zend\Cache\Storage\Plugin; -use Zend\Cache\Storage\Adapter, +use Zend\Cache\Exception, + Zend\Cache\Storage\Adapter, Zend\Cache\Storage\Event, Zend\EventManager\EventCollection; From 1588f40c73a915587f0f179e9dadf896d257c62f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 19:16:38 +0100 Subject: [PATCH 196/311] fixed use of undefined validabe $value --- src/Storage/Adapter/AbstractZendServer.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 121fe7424..9ee2534b6 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -427,7 +427,6 @@ public function removeItem($key, array $options = array()) $this->normalizeOptions($options); $args = new ArrayObject(array( 'key' => & $key, - 'value' => & $value, 'options' => & $options, )); From 992ffef0840c650d0678734ccfce6d68543d650f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 19:31:20 +0100 Subject: [PATCH 197/311] fixed use of undefined variable $value and a typo on event args --- src/Storage/Adapter/Apc.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index c9f4e0bd3..81043f7e6 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -834,7 +834,6 @@ public function removeItem($key, array $options = array()) $this->normalizeKey($key); $args = new ArrayObject(array( 'key' => & $key, - 'value' => & $value, 'options' => & $options, )); @@ -1076,7 +1075,7 @@ public function getDelayed(array $keys, array $options = array()) } $args = new ArrayObject(array( - 'key' => & $key, + 'keys' => & $keys, 'options' => & $options, )); From 07094a8796aa92972747a0f87f7f0bfd795712ab Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 19:37:19 +0100 Subject: [PATCH 198/311] fixed some undefined variables on filesystem adapter --- src/Storage/Adapter/Filesystem.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 351b6c512..1bee7de81 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1162,7 +1162,7 @@ protected function internalSetItem($key, $value, array &$options) $error = ErrorHandler::stop(); if (!$mkdir) { throw new Exception\RuntimeException( - "Error creating directory '{$file}'", 0, $error + "Error creating directory '{$path}'", 0, $error ); } } @@ -1171,7 +1171,7 @@ protected function internalSetItem($key, $value, array &$options) $info = null; if ($baseOptions->getReadControl()) { - $info['hash'] = Utils::generateHash($this->getReadControlAlgo(), $data, true); + $info['hash'] = Utils::generateHash($this->getReadControlAlgo(), $value, true); $info['algo'] = $baseOptions->getReadControlAlgo(); } @@ -1368,7 +1368,7 @@ protected function internalTouchItem($key, array &$options) $error = ErrorHandler::stop(); if (!$touch) { throw new Exception\RuntimeException( - "Error touching file '{$file}'", 0, $error + "Error touching file '{$keyInfo['filespec']}.dat'", 0, $error ); } } @@ -1443,19 +1443,19 @@ protected function fetchByGlob() // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - if (!isset($meta['tags']) || count(array_diff($opts['tags'], $meta['tags'])) > 0) { + if (!isset($meta['tags']) || count(array_diff($options['tags'], $meta['tags'])) > 0) { continue; } // if MATCH_NO_TAGS mode -> check if no given tag available in current cache } elseif( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - if (isset($meta['tags']) && count(array_diff($opts['tags'], $meta['tags'])) != count($opts['tags'])) { + if (isset($meta['tags']) && count(array_diff($options['tags'], $meta['tags'])) != count($options['tags'])) { continue; } // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache } elseif ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - if (!isset($meta['tags']) || count(array_diff($opts['tags'], $meta['tags'])) == count($opts['tags'])) { + if (!isset($meta['tags']) || count(array_diff($options['tags'], $meta['tags'])) == count($options['tags'])) { continue; } @@ -1541,7 +1541,7 @@ protected function clearByPrefix($prefix, $mode, array &$opts) // check tags only if one of the tag matching mode is selected if (($mode & 070) > 0) { - $info = $this->readInfoFile($filespec . '.ifo'); + $info = $this->readInfoFile($pathnameSpec . '.ifo'); // if MATCH_TAGS mode -> check if all given tags available in current cache if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { From 5d79dcf03c2e9a21832f8f414428f017c9f66f33 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 19:41:53 +0100 Subject: [PATCH 199/311] added missing 'new' --- src/Storage/Adapter/Memory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 00bbc26ea..855b08a4b 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -657,7 +657,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) } $this->normalizeOptions($options); - $args = ArrayObject(array( + $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, 'options' => & $options, )); From 26e0eee22d19aa3acab79d532299b64e966ae9b3 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 19:46:32 +0100 Subject: [PATCH 200/311] removed not needed @ --- src/Storage/Adapter/WinCache.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 3848634e8..497fd6d2d 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -380,7 +380,7 @@ public function getMetadata($key, array $options = array()) $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $info = wincache_ucache_info(true, $internalKey); + $info = wincache_ucache_info(true, $internalKey); if (isset($info['ucache_entries'][1])) { $metadata = $info['ucache_entries'][1]; } @@ -620,7 +620,7 @@ public function addItem($key, $value, array $options = array()) } $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!@wincache_ucache_add($internalKey, $value, $options['ttl'])) { + if (!wincache_ucache_add($internalKey, $value, $options['ttl'])) { if (wincache_ucache_exists($internalKey)) { throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); } @@ -977,8 +977,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) return $eventRs->last(); } - $result= wincache_ucache_clear(); - + $result = wincache_ucache_clear(); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); From 2d2dab1341a671927b0d2b7255b55b8e6c70d5e1 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:03:59 +0100 Subject: [PATCH 201/311] removed type check of options on setOptions because it will already done by the constructor of Zend\Stdlib\Options --- src/Pattern/AbstractPattern.php | 14 -------------- src/Pattern/CallbackCache.php | 5 +++-- src/Storage/Adapter/AbstractAdapter.php | 12 ------------ src/Storage/Adapter/Apc.php | 12 ------------ src/Storage/Adapter/Filesystem.php | 12 ------------ src/Storage/Adapter/Memcached.php | 12 ------------ src/Storage/Adapter/Memory.php | 12 ------------ src/Storage/Adapter/WinCache.php | 13 +++---------- 8 files changed, 6 insertions(+), 86 deletions(-) diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index 1b319858d..72e700235 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -48,18 +48,6 @@ abstract class AbstractPattern implements Pattern */ public function setOptions(PatternOptions $options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof PatternOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object, or an PatternOptions instance; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - if (!$options instanceof PatternOptions) { $options = new PatternOptions($options); } @@ -68,8 +56,6 @@ public function setOptions(PatternOptions $options) return $this; } - - /** * Get all pattern options * diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index 148555d9b..8b5dfe76c 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -36,14 +36,15 @@ class CallbackCache extends AbstractPattern { /** * Set options - * - * @param PatternOptions $options + * + * @param PatternOptions $options * @return CallbackCache * @throws Exception\InvalidArgumentException if missing storage option */ public function setOptions(PatternOptions $options) { parent::setOptions($options); + if (!$options->getStorage()) { throw new Exception\InvalidArgumentException("Missing option 'storage'"); } diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index c75025e82..37e1f9156 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -141,18 +141,6 @@ public function __destruct() */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof AdapterOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object, or an AdapterOptions instance; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - if (!$options instanceof AdapterOptions) { $options = new AdapterOptions($options); } diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 81043f7e6..08110fb73 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -118,18 +118,6 @@ public function __construct($options = null) */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof ApcOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object, or an ApcOptions instance; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - if (!$options instanceof ApcOptions) { $options = new ApcOptions($options); } diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 1bee7de81..9ae1464a5 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -79,18 +79,6 @@ class Filesystem extends AbstractAdapter */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof FilesystemOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object, or an FilesystemOptions instance; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - if (!$options instanceof FilesystemOptions) { $options = new FilesystemOptions($options); } diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index c46966c1d..c706025d8 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -93,18 +93,6 @@ public function __construct($options = null) */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof MemcachedOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object, or a MemcachedOptions object; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - if (!$options instanceof MemcachedOptions) { $options = new MemcachedOptions($options); } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 855b08a4b..9517dde6e 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -64,18 +64,6 @@ class Memory extends AbstractAdapter */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof MemoryOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object, or an MemoryOptions instance; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); - } - if (!$options instanceof MemoryOptions) { $options = new MemoryOptions($options); } diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 497fd6d2d..55a51195b 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -81,17 +81,10 @@ public function __construct($options = null) */ public function setOptions($options) { - if (!is_array($options) - && !$options instanceof Traversable - && !$options instanceof WinCacheOptions - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects an array, a Traversable object; ' - . 'received "%s"', - __METHOD__, - (is_object($options) ? get_class($options) : gettype($options)) - )); + if (!$options instanceof WinCacheOptions) { + $options = new WinCacheOptions($options); } + $this->options = $options; return $this; } From 31767bb48b0de54fb962c7445b729206c27d9e1f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:06:38 +0100 Subject: [PATCH 202/311] fixed undefined variable $mask, should be $umask --- src/Pattern/PatternOptions.php | 72 +++++++++++++++++----------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 1955c510b..53a99a281 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -189,7 +189,7 @@ public function setCacheByDefault($cacheByDefault) $this->cacheByDefault = $cacheByDefault; return $this; } - + /** * Do we cache by default? * @@ -220,7 +220,7 @@ public function setCacheOutput($cacheOutput) $this->cacheOutput = (bool) $cacheOutput; return $this; } - + /** * Will we cache output? * @@ -253,7 +253,7 @@ public function setClass($class) $this->class = $class; return $this; } - + /** * Get class name * @@ -281,7 +281,7 @@ public function setClassCacheMethods(array $classCacheMethods) $this->classCacheMethods = $this->recursiveStrtolower($classCacheMethods); return $this; } - + /** * Get list of methods from which to cache return values * @@ -309,7 +309,7 @@ public function setClassNonCacheMethods(array $classNonCacheMethods) $this->classNonCacheMethods = $this->recursiveStrtolower($classNonCacheMethods); return $this; } - + /** * Get list of methods from which NOT to cache return values * @@ -327,8 +327,8 @@ public function getClassNonCacheMethods() * Set directory permissions * * Sets {@link $dirUmask} property to inverse of provided value. - * - * @param string $dirPerm + * + * @param string $dirPerm * @return PatternOptions */ public function setDirPerm($dirPerm) @@ -347,7 +347,7 @@ public function setDirPerm($dirPerm) * Gets directory permissions * * Proxies to {@link $dirUmask} property, returning its inverse. - * + * * @return int */ public function getDirPerm() @@ -377,7 +377,7 @@ public function setDirUmask($dirUmask) $this->dirUmask = $dirUmask; return $this; } - + /** * Get directory umask * @@ -405,7 +405,7 @@ public function setFileLocking($fileLocking) $this->fileLocking = (bool) $fileLocking; return $this; } - + /** * Is file locking enabled? * @@ -423,8 +423,8 @@ public function getFileLocking() * Set file permissions * * Sets {@link $fileUmask} property to inverse of provided value. - * - * @param string $filePerm + * + * @param string $filePerm * @return PatternOptions */ public function setFilePerm($filePerm) @@ -443,7 +443,7 @@ public function setFilePerm($filePerm) * Gets file permissions * * Proxies to {@link $fileUmask} property, returning its inverse. - * + * * @return int */ public function getFilePerm() @@ -478,7 +478,7 @@ public function setFileUmask($fileUmask) $this->fileUmask = $fileUmask; return $this; } - + /** * Get file umask * @@ -503,7 +503,7 @@ public function setIndexFilename($indexFilename) $this->indexFilename = (string) $indexFilename; return $this; } - + /** * Get value for index filename * @@ -530,7 +530,7 @@ public function setObject($object) $this->object = $object; return $this; } - + /** * Get object to cache * @@ -555,7 +555,7 @@ public function setObjectCacheMagicProperties($objectCacheMagicProperties) $this->objectCacheMagicProperties = (bool) $objectCacheMagicProperties; return $this; } - + /** * Should we cache magic properties? * @@ -581,7 +581,7 @@ public function setObjectCacheMethods(array $objectCacheMethods) $this->objectCacheMethods = $this->normalizeObjectMethods($objectCacheMethods); return $this; } - + /** * Get list of object methods for which to cache return values * @@ -612,7 +612,7 @@ public function setObjectKey($objectKey) } return $this; } - + /** * Get object key * @@ -638,7 +638,7 @@ public function setObjectNonCacheMethods(array $objectNonCacheMethods) $this->objectNonCacheMethods = $this->normalizeObjectMethods($objectNonCacheMethods); return $this; } - + /** * Get list of object methods for which NOT to cache return values * @@ -663,7 +663,7 @@ public function setPublicDir($publicDir) $this->publicDir = (string) $publicDir; return $this; } - + /** * Get location of public directory * @@ -695,7 +695,7 @@ public function setStorage($storage) $this->storage = $storage; return $this; } - + /** * Get storage adapter * @@ -727,7 +727,7 @@ public function setTagKey($tagKey) $this->tagKey = $tagKey; return $this; } - + /** * Get tag key * @@ -752,7 +752,7 @@ public function setTags(array $tags) $this->tags = $tags; return $this; } - + /** * Get tags * @@ -781,7 +781,7 @@ public function setTagStorage($tagStorage) $this->tagStorage = $tagStorage; return $this; } - + /** * Get storage adapter for tags * @@ -798,8 +798,8 @@ public function getTagStorage() /** * Recursively apply strtolower on all values of an array, and return as a * list of unique values - * - * @param array $array + * + * @param array $array * @return array */ protected function recursiveStrtolower(array $array) @@ -811,11 +811,11 @@ protected function recursiveStrtolower(array $array) /** * Normalize object methods - * - * Recursively casts values to lowercase, then determines if any are in a + * + * Recursively casts values to lowercase, then determines if any are in a * list of methods not handled, raising an exception if so. * - * @param array $methods + * @param array $methods * @return array * @throws Exception\InvalidArgumentException */ @@ -836,13 +836,13 @@ protected function normalizeObjectMethods(array $methods) * * Allows specifying a umask as either an octal or integer. If the umask * fails required permissions, raises an exception. - * - * @param int|string $mask - * @param callable Callback used to verify the umask is acceptable for the given purpose + * + * @param int|string $umask + * @param callable $comparison Callback used to verify the umask is acceptable for the given purpose * @return int * @throws Exception\InvalidArgumentException */ - protected function normalizeUmask($mask, $comparison) + protected function normalizeUmask($umask, $comparison) { if (is_string($umask)) { $umask = octdec($umask); @@ -857,8 +857,8 @@ protected function normalizeUmask($mask, $comparison) /** * Create a storage object from a given specification - * - * @param array|string|StorageAdapter $storage + * + * @param array|string|StorageAdapter $storage * @return StorageAdapter */ protected function storageFactory($storage) From 53cd1e6a5ab3629cb6bed4756754f5f05ff3b74d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:16:38 +0100 Subject: [PATCH 203/311] fixed undefined variable $value --- src/Storage/Adapter/WinCache.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 55a51195b..fafbc8464 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -780,7 +780,6 @@ public function removeItem($key, array $options = array()) $this->normalizeKey($key); $args = new ArrayObject(array( 'key' => & $key, - 'value' => & $value, 'options' => & $options, )); From ada67171b5c0dbbfdbd0b28089924caeb73b4299 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:19:32 +0100 Subject: [PATCH 204/311] Assignment in condition --- src/Pattern/CallbackCache.php | 3 ++- src/Storage/Adapter/Filesystem.php | 5 +++-- src/Storage/Plugin/ExceptionHandler.php | 5 +++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index 8b5dfe76c..3001f5659 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -73,7 +73,8 @@ public function call($callback, array $args = array(), array $options = array()) return $rs[0]; } - if ( ($cacheOutput = $classOptions->getCacheOutput()) ) { + $cacheOutput = $classOptions->getCacheOutput(); + if ($cacheOutput) { ob_start(); ob_implicit_flush(false); } diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 9ae1464a5..789f3e549 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1023,7 +1023,7 @@ public function optimize(array $options = array()) return $eventRs->last(); } - if ( ($dirLevel = $baseOptions->getDirLevel()) ) { + if ($baseOptions->getDirLevel()) { // removes only empty directories $this->rmDir( $baseOptions->getCacheDir(), @@ -1323,7 +1323,8 @@ protected function internalGetMetadata($key, array &$options) $keyInfo['atime'] = fileatime($keyInfo['filespec'] . '.dat'); } - if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) ) { + $info = $this->readInfoFile($keyInfo['filespec'] . '.ifo'); + if ($info) { return $keyInfo + $info; } diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 6aea248e7..1844afe7b 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -145,8 +145,9 @@ public function detach(EventCollection $eventCollection) */ public function onException(ExceptionEvent $event) { - $options = $this->getOptions(); - if (($callback = $options->getExceptionCallback())) { + $options = $this->getOptions(); + $callback = $options->getExceptionCallback(); + if ($callback) { call_user_func($callback, $event->getException()); } From f0d494393cff7d11f8901bfa2ebdc02c73b38971 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:20:45 +0100 Subject: [PATCH 205/311] added missing ArrayObject --- src/Storage/Adapter/ZendServerDisk.php | 3 ++- src/Storage/Adapter/ZendServerShm.php | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index fac6cb907..6b98e346f 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -21,7 +21,8 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Utils, +use ArrayObject, + Zend\Cache\Utils, Zend\Cache\Exception; /** diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 4d71ead47..cc70b2b0b 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -21,7 +21,8 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception; +use ArrayObject, + Zend\Cache\Exception; /** * @category Zend From a22fa4aee1e2567f4bef9a10c28b672b9e435a3d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:23:01 +0100 Subject: [PATCH 206/311] fixed undefined variable $key, should be $internalKey --- src/Storage/Adapter/ZendServerDisk.php | 14 +++++++------- src/Storage/Adapter/ZendServerShm.php | 14 +++++++------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index 6b98e346f..85a930f54 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -91,12 +91,12 @@ public function getCapacity(array $options = array()) * @return void * @throws Exception\RuntimeException */ - protected function zdcStore($key, $value, $ttl) + protected function zdcStore($internalKey, $value, $ttl) { - if (!zend_disk_cache_store($key, $value, $ttl)) { + if (!zend_disk_cache_store($internalKey, $value, $ttl)) { $valueType = gettype($value); throw new Exception\RuntimeException( - "zend_disk_cache_store($internalKey, <{$valueType}>, {$options['ttl']}) failed" + "zend_disk_cache_store($internalKey, <{$valueType}>, {$ttl}) failed" ); } } @@ -108,9 +108,9 @@ protected function zdcStore($key, $value, $ttl) * @return mixed The stored value or FALSE if item wasn't found * @throws Exception\RuntimeException */ - protected function zdcFetch($key) + protected function zdcFetch($internalKey) { - return zend_disk_cache_fetch((string)$key); + return zend_disk_cache_fetch((string)$internalKey); } /** @@ -136,9 +136,9 @@ protected function zdcFetchMulti(array $internalKeys) * @return boolean * @throws Exception\RuntimeException */ - protected function zdcDelete($key) + protected function zdcDelete($internalKey) { - return zend_disk_cache_delete($key); + return zend_disk_cache_delete($internalKey); } /** diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index cc70b2b0b..f04b64bf1 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -96,12 +96,12 @@ public function getCapacity(array $options = array()) * @return void * @throws Exception\RuntimeException */ - protected function zdcStore($key, $value, $ttl) + protected function zdcStore($internalKey, $value, $ttl) { - if (!zend_shm_cache_store($key, $value, $ttl)) { + if (!zend_shm_cache_store($internalKey, $value, $ttl)) { $valueType = gettype($value); throw new Exception\RuntimeException( - "zend_disk_cache_store($internalKey, <{$valueType}>, {$options['ttl']}) failed" + "zend_disk_cache_store($internalKey, <{$valueType}>, {$ttl}) failed" ); } } @@ -113,9 +113,9 @@ protected function zdcStore($key, $value, $ttl) * @return mixed The stored value or FALSE if item wasn't found * @throws Exception\RuntimeException */ - protected function zdcFetch($key) + protected function zdcFetch($internalKey) { - return zend_shm_cache_fetch((string)$key); + return zend_shm_cache_fetch((string)$internalKey); } /** @@ -141,9 +141,9 @@ protected function zdcFetchMulti(array $internalKeys) * @return boolean * @throws Exception\RuntimeException */ - protected function zdcDelete($key) + protected function zdcDelete($internalKey) { - return zend_shm_cache_delete($key); + return zend_shm_cache_delete($internalKey); } /** From 2597e99c9e8ed9df9dd007334355a8b68400d4e5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:30:29 +0100 Subject: [PATCH 207/311] fixed call to undefined method decrementMulti on AbstractAdapter --- src/Storage/Adapter/AbstractAdapter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 37e1f9156..c03d10e47 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -726,7 +726,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->decrementMulti($key, $value, $options) && $ret; + $ret = $this->decrementItem($key, $value, $options) && $ret; } return $ret; } From 465e7b03dba3c49df20e80d6ea76b50ebac642f7 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 20:34:29 +0100 Subject: [PATCH 208/311] AbstractAdapter::incrementItems should call incrementItem internally --- src/Storage/Adapter/AbstractAdapter.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index c03d10e47..b0a046a3d 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -684,7 +684,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()) $ret = true; foreach ($keyValuePairs as $key => $value) { - $ret = $this->incrementItems($key, $value, $options) && $ret; + $ret = $this->incrementItem($key, $value, $options) && $ret; } return $ret; } From bc4058b0a7b13e393d598ad03a2faf53cab03461 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 5 Feb 2012 21:01:24 +0100 Subject: [PATCH 209/311] Now all tests of Zend\Cache\Storage\Adapter\ZendServer*-Adapters pass --- src/Storage/Adapter/AbstractZendServer.php | 9 ++++++++- test/Storage/Adapter/CommonAdapterTest.php | 2 +- test/Storage/Adapter/ZendServerDiskTest.php | 3 ++- test/Storage/Adapter/ZendServerShmTest.php | 3 ++- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 9ee2534b6..97a392b54 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -287,7 +287,14 @@ public function getMetadata($key, array $options = array()) } $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - $result = ($this->zdcFetch($internalKey) !== false) ? array() : false; + if ($this->zdcFetch($internalKey) === false) { + if (!$options['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + } + $result = false; + } else { + $result = array(); + } return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 55596271f..1d1b04e60 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -980,7 +980,7 @@ public function testTouchItem() $this->assertTrue($this->_storage->setItem('key', 'value')); // sleep 1 times before expire to touch the item - usleep($capabilities->getTtlPrecision() * 2000000); + usleep($capabilities->getTtlPrecision() * 1000000); $this->assertTrue($this->_storage->touchItem('key')); usleep($capabilities->getTtlPrecision() * 1000000); diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php index c0002748b..e061a1b89 100644 --- a/test/Storage/Adapter/ZendServerDiskTest.php +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -46,7 +46,8 @@ public function setUp() } } - $this->_storage = new Cache\Storage\Adapter\ZendServerDisk(); + $this->_options = new Cache\Storage\Adapter\AdapterOptions(); + $this->_storage = new Cache\Storage\Adapter\ZendServerDisk($this->_options); parent::setUp(); } diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index f23b8e041..4deb29640 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -51,7 +51,8 @@ public function setUp() } } - $this->_storage = new Cache\Storage\Adapter\ZendServerShm(); + $this->_options = new Cache\Storage\Adapter\AdapterOptions(); + $this->_storage = new Cache\Storage\Adapter\ZendServerShm($this->_options); parent::setUp(); } From 70def086d1237448ae8e407401b5af7b6cb0852e Mon Sep 17 00:00:00 2001 From: Mike Willbanks Date: Fri, 24 Feb 2012 16:05:30 -0600 Subject: [PATCH 210/311] updated adapter to use addServers --- src/Storage/Adapter/Memcached.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 4db849e3f..11f37970e 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -84,10 +84,7 @@ public function __construct($options = null) $options->addServer('localhost', 11211); $servers = $options->getServers(); } - - foreach ($servers as $server) { - $this->memcached->addServer($server[0], $server[1]); - } + $this->memcached->addServers($servers); } /* options */ From 62e60f09600abadef825d45516df3ad2097d4200 Mon Sep 17 00:00:00 2001 From: Mike Willbanks Date: Fri, 24 Feb 2012 16:09:55 -0600 Subject: [PATCH 211/311] updated memcached test to reflect usage --- test/Storage/Adapter/MemcachedTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index d4f801203..66706adc6 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -42,8 +42,7 @@ public function setUp() } $this->_options = new Cache\Storage\Adapter\MemcachedOptions(); - $this->_storage = new Cache\Storage\Adapter\Memcached(); - $this->_storage->setOptions($this->_options); + $this->_storage = new Cache\Storage\Adapter\Memcached($this->_options); parent::setUp(); } From 5185be687fb60448890547055f92245b18e7856b Mon Sep 17 00:00:00 2001 From: Mike Willbanks Date: Fri, 24 Feb 2012 16:19:41 -0600 Subject: [PATCH 212/311] added unit test for server handling --- test/Storage/Adapter/MemcachedTest.php | 42 ++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index 66706adc6..ef3c4cae6 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -47,6 +47,48 @@ public function setUp() parent::setUp(); } + public function testOptionsAddServer() + { + $options = new Cache\Storage\Adapter\MemcachedOptions(); + $options->addServer('127.0.0.1', 11211); + $options->addServer('localhost'); + $options->addServer('domain.com', 11215); + + $servers = array( + array('127.0.0.1', 11211), + array('localhost', 11211), + array('domain.com', 11215), + ); + + $this->assertEquals($options->getServers(), $servers); + $memcached = new Cache\Storage\Adapter\Memcached($options); + $this->assertEquals($memcached->getOptions()->getServers(), $servers); + } + + public function testOptionsSetServers() + { + $options = new Cache\Storage\Adapter\MemcachedOptions(); + $servers = array( + array('127.0.0.1', 12345), + array('localhost', 54321), + array('domain.com') + ); + + $options->setServers($servers); + $servers[2][1] = 11211; + $this->assertEquals($options->getServers(), $servers); + + $memcached = new Cache\Storage\Adapter\Memcached($options); + $this->assertEquals($memcached->getOptions()->getServers(), $servers); + } + + public function testNoOptionsSetsDefaultServer() + { + $memcached = new Cache\Storage\Adapter\Memcached(); + + $this->assertEquals($memcached->getOptions()->getServers(), array(array('localhost', 11211))); + } + public function tearDown() { if (!empty($this->_storage)) { From efac9230a7b52717b632517e5369a04e46226a47 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 28 Feb 2012 19:52:15 +0100 Subject: [PATCH 213/311] internal changes to cache adapters to simplify spizific adapters --- src/Storage/Adapter/AbstractAdapter.php | 655 ++++++++++++++--- src/Storage/Adapter/AbstractZendServer.php | 370 +++------- src/Storage/Adapter/Apc.php | 650 ++++++----------- src/Storage/Adapter/Filesystem.php | 703 +++++++------------ src/Storage/Adapter/Memcached.php | 343 ++++----- src/Storage/Adapter/Memory.php | 436 ++++-------- src/Storage/Adapter/WinCache.php | 492 +++---------- test/Storage/Adapter/AbstractAdapterTest.php | 283 ++++++-- test/Storage/TestAsset/MockAdapter.php | 8 +- 9 files changed, 1769 insertions(+), 2171 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index b0a046a3d..896ad11ac 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -30,8 +30,8 @@ Zend\Cache\Storage\Capabilities, Zend\Cache\Storage\Event, Zend\Cache\Storage\ExceptionEvent, - Zend\Cache\Storage\Plugin, Zend\Cache\Storage\PostEvent, + Zend\Cache\Storage\Plugin, Zend\EventManager\EventCollection, Zend\EventManager\EventManager; @@ -351,26 +351,136 @@ public function getPlugins() /* reading */ /** - * Get items + * Get an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return mixed Data on success and false on failure + * @throws Exception + * + * @triggers getItem.pre(PreEvent) + * @triggers getItem.post(PostEvent) + * @triggers getItem.exception(ExceptionEvent) + */ + public function getItem($key, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetItem($key, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to get an item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item or return false + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure + * @throws Exception + */ + abstract protected function internalGetItem(& $normalizedKey, array &$normalizedOptions); + + /** + * Get multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keys * @param array $options - * @return array + * @return array Associative array of existing keys and values + * @throws Exception + * + * @triggers getItems.pre(PreEvent) + * @triggers getItems.post(PostEvent) + * @triggers getItems.exception(ExceptionEvent) */ public function getItems(array $keys, array $options = array()) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { + if (!$this->getOptions()->getReadable()) { return array(); } + $this->normalizeKeys($keys); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetItems($keys, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to get multiple items. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing keys and values + * @throws Exception + */ + protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + { + // Ignore missing items by catching the exception + $normalizedOptions['ignore_missing_items'] = false; + $ret = array(); - foreach ($keys as $key) { + foreach ($normalizedKeys as $normalizedKey) { try { - $value = $this->getItem($key, $options); - if ($value !== false) { - $ret[$key] = $value; - } + $ret[$normalizedKey] = $this->internalGetItem($normalizedKey, $normalizedOptions); } catch (Exception\ItemNotFoundException $e) { // ignore missing items } @@ -380,11 +490,22 @@ public function getItems(array $keys, array $options = array()) } /** - * Checks if adapter has an item + * Test if an item exists. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param string $key - * @param array $options - * @return bool + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers hasItem.pre(PreEvent) + * @triggers hasItem.post(PostEvent) + * @triggers hasItem.exception(ExceptionEvent) */ public function hasItem($key, array $options = array()) { @@ -392,21 +513,67 @@ public function hasItem($key, array $options = array()) return false; } + $this->normalizeKey($key); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + try { - $ret = ($this->getItem($key, $options) !== false); - } catch (Exception\ItemNotFoundException $e) { - $ret = false; + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalHasItem($key, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } + } - return $ret; + /** + * Internal method to test if an item exists. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + { + try { + $this->internalGetItem($normalizedKey, $normalizedOptions); + return true; + } catch (Exception\ItemNotFoundException $e) { + return false; + } } /** - * Checks if adapter has items + * Test multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keys * @param array $options - * @return array + * @return array Array of existing keys + * @throws Exception + * + * @triggers hasItems.pre(PreEvent) + * @triggers hasItems.post(PostEvent) + * @triggers hasItems.exception(ExceptionEvent) */ public function hasItems(array $keys, array $options = array()) { @@ -414,22 +581,141 @@ public function hasItems(array $keys, array $options = array()) return array(); } - $ret = array(); - foreach ($keys as $key) { - if ($this->hasItem($key, $options)) { - $ret[] = $key; + $this->normalizeKeys($keys); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } + + $result = $this->internalHasItems($keys, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } + } - return $ret; + /** + * Internal method to test multiple items. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $keys + * @param array $options + * @return array Array of existing keys + * @throws Exception + */ + protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + { + $result = array(); + foreach ($normalizedKeys as $normalizedKey) { + if ($this->internalHasItem($normalizedKey, $normalizedOptions)) { + $result[] = $normalizedKey; + } + } + return $result; + } + + /** + * Get metadata of an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return array|boolean Metadata or false on failure + * @throws Exception + * + * @triggers getMetadata.pre(PreEvent) + * @triggers getMetadata.post(PostEvent) + * @triggers getMetadata.exception(ExceptionEvent) + */ + public function getMetadata($key, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return false; + } + + $this->normalizeKey($key); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetMetadata($key, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to get metadata of an item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return array|boolean Metadata or false on failure + * @throws Exception + */ + protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) + { + if ($this->internalHasItem($normalizedKey, $normalizedOptions)) { + return array(); + } + + if ($normalizedOptions['ignore_missing_items']) { + return false; + } + + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found on namespace '{$normalizedOptions['namespace']}'" + ); } /** - * Get Metadatas + * Get multiple metadata + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keys * @param array $options - * @return array + * @return array Associative array of existing cache ids and its metadata + * @throws Exception + * + * @triggers getMetadatas.pre(PreEvent) + * @triggers getMetadatas.post(PostEvent) + * @triggers getMetadatas.exception(ExceptionEvent) */ public function getMetadatas(array $keys, array $options = array()) { @@ -437,29 +723,143 @@ public function getMetadatas(array $keys, array $options = array()) return array(); } - $ret = array(); - foreach ($keys as $key) { + $this->normalizeKeys($keys); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetMetadatas($keys, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to get multiple metadata + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing cache ids and its metadata + * @throws Exception + */ + protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + { + // Ignoore missing items - don't need to throw + catch the ItemNotFoundException + // because on found metadata an array will be returns and on a missing item false + $normalizedOptions['ignore_missing_items'] = true; + + $result = array(); + foreach ($normalizedKeys as $normalizedKey) { try { - $meta = $this->getMetadata($key, $options); - if ($meta !== false) { - $ret[$key] = $meta; + $metadata = $this->internalGetMetadata($normalizedKey, $normalizedOptions); + if ($metadata !== false) { + $result[$normalizedKey] = $metadata; } } catch (Exception\ItemNotFoundException $e) { // ignore missing items } } - return $ret; + return $result; } /* writing */ + /** + * Store an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers setItem.pre(PreEvent) + * @triggers setItem.post(PostEvent) + * @triggers setItem.exception(ExceptionEvent) + */ + public function setItem($key, $value, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalSetItem($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to store an item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + abstract protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions); + /** - * Set items + * Store multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keyValuePairs * @param array $options - * @return bool + * @return boolean + * @throws Exception + * + * @triggers setItems.pre(PreEvent) + * @triggers setItems.post(PostEvent) + * @triggers setItems.exception(ExceptionEvent) */ public function setItems(array $keyValuePairs, array $options = array()) { @@ -467,12 +867,46 @@ public function setItems(array $keyValuePairs, array $options = array()) return false; } - $ret = true; - foreach ($keyValuePairs as $key => $value) { - $ret = $this->setItem($key, $value, $options) && $ret; + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalSetItems($keyValuePairs, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } + } - return $ret; + /** + * Internal method to store multiple items. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + { + $result = true; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $result = $this->internalSetItem($normalizedKey, $value, $normalizedOptions) && $result; + } + return $result; } /** @@ -527,6 +961,7 @@ public function replaceItem($key, $value, array $options = array()) if (!$this->hasItem($key, $options)) { throw new Exception\ItemNotFoundException("Key '{$key}' doen't exists"); } + return $this->setItem($key, $value, $options); } @@ -627,7 +1062,7 @@ public function touchItems(array $keys, array $options = array()) } /** - * Remove items + * Remove multiple items. * * @param array $keys * @param array $options @@ -731,65 +1166,67 @@ public function decrementItems(array $keyValuePairs, array $options = array()) return $ret; } - /* non-blocking */ - - /** - * Get delayed - * - * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - select optional - * - An array of the information the returned item contains - * (Default: array('key', 'value')) - * - callback optional - * - An result callback will be invoked for each item in the result set. - * - The first argument will be the item array. - * - The callback does not have to return anything. - * - * @param array $keys - * @param array $options - * @return bool - * @throws Exception\InvalidArgumentException|Exception\RuntimeException - */ - public function getDelayed(array $keys, array $options = array()) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - if (!$this->getOptions()->getReadable()) { - return false; - } elseif (!$keys) { - // empty statement - return true; - } - - $this->normalizeOptions($options); - if (!isset($options['select'])) { - $options['select'] = array('key', 'value'); - } - - $this->stmtOptions = array_merge($this->getOptions()->toArray(), $options); - $this->stmtKeys = $keys; - $this->stmtActive = true; - - if (isset($options['callback'])) { - $callback = $options['callback']; - if (!is_callable($callback, false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - while ( ($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - return true; + /* non-blocking */ + + /** + * Get delayed + * + * Options: + * - ttl optional + * - The time-to-live (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - select optional + * - An array of the information the returned item contains + * (Default: array('key', 'value')) + * - callback optional + * - An result callback will be invoked for each item in the result set. + * - The first argument will be the item array. + * - The callback does not have to return anything. + * + * @param array $keys + * @param array $options + * @return bool + * @throws Exception\InvalidArgumentException|Exception\RuntimeException + */ + public function getDelayed(array $keys, array $options = array()) + { + if ($this->stmtActive) { + throw new Exception\RuntimeException('Statement already in use'); + } + + if (!$this->getOptions()->getReadable()) { + return false; + } elseif (!$keys) { + // empty statement + return true; + } + + $this->normalizeOptions($options); + if (!isset($options['select'])) { + $options['select'] = array('key', 'value'); + } + + $this->stmtOptions = array_merge($this->getOptions()->toArray(), $options); + $this->stmtKeys = $keys; + $this->stmtActive = true; + + if (isset($options['callback'])) { + $callback = $options['callback']; + if (!is_callable($callback, false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } + + while ( ($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + return true; } + /* find */ + /** * Find * @@ -1088,13 +1525,36 @@ protected function normalizeKey(&$key) { $key = (string) $key; - if (($p = $this->getOptions()->getKeyPattern()) && !preg_match($p, $key)) { + if ($key === '') { + throw new Exception\InvalidArgumentException( + "An empty key isn't allowed" + ); + } elseif (($p = $this->getOptions()->getKeyPattern()) && !preg_match($p, $key)) { throw new Exception\InvalidArgumentException( "The key '{$key}' doesn't match agains pattern '{$p}'" ); } } + /** + * Validates and normalizes multiple keys + * + * @param array $keys + * @return array + * @throws Exception\InvalidArgumentException On an invalid key + */ + protected function normalizeKeys(array &$keys) + { + if (!$keys) { + throw new Exception\InvalidArgumentException( + "An empty list of keys isn't allowed" + ); + } + + array_walk($keys, array($this, 'normalizeKey')); + $keys = array_values(array_unique($keys)); + } + /** * Return registry of plugins * @@ -1107,4 +1567,5 @@ protected function getPluginRegistry() } return $this->pluginRegistry; } + } diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 97a392b54..8253a5186 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -45,261 +45,112 @@ abstract class AbstractZendServer extends AbstractAdapter /* reading */ /** - * Get an item. + * Internal method to get an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional + * - namespace + * - The namespace to use + * - ignore_missing_items * - Throw exception on missing item or return false * - * @param string $key - * @param array $options - * @return mixed Value on success and false on failure + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure * @throws Exception - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array()) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { - if (!$this->getOptions()->getReadable()) { - return false; - } - - $this->normalizeKey($key); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - $result = $this->zdcFetch($internalKey); - if ($result === false) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - - $result = false; - } elseif (array_key_exists('token', $options)) { - $options['token'] = $result; + $internalKey = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR . $normalizedKey; + $result = $this->zdcFetch($internalKey); + if ($result === false) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + } elseif (array_key_exists('token', $normalizedOptions)) { + $normalizedOptions['token'] = $result; } + + return $result; } /** - * Get multiple items. + * Internal method to get multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param array $keys - * @param array $options - * @return array Assoziative array of existing keys and values or false on failure + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing keys and values * @throws Exception - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) { - if (!$this->getOptions()->getReadable()) { - return array(); - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; - $internalKeys = array(); - foreach ($keys as &$key) { - $this->normalizeKey($key); - $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - } - - $fetch = $this->zdcFetchMulti($internalKeys); - $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); - $result = array(); - foreach ($fetch as $k => &$v) { - $result[ substr($k, $prefixL) ] = $v; - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; } - } - /** - * Test if an item exists. - * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param string $key - * @param array $options - * @return boolean - * @throws Exception - * - * @triggers hasItem.pre(PreEvent) - * @triggers hasItem.post(PostEvent) - * @triggers hasItem.exception(ExceptionEvent) - */ - public function hasItem($key, array $options = array()) - { - if (!$this->getOptions()->getReadable()) { - return false; + $fetch = $this->zdcFetchMulti($internalKeys); + $prefixL = strlen($prefix); + $result = array(); + foreach ($fetch as $k => & $v) { + $result[ substr($k, $prefixL) ] = $v; } - $this->normalizeKey($key); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - $result = ($this->zdcFetch($internalKey) !== false); - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $result; } /** - * Test if multiple items exists. + * Internal method to test if an item exists. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers hasItems.pre(PreEvent) - * @triggers hasItems.post(PostEvent) - * @triggers hasItems.exception(ExceptionEvent) */ - public function hasItems(array $keys, array $options = array()) + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - if (!$this->getOptions()->getReadable()) { - return array(); - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeys = array(); - foreach ($keys as &$key) { - $this->normalizeKey($key); - $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - } - - $fetch = $this->zdcFetchMulti($internalKeys); - $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); - $result = array(); - foreach ($fetch as $k => &$v) { - $result[] = substr($k, $prefixL); - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; + return ($this->zdcFetch($prefix . $normalizedKey) !== false); } /** - * Get metadata of an item. + * Internal method to test multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use * - * @param string $key + * @param array $keys * @param array $options - * @return array|boolean Metadata or false on failure + * @return array Array of existing keys * @throws Exception - * - * @triggers getMetadata.pre(PreEvent) - * @triggers getMetadata.post(PostEvent) - * @triggers getMetadata.exception(ExceptionEvent) */ - public function getMetadata($key, array $options = array()) + protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) { - if (!$this->getOptions()->getReadable()) { - return false; - } - - $this->normalizeKey($key); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; - $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - if ($this->zdcFetch($internalKey) === false) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - $result = false; - } else { - $result = array(); - } + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; + } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $fetch = $this->zdcFetchMulti($internalKeys); + $prefixL = strlen($prefix); + $result = array(); + foreach ($fetch as $internalKey => & $value) { + $result[] = substr($internalKey, $prefixL); } + + return $result; } /** @@ -309,101 +160,54 @@ public function getMetadata($key, array $options = array()) * - namespace optional * - The namespace to use (Default: namespace of object) * - * @param array $keys - * @param array $options - * @return array - * @throws Exception\ItemNotFoundException + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array|boolean * * @triggers getMetadatas.pre(PreEvent) * @triggers getMetadatas.post(PostEvent) * @triggers getMetadatas.exception(ExceptionEvent) */ - public function getMetadatas(array $keys, array $options = array()) + protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) { - if (!$this->getOptions()->getReadable()) { - return array(); + $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeys = array(); - foreach ($keys as &$key) { - $this->normalizeKey($key); - $internalKeys[] = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - } - - $fetch = $this->zdcFetchMulti($internalKeys); - $prefixL = strlen($options['namespace'] . self::NAMESPACE_SEPARATOR); - $result = array(); - foreach ($fetch as $k => &$v) { - $result[ substr($k, $prefixL) ] = array(); - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $fetch = $this->zdcFetchMulti($internalKeys); + $prefixL = strlen($prefix); + $result = array(); + foreach ($fetch as $internalKey => $value) { + $result[ substr($internalKey, $prefixL) ] = array(); } + + return $result; } /* writing */ /** - * Store an item. + * Internal method to store an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeKey($key); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - $this->zdcStore($internalKey, $value, $options['ttl']); - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $internalKey = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR . $normalizedKey; + $this->zdcStore($internalKey, $value, $normalizedOptions['ttl']); + return true; } /** diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 08110fb73..9deccb8c3 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -144,223 +144,128 @@ public function getOptions() /* reading */ /** - * Get an item. + * Internal method to get an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional + * - namespace + * - The namespace to use + * - ignore_missing_items * - Throw exception on missing item or return false * - * @param string $key - * @param array $options - * @return mixed Value on success and false on failure + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure * @throws Exception - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array()) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $success = false; + $result = apc_fetch($internalKey, $success); + + if (!$success) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = apc_fetch($internalKey, $success); - if (!$success) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - $result = false; - } else { - if (array_key_exists('token', $options)) { - $options['token'] = $result; - } + $result = false; + } else { + if (array_key_exists('token', $normalizedOptions)) { + $normalizedOptions['token'] = $result; } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $result; } /** - * Get multiple items. + * Internal method to get multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param array $keys - * @param array $options - * @return array Assoziative array of existing keys and values or false on failure + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing keys and values * @throws Exception - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); - } + $namespaceSep = $this->getOptions()->getNamespaceSeparator(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $namespaceSep = $baseOptions->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $namespaceSep . $key; - } - - $fetch = apc_fetch($internalKeys); - if (!$options['ignore_missing_items']) { - if (count($keys) != count($fetch)) { - $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); - throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); - } - } + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; + } - // remove namespace prefix - $prefixL = strlen($options['namespace'] . $namespaceSep); - $result = array(); - foreach ($fetch as $internalKey => &$value) { - $result[ substr($internalKey, $prefixL) ] = $value; + $fetch = apc_fetch($internalKeys); + if (!$normalizedOptions['ignore_missing_items']) { + if (count($normalizedKeys) != count($fetch)) { + $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); + throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); } + } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + // remove namespace prefix + $prefixL = strlen($prefix); + $result = array(); + foreach ($fetch as $internalKey => & $value) { + $result[ substr($internalKey, $prefixL) ] = $value; } + + return $result; } /** - * Test if an item exists. + * Internal method to test if an item exists. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers hasItem.pre(PreEvent) - * @triggers hasItem.post(PostEvent) - * @triggers hasItem.exception(ExceptionEvent) */ - public function hasItem($key, array $options = array()) + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = apc_exists($internalKey); - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + return apc_exists($prefix . $normalizedKey); } /** - * Test if multiple items exists. + * Internal method to test multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param string $key + * @param array $keys * @param array $options - * @return boolean + * @return array Array of existing keys * @throws Exception - * - * @triggers hasItems.pre(PreEvent) - * @triggers hasItems.post(PostEvent) - * @triggers hasItems.exception(ExceptionEvent) */ - public function hasItems(array $keys, array $options = array()) + protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $exists = apc_exists($internalKeys); + $result = array(); + $prefixL = strlen($prefix); + foreach ($exists as $internalKey => $bool) { + if ($bool === true) { + $result[] = substr($internalKey, $prefixL); } - - $namespaceSep = $baseOptions->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $namespaceSep . $key; - } - - $exists = apc_exists($internalKeys); - $result = array(); - $prefixL = strlen($options['namespace'] . $namespaceSep); - foreach ($exists as $internalKey => $bool) { - if ($bool === true) { - $result[] = substr($internalKey, $prefixL); - } - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $result; } /** @@ -372,8 +277,8 @@ public function hasItems(array $keys, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return array|boolean Metadata or false on failure * @throws Exception * @@ -381,50 +286,29 @@ public function hasItems(array $keys, array $options = array()) * @triggers getMetadata.post(PostEvent) * @triggers getMetadata.exception(ExceptionEvent) */ - public function getMetadata($key, array $options = array()) + protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + // @see http://pecl.php.net/bugs/bug.php?id=22564 + if (!apc_exists($internalKey)) { + $metadata = false; + } else { $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; $regexp = '/^' . preg_quote($internalKey, '/') . '$/'; $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); $metadata = $it->current(); + } - // @see http://pecl.php.net/bugs/bug.php?id=22564 - if (!apc_exists($internalKey)) { - $metadata = false; - } - - if (!$metadata) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - } else { - $this->normalizeMetadata($metadata); + if (!$metadata) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - - return $this->triggerPost(__FUNCTION__, $args, $metadata); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + } else { + $this->normalizeMetadata($metadata); } + + return $metadata; } /** @@ -434,8 +318,8 @@ public function getMetadata($key, array $options = array()) * - namespace optional * - The namespace to use (Default: namespace of object) * - * @param array $keys - * @param array $options + * @param array $normalizedKeys + * @param array $normalizedOptions * @return array * @throws Exception\ItemNotFoundException * @@ -443,175 +327,95 @@ public function getMetadata($key, array $options = array()) * @triggers getMetadatas.post(PostEvent) * @triggers getMetadatas.exception(ExceptionEvent) */ - public function getMetadatas(array $keys, array $options = array()) + protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + $keysRegExp = array(); + foreach ($normalizedKeys as $normalizedKey) { + $keysRegExp[] = preg_quote($normalizedKey, '/'); } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $keysRegExp = array(); - foreach ($keys as $key) { - $keysRegExp[] = preg_quote($key, '/'); - } - $regexp = '/^' - . preg_quote($options['namespace'] . $baseOptions->getNamespaceSeparator(), '/') - . '(' . implode('|', $keysRegExp) . ')' - . '$/'; - $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; - - $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); - $result = array(); - $prefixL = strlen($options['namespace'] . $baseOptions->getNamespaceSeparator()); - foreach ($it as $internalKey => $metadata) { - // @see http://pecl.php.net/bugs/bug.php?id=22564 - if (!apc_exists($internalKey)) { - continue; - } - - $this->normalizeMetadata($metadata); - $result[ substr($internalKey, $prefixL) ] = & $metadata; - } - - if (!$options['ignore_missing_items']) { - if (count($keys) != count($result)) { - $missing = implode("', '", array_diff($keys, array_keys($result))); - throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $regexp = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $keysRegExp) . ')' . '$/'; + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + + $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $result = array(); + $prefixL = strlen($prefix); + foreach ($it as $internalKey => $metadata) { + // @see http://pecl.php.net/bugs/bug.php?id=22564 + if (!apc_exists($internalKey)) { + continue; } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $this->normalizeMetadata($metadata); + $result[ substr($internalKey, $prefixL) ] = & $metadata; } + + return $result; } /* writing */ /** - * Store an item. + * Internal method to store an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!apc_store($internalKey, $value, $options['ttl'])) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "apc_store('{$internalKey}', <{$type}>, {$options['ttl']}) failed" - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + if (!apc_store($internalKey, $value, $normalizedOptions['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "apc_store('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + ); } + return true; } /** - * Store multiple items. + * Internal method to store multiple items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItems.pre(PreEvent) - * @triggers setItems.post(PostEvent) - * @triggers setItems.exception(ExceptionEvent) */ - public function setItems(array $keyValuePairs, array $options = array()) + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeyValuePairs = array(); - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - foreach ($keyValuePairs as $key => &$value) { - $internalKey = $prefix . $key; - $internalKeyValuePairs[$internalKey] = &$value; - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $errKeys = apc_store($internalKeyValuePairs, null, $options['ttl']); - if ($errKeys) { - throw new Exception\RuntimeException( - "apc_store(, null, {$options['ttl']}) failed for keys: " - . "'" . implode("','", $errKeys) . "'" - ); - } + $internalKeyValuePairs = array(); + foreach ($normalizedKeyValuePairs as $normalizedKey => &$value) { + $internalKey = $prefix . $normalizedKey; + $internalKeyValuePairs[$internalKey] = &$value; + } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $errKeys = apc_store($internalKeyValuePairs, null, $normalizedOptions['ttl']); + if ($errKeys) { + throw new Exception\RuntimeException( + "apc_store(, null, {$normalizedOptions['ttl']}) failed for keys: " + . "'" . implode("','", $errKeys) . "'" + ); } + + return true; } /** @@ -1028,85 +832,87 @@ public function decrementItem($key, $value, array $options = array()) } } - /* non-blocking */ - - /** - * Get items that were marked to delay storage for purposes of removing blocking - * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param array $keys - * @param array $options - * @return bool - * @throws Exception - * - * @triggers getDelayed.pre(PreEvent) - * @triggers getDelayed.post(PostEvent) - * @triggers getDelayed.exception(ExceptionEvent) + /* non-blocking */ + + /** + * Get items that were marked to delay storage for purposes of removing blocking + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return bool + * @throws Exception + * + * @triggers getDelayed.pre(PreEvent) + * @triggers getDelayed.post(PostEvent) + * @triggers getDelayed.exception(ExceptionEvent) */ - public function getDelayed(array $keys, array $options = array()) - { - $baseOptions = $this->getOptions(); - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } elseif (!$baseOptions->getReadable()) { - return false; - } elseif (!$keys) { - return true; - } - - $this->normalizeOptions($options); - if (isset($options['callback']) && !is_callable($options['callback'], false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - $prefix = preg_quote($prefix, '/'); - - $format = 0; - foreach ($options['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; - } - } - - $search = array(); - foreach ($keys as $key) { - $search[] = preg_quote($key, '/'); - } - $search = '/^' . $prefix . '(' . implode('|', $search) . ')$/'; - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = &$options; - - if (isset($options['callback'])) { - $callback = $options['callback']; - while (($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + public function getDelayed(array $keys, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($this->stmtActive) { + throw new Exception\RuntimeException('Statement already in use'); + } elseif (!$baseOptions->getReadable()) { + return false; + } elseif (!$keys) { + return true; + } + + $this->normalizeOptions($options); + if (isset($options['callback']) && !is_callable($options['callback'], false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } + + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); + $prefix = preg_quote($prefix, '/'); + + $format = 0; + foreach ($options['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; + } + } + + $search = array(); + foreach ($keys as $key) { + $search[] = preg_quote($key, '/'); + } + $search = '/^' . $prefix . '(' . implode('|', $search) . ')$/'; + + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = &$options; + + if (isset($options['callback'])) { + $callback = $options['callback']; + while (($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + $result = true; + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } + /* find */ + /** * Find items. * diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 789f3e549..cbbf7cb64 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -105,344 +105,369 @@ public function getOptions() /* reading */ /** - * Get item + * Get an item. * - * @param $key - * @param array $options - * @return bool|mixed + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item or return false + * + * @param string $key + * @param array $options + * @return mixed Data on success and false on failure + * @throws Exception + * + * @triggers getItem.pre(PreEvent) + * @triggers getItem.post(PostEvent) + * @triggers getItem.exception(ExceptionEvent) */ public function getItem($key, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = $this->internalGetItem($key, $options); - if (array_key_exists('token', $options)) { - // use filemtime + filesize as CAS token - $keyInfo = $this->getKeyInfo($key, $options['namespace']); - $options['token'] = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::getItem($key, $options); } /** - * Get items + * Get multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keys * @param array $options - * @return array|mixed + * @return array Associative array of existing keys and values + * @throws Exception + * + * @triggers getItems.pre(PreEvent) + * @triggers getItems.post(PostEvent) + * @triggers getItems.exception(ExceptionEvent) */ public function getItems(array $keys, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - // don't throw ItemNotFoundException on getItems - $options['ignore_missing_items'] = true; + return parent::getItems($keys, $options); + } - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); + /** + * Internal method to get an item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item or return false + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure + * @throws Exception + */ + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) + { + if ( !$this->internalHasItem($normalizedKey, $normalizedOptions) + || !($keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace'])) + ) { + if ($normalizedOptions['ignore_missing_items']) { + return false; + } else { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found within namespace '{$normalizedOptions['namespace']}'" + ); + } + } + $baseOptions = $this->getOptions(); try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + $data = $this->getFileContent($keyInfo['filespec'] . '.dat'); - if ($baseOptions->getClearStatCache()) { - clearstatcache(); + if ($baseOptions->getReadControl()) { + if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) + && isset($info['hash'], $info['algo']) + && Utils::generateHash($info['algo'], $data, true) != $info['hash'] + ) { + throw new Exception\UnexpectedValueException( + "ReadControl: Stored hash and computed hash don't match" + ); + } } - $result = array(); - foreach ($keys as $key) { - if ( ($rs = $this->internalGetItem($key, $options)) !== false) { - $result[$key] = $rs; - } + if (array_key_exists('token', $normalizedOptions)) { + // use filemtime + filesize as CAS token + $normalizedOptions['token'] = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); } - return $this->triggerPost(__FUNCTION__, $args, $result); + return $data; + } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + try { + // remove cache file on exception + $this->internalRemoveItem($normalizedKey, $normalizedOptions); + } catch (Exception $tmp) { + // do not throw remove exception on this point + } + + throw $e; } } /** - * Check for an item + * Test if an item exists. * - * @param $key - * @param array $options - * @return bool|mixed + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers hasItem.pre(PreEvent) + * @triggers hasItem.post(PostEvent) + * @triggers hasItem.exception(ExceptionEvent) */ public function hasItem($key, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = $this->internalHasItem($key, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::hasItem($key, $options); } /** - * Check for items + * Test multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $keys * @param array $options - * @return array|mixed + * @return array Array of existing keys + * @throws Exception + * + * @triggers hasItems.pre(PreEvent) + * @triggers hasItems.post(PostEvent) + * @triggers hasItems.exception(ExceptionEvent) */ public function hasItems(array $keys, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = array(); - foreach ($keys as $key) { - if ( $this->internalHasItem($key, $options) === true ) { - $result[] = $key; - } - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::hasItems($keys, $options); } /** - * Get metadata + * Internal method to test if an item exists. * - * @param $key - * @param array $options - * @return array|bool|mixed|null + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return boolean + * @throws Exception */ - public function getMetadata($key, array $options = array()) + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; + $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); + if (!$keyInfo) { + return false; // missing or corrupted cache data } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = $this->internalGetMetadata($key, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $ttl = $normalizedOptions['ttl']; + if (!$ttl || time() < ($keyInfo['mtime'] + $ttl)) { + return true; } + + return false; } /** - * Get metadatas + * Get metadata * - * @param array $keys + * @param $key * @param array $options - * @return array|mixed + * @return array|bool|mixed|null */ - public function getMetadatas(array $keys, array $options = array()) + public function getMetadata($key, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - // don't throw ItemNotFoundException on getMetadatas - $options['ignore_missing_items'] = true; - - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = array(); - foreach ($keys as $key) { - $meta = $this->internalGetMetadata($key, $options); - if ($meta !== false ) { - $result[$key] = $meta; - } - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::getMetadata($key, $options); } - /* writing */ - /** - * Set item + * Get info by key * - * @param $key - * @param $value - * @param array $options - * @return bool|mixed + * @param string $normalizedKey + * @param array $normalizedOptions + * @return array|bool + * @throws ItemNotFoundException */ - public function setItem($key, $value, array $options = array()) + protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { + $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); + if (!$keyInfo) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found on namespace '{$normalizedOptions['namespace']}'" + ); + } return false; } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } + $baseOptions = $this->getOptions(); + if (!$baseOptions->getNoCtime()) { + $keyInfo['ctime'] = filectime($keyInfo['filespec'] . '.dat'); + } - $value = $args['value']; + if (!$baseOptions->getNoAtime()) { + $keyInfo['atime'] = fileatime($keyInfo['filespec'] . '.dat'); + } - $result = $this->internalSetItem($key, $value, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $info = $this->readInfoFile($keyInfo['filespec'] . '.ifo'); + if ($info) { + return $keyInfo + $info; } + + return $keyInfo; } /** - * Set items + * Get metadatas * - * @param array $keyValuePairs + * @param array $keys * @param array $options - * @return bool|mixed + * @return array */ - public function setItems(array $keyValuePairs, array $options = array()) + public function getMetadatas(array $keys, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } + return parent::getMetadatas($keys, $options); + } - $result = true; - foreach ($args['keyValuePairs'] as $key => $value) { - $result = $this->internalSetItem($key, $value, $options) && $result; - } + /* writing */ - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + /** + * Internal method to store an item. + * + * Options: + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + { + $baseOptions = $this->getOptions(); + $oldUmask = null; + + $lastInfoId = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator() . $normalizedKey; + if ($this->lastInfoId == $lastInfoId) { + $filespec = $this->lastInfo['filespec']; + // if lastKeyInfo is available I'm sure that the cache directory exist + } else { + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions['namespace']); + if ($baseOptions->getDirLevel() > 0) { + $path = dirname($filespec); + if (!file_exists($path)) { + $oldUmask = umask($baseOptions->getDirUmask()); + ErrorHandler::start(); + $mkdir = mkdir($path, 0777, true); + $error = ErrorHandler::stop(); + if (!$mkdir) { + throw new Exception\RuntimeException( + "Error creating directory '{$path}'", 0, $error + ); + } + } + } + } + + $info = null; + if ($baseOptions->getReadControl()) { + $info['hash'] = Utils::generateHash($this->getReadControlAlgo(), $value, true); + $info['algo'] = $baseOptions->getReadControlAlgo(); + } + + if (isset($options['tags']) && $normalizedOptions['tags']) { + $tags = $normalizedOptions['tags']; + if (!is_array($tags)) { + $tags = array($tags); + } + $info['tags'] = array_values(array_unique($tags)); + } + + try { + if ($oldUmask !== null) { // $oldUmask could be defined on set directory_umask + umask($baseOptions->getFileUmask()); + } else { + $oldUmask = umask($baseOptions->getFileUmask()); + } + + $ret = $this->putFileContent($filespec . '.dat', $value); + if ($ret && $info) { + // Don't throw exception if writing of info file failed + // -> only return false + try { + $ret = $this->putFileContent($filespec . '.ifo', serialize($info)); + } catch (Exception\RuntimeException $e) { + $ret = false; + } + } + + $this->lastInfoId = null; + + // reset file_umask + umask($oldUmask); + + return $ret; + + } catch (Exception $e) { + // reset umask on exception + umask($oldUmask); + throw $e; + } } /** @@ -1121,88 +1146,6 @@ public function getCapacity(array $options = array()) /* internal */ - /** - * Set key value pair - * - * @param string $key - * @param mixed $value - * @param array $options - * @return bool - * @throws RuntimeException - */ - protected function internalSetItem($key, $value, array &$options) - { - $baseOptions = $this->getOptions(); - $oldUmask = null; - - $lastInfoId = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if ($this->lastInfoId == $lastInfoId) { - $filespec = $this->lastInfo['filespec']; - // if lastKeyInfo is available I'm sure that the cache directory exist - } else { - $filespec = $this->getFileSpec($key, $options['namespace']); - if ($baseOptions->getDirLevel() > 0) { - $path = dirname($filespec); - if (!file_exists($path)) { - $oldUmask = umask($baseOptions->getDirUmask()); - ErrorHandler::start(); - $mkdir = mkdir($path, 0777, true); - $error = ErrorHandler::stop(); - if (!$mkdir) { - throw new Exception\RuntimeException( - "Error creating directory '{$path}'", 0, $error - ); - } - } - } - } - - $info = null; - if ($baseOptions->getReadControl()) { - $info['hash'] = Utils::generateHash($this->getReadControlAlgo(), $value, true); - $info['algo'] = $baseOptions->getReadControlAlgo(); - } - - if (isset($options['tags']) && $options['tags']) { - $tags = $options['tags']; - if (!is_array($tags)) { - $tags = array($tags); - } - $info['tags'] = array_values(array_unique($tags)); - } - - try { - if ($oldUmask !== null) { // $oldUmask could be defined on set directory_umask - umask($baseOptions->getFileUmask()); - } else { - $oldUmask = umask($baseOptions->getFileUmask()); - } - - $ret = $this->putFileContent($filespec . '.dat', $value); - if ($ret && $info) { - // Don't throw exception if writing of info file failed - // -> only return false - try { - $ret = $this->putFileContent($filespec . '.ifo', serialize($info)); - } catch (Exception\RuntimeException $e) { - $ret = false; - } - } - - $this->lastInfoId = null; - - // reset file_umask - umask($oldUmask); - - return $ret; - - } catch (Exception $e) { - // reset umask on exception - umask($oldUmask); - throw $e; - } - } - /** * Remove a key * @@ -1223,114 +1166,6 @@ protected function internalRemoveItem($key, array &$options) $this->lastInfoId = null; } - /** - * Get by key - * - * @param $key - * @param array $options - * @return bool|string - * @throws Exception\ItemNotFoundException|Exception\UnexpectedValueException - */ - protected function internalGetItem($key, array &$options) - { - if ( !$this->internalHasItem($key, $options) - || !($keyInfo = $this->getKeyInfo($key, $options['namespace'])) - ) { - if ($options['ignore_missing_items']) { - return false; - } else { - throw new Exception\ItemNotFoundException( - "Key '{$key}' not found within namespace '{$options['namespace']}'" - ); - } - } - - $baseOptions = $this->getOptions(); - try { - $data = $this->getFileContent($keyInfo['filespec'] . '.dat'); - - if ($baseOptions->getReadControl()) { - if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) - && isset($info['hash'], $info['algo']) - && Utils::generateHash($info['algo'], $data, true) != $info['hash'] - ) { - throw new Exception\UnexpectedValueException( - "ReadControl: Stored hash and computed hash don't match" - ); - } - } - - return $data; - - } catch (Exception $e) { - try { - // remove cache file on exception - $this->internalRemoveItem($key, $options); - } catch (Exception $tmp) {} // do not throw remove exception on this point - - throw $e; - } - } - - /** - * Checks for a key - * - * @param $key - * @param array $options - * @return bool - */ - protected function internalHasItem($key, array &$options) - { - $keyInfo = $this->getKeyInfo($key, $options['namespace']); - if (!$keyInfo) { - return false; // missing or corrupted cache data - } - - if ( !$options['ttl'] // infinite lifetime - || time() < ($keyInfo['mtime'] + $options['ttl']) // not expired - ) { - return true; - } - - return false; - } - - /** - * Get info by key - * - * @param $key - * @param array $options - * @return array|bool - * @throws ItemNotFoundException - */ - protected function internalGetMetadata($key, array &$options) - { - $baseOptions = $this->getOptions(); - $keyInfo = $this->getKeyInfo($key, $options['namespace']); - if (!$keyInfo) { - if ($options['ignore_missing_items']) { - return false; - } else { - throw new Exception\ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); - } - } - - if (!$baseOptions->getNoCtime()) { - $keyInfo['ctime'] = filectime($keyInfo['filespec'] . '.dat'); - } - - if (!$baseOptions->getNoAtime()) { - $keyInfo['atime'] = fileatime($keyInfo['filespec'] . '.dat'); - } - - $info = $this->readInfoFile($keyInfo['filespec'] . '.ifo'); - if ($info) { - return $keyInfo + $info; - } - - return $keyInfo; - } - /** * Touch a key * diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 11f37970e..68b48221d 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -27,6 +27,8 @@ stdClass, Traversable, Zend\Cache\Exception, + Zend\Cache\Storage\Event, + Zend\Cache\Storage\CallbackEvent, Zend\Cache\Storage\Capabilities; /** @@ -79,11 +81,11 @@ public function __construct($options = null) // ext/memcached auto-connects to the server on first use $options = $this->getOptions(); - $servers = $options->getServers(); - if (!$servers) { - $options->addServer('localhost', 11211); - $servers = $options->getServers(); - } + $servers = $options->getServers(); + if (!$servers) { + $options->addServer('localhost', 11211); + $servers = $options->getServers(); + } $this->memcached->addServers($servers); } @@ -134,273 +136,208 @@ public function getOptions() /* reading */ /** - * Get an item. + * Internal method to get an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional + * - namespace + * - The namespace to use + * - ignore_missing_items * - Throw exception on missing item or return false * - * @param string $key - * @param array $options - * @return mixed Value on success and false on failure + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure * @throws Exception - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array()) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); + if (array_key_exists('token', $normalizedOptions)) { + $result = $this->memcached->get($normalizedKey, null, $normalizedOptions['token']); + } else { + $result = $this->memcached->get($normalizedKey); + } - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + if ($result === false) { + if (($rsCode = $this->memcached->getResultCode()) != 0 + && ($rsCode != MemcachedResource::RES_NOTFOUND || !$normalizedOptions['ignore_missing_items']) + ) { + throw $this->getExceptionByResultCode($rsCode); } + } - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - if (array_key_exists('token', $options)) { - $result = $this->memcached->get($key, null, $options['token']); - } else { - $result = $this->memcached->get($key); - } + return $result; + } - if ($result === false) { - if (($rsCode = $this->memcached->getResultCode()) != 0 - && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) - ) { - throw $this->getExceptionByResultCode($rsCode); - } - } + /** + * Internal method to get multiple items. + * + * Options: + * - namespace + * - The namespace to use + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing keys and values + * @throws Exception + */ + protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + { + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = $this->memcached->getMulti($normalizedKeys); + if ($result === false) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + + return $result; } /** - * Get multiple items. + * Internal method to test if an item exists. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param array $keys - * @param array $options - * @return array Assoziative array of existing keys and values or false on failure + * @param string $normalizedKey + * @param array $normalizedOptions + * @return boolean * @throws Exception - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); + + $value = $this->memcached->get($normalizedKey); + if ($value === false) { + $rsCode = $this->memcached->getResultCode(); + if ($rsCode == MemcachedResource::RES_SUCCESS) { + return true; + } elseif ($rsCode == MemcachedResource::RES_NOTFOUND) { + return false; + } else { + throw $this->getExceptionByResultCode($rsCode); + } } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); + return true; + } - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + /** + * Internal method to test multiple items. + * + * Options: + * - namespace + * - The namespace to use + * + * @param array $keys + * @param array $options + * @return array Array of existing keys + * @throws Exception + */ + protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + { + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - $result = $this->memcached->getMulti($keys); - if ($result === false) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } + $result = $this->memcached->getMulti($normalizedKeys); + if ($result === false) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + foreach ($result as $key => & $value) { + $value = true; } + + return $result; } /** - * Get metadata of an item. + * Get metadata of multiple items * * Options: * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - The namespace to use * - * @param string $key - * @param array $options - * @return array|boolean Metadata or false on failure + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array * @throws Exception * - * @triggers getMetadata.pre(PreEvent) - * @triggers getMetadata.post(PostEvent) - * @triggers getMetadata.exception(ExceptionEvent) + * @triggers getMetadatas.pre(PreEvent) + * @triggers getMetadatas.post(PostEvent) + * @triggers getMetadatas.exception(ExceptionEvent) */ - public function getMetadata($key, array $options = array()) + protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - $result = $this->memcached->get($key); - - if ($result === false) { - if (($rsCode = $this->memcached->getResultCode()) != 0 - && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) - ) { - throw $this->getExceptionByResultCode($rsCode); - } - } else { - $result = array(); - } + $result = $this->memcached->getMulti($normalizedKeys); + if ($result === false) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + foreach ($result as $key => & $value) { + $value = array(); } + + return $result; } /* writing */ /** - * Store an item. + * Internal method to store an item. * * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->set($key, $value, $expiration)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $expiration = $this->expirationTime($normalizedOptions['ttl']); + if (!$this->memcached->set($normalizedKey, $value, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + + return true; } /** - * Store multiple items. + * Internal method to store multiple items. * * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItems.pre(PreEvent) - * @triggers setItems.post(PostEvent) - * @triggers setItems.exception(ExceptionEvent) */ - public function setItems(array $keyValuePairs, array $options = array()) + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->setMulti($keyValuePairs, $expiration)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $expiration = $this->expirationTime($normalizedOptions['ttl']); + if (!$this->memcached->setMulti($normalizedKeyValuePairs, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + + return true; } /** diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 9517dde6e..7a93a840a 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -89,176 +89,146 @@ public function getOptions() /* reading */ /** - * Get an item. + * Internal method to get an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items * - Throw exception on missing item or return false * - * @param string $key - * @param array $options - * @return mixed Value on success and false on failure + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure * @throws Exception - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array()) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $ns = $normalizedOptions['namespace']; + $exist = isset($this->data[$ns][$normalizedKey]); + if ($exist) { + $data = & $this->data[$ns][$normalizedKey]; + $ttl = $normalizedOptions['ttl']; + if ($ttl && microtime(true) >= ($data[1] + $ttl) ) { + $exist = false; } + } - $ns = $options['namespace']; - $exist = isset($this->data[$ns][$key]); - if ($exist) { - if ($options['ttl'] && microtime(true) >= ($this->data[$ns][$key][1] + $options['ttl']) ) { - $exist = false; - } + if (!$exist) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$normalizedKey}' not found on namespace '{$ns}'"); } - - if (!$exist) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); - } - $result = false; - } else { - $result = $this->data[$ns][$key][0]; - if (array_key_exists('token', $options)) { - $options['token'] = $this->data[$ns][$key][0]; - } + $result = false; + } else { + $result = $data[0]; + if (array_key_exists('token', $normalizedOptions)) { + $normalizedOptions['token'] = $data[0]; } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $result; } /** - * Get multiple items. + * Internal method to get multiple items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param array $keys - * @param array $options - * @return array Assoziative array of existing keys and values or false on failure + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing keys and values * @throws Exception - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns])) { return array(); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if (!isset($this->data[$ns])) { - $result = array(); - } else { - $data = &$this->data[$ns]; + $data = & $this->data[$ns]; + $ttl = $normalizedOptions['ttl']; - $keyValuePairs = array(); - foreach ($keys as $key) { - if (isset($data[$key])) { - if (!$options['ttl'] || microtime(true) < ($this->data[$ns][$key][1] + $options['ttl']) ) { - $keyValuePairs[$key] = $data[$key][0]; - } - } + $result = array(); + foreach ($normalizedKeys as $normalizedKey) { + if (isset($data[$normalizedKey])) { + if (!$ttl || microtime(true) < ($data[$normalizedKey][1] + $ttl) ) { + $result[$normalizedKey] = $data[$normalizedKey][0]; } - - $result = $keyValuePairs; } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $result; } /** - * Test if an item exists. + * Internal method to test if an item exists. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers hasItem.pre(PreEvent) - * @triggers hasItem.post(PostEvent) - * @triggers hasItem.exception(ExceptionEvent) */ - public function hasItem($key, array $options = array()) + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns][$normalizedKey])) { return false; } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); + // check if expired + $ttl = $normalizedOptions['ttl']; + if ($ttl && microtime(true) >= ($this->data[$ns][$normalizedKey][1] + $ttl) ) { + return false; + } - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + return true; + } - $result = $this->checkItem($key, $options); + /** + * Internal method to test multiple items. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $keys + * @param array $options + * @return array Array of existing keys + * @throws Exception + */ + protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + { + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns])) { + return array(); + } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $data = & $this->data[$ns]; + $ttl = $normalizedOptions['ttl']; + + $result = array(); + foreach ($normalizedKeys as $normalizedKey) { + if (!$ttl || microtime(true) < ($data[$normalizedKey][1] + $ttl) ) { + $result[$normalizedKey] = true; + } } + + return $result; } /** @@ -272,8 +242,8 @@ public function hasItem($key, array $options = array()) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return array|boolean Metadata or false on failure * @throws Exception * @@ -281,165 +251,88 @@ public function hasItem($key, array $options = array()) * @triggers getMetadata.post(PostEvent) * @triggers getMetadata.exception(ExceptionEvent) */ - public function getMetadata($key, array $options = array()) + protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$this->checkItem($key, $options)) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$key}' not found on namespace '{$options['namespace']}'" - ); - } - $result = false; - } else { - $ns = $options['namespace']; - $result = array( - 'mtime' => $this->data[$ns][$key][1], - 'tags' => $this->data[$ns][$key][2], + if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found on namespace '{$normalizedOptions['namespace']}'" ); } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + return false; } + + $ns = $normalizedOptions['namespace']; + return array( + 'mtime' => $this->data[$ns][$normalizedKey][1], + 'tags' => $this->data[$ns][$normalizedKey][2], + ); } /* writing */ /** - * Store an item. + * Internal method to store an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - namespace + * - The namespace to use * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if (!$this->hasFreeCapacity()) { + $memoryLimit = $this->getOptions()->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + "Memory usage exceeds limit ({$memoryLimit})." + ); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$this->hasFreeCapacity()) { - $memoryLimit = $baseOptions->getMemoryLimit(); - throw new Exception\OutOfCapacityException( - 'Memory usage exceeds limit ({$memoryLimit}).' - ); - } - - $ns = $options['namespace']; - $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); + $ns = $normalizedOptions['namespace']; + $this->data[$ns][$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Store multiple items. + * Internal method to store multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItems.pre(PreEvent) - * @triggers setItems.post(PostEvent) - * @triggers setItems.exception(ExceptionEvent) */ - public function setItems(array $keyValuePairs, array $options = array()) + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if (!$this->hasFreeCapacity()) { + $memoryLimit = $this->getOptions()->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$this->hasFreeCapacity()) { - $memoryLimit = $baseOptions->getMemoryLimit(); - throw new Exception\OutOfCapacityException( - 'Memory usage exceeds limit ({$memoryLimit}).' - ); - } - - $ns = $options['namespace']; - if (!isset($this->data[$ns])) { - $this->data[$ns] = array(); - } - - $data = & $this->data[$ns]; - foreach ($keyValuePairs as $key => $value) { - $data[$key] = array($value, microtime(true), $options['tags']); - } + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns])) { + $this->data[$ns] = array(); + } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $data = & $this->data[$ns]; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $data[$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); } + + return true; } /** @@ -1006,7 +899,7 @@ public function decrementItem($key, $value, array $options = array()) } } - /* non-blocking */ + /* find */ /** * Find items. @@ -1064,13 +957,13 @@ public function find($mode = self::MATCH_ACTIVE, array $options=array()) // if MATCH_EXPIRED -> filter active items if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($this->checkItem($key, $options)) { + if ($this->internalHasItem($key, $options)) { continue; } // if MATCH_ACTIVE -> filter expired items } else { - if (!$this->checkItem($key, $options)) { + if (!$this->internalHasItem($key, $options)) { continue; } } @@ -1145,7 +1038,7 @@ public function fetch() if ($key === null) { break; } - if (!$this->checkItem($key, $options)) { + if (!$this->internalHasItem($key, $options)) { continue; } $ref = & $this->data[ $options['namespace'] ][$key]; @@ -1407,33 +1300,6 @@ protected function hasFreeCapacity() return ($free > 0); } - /** - * Internal method to check if an key exists - * and if it isn't expired. - * - * Options: - * - namespace required - * - ttl required - * - * @param string $key - * @param array $options - */ - protected function checkItem($key, array &$options) - { - $ns = $options['namespace']; - - if (!isset($this->data[$ns][$key])) { - return false; - } - - // check if expired - if ($options['ttl'] && microtime(true) >= ($this->data[$ns][$key][1] + $options['ttl']) ) { - return false; - } - - return true; - } - /** * Internal method to run a clear command * on a given data array which doesn't contain namespaces. diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index fafbc8464..346372277 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -106,244 +106,107 @@ public function getOptions() /* reading */ /** - * Get an item. + * Internal method to get an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items * - Throw exception on missing item or return false * - * @param string $key - * @param array $options - * @return mixed Value on success and false on failure + * @param string $normalizedKey + * @param array $normalizedOptions + * @return mixed Data on success or false on failure * @throws Exception - * - * @triggers getItem.pre(PreEvent) - * @triggers getItem.post(PostEvent) - * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array()) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $success = false; + $result = wincache_ucache_get($internalKey, $success); + if (!$success) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = wincache_ucache_get($internalKey, $success); - if (!$success) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - } else { - if (array_key_exists('token', $options)) { - $options['token'] = $result; - } + } else { + if (array_key_exists('token', $normalizedOptions)) { + $normalizedOptions['token'] = $result; } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $result; } /** - * Get multiple items. + * Internal method to get multiple items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param array $keys - * @param array $options - * @return array Assoziative array of existing keys and values or false on failure + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing keys and values * @throws Exception - * - * @triggers getItems.pre(PreEvent) - * @triggers getItems.post(PostEvent) - * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $namespaceSep = $baseOptions->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $namespaceSep . $key; + $fetch = wincache_ucache_get($internalKeys); + if (!$normalizedOptions['ignore_missing_items']) { + if (count($normalizedKeys) != count($fetch)) { + $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); + throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); } - - $fetch = wincache_ucache_get($internalKeys); - if (!$options['ignore_missing_items']) { - if (count($keys) != count($fetch)) { - $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); - throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); - } - } - - // remove namespace prefix - $prefixL = strlen($options['namespace'] . $namespaceSep); - $result = array(); - foreach ($fetch as $internalKey => &$value) { - $result[ substr($internalKey, $prefixL) ] = $value; - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } - } - /** - * Test if an item exists. - * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param string $key - * @param array $options - * @return boolean - * @throws Exception - * - * @triggers hasItem.pre(PreEvent) - * @triggers hasItem.post(PostEvent) - * @triggers hasItem.exception(ExceptionEvent) - */ - public function hasItem($key, array $options = array()) - { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; + // remove namespace prefix + $prefixL = strlen($prefix); + $result = array(); + foreach ($fetch as $internalKey => & $value) { + $result[ substr($internalKey, $prefixL) ] = $value; } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $result = wincache_ucache_exists($internalKey); - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $result; } /** - * Test if an item exists. + * Internal method to test if an item exists. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param array $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers hasItems.pre(PreEvent) - * @triggers hasItems.post(PostEvent) - * @triggers hasItems.exception(ExceptionEvent) */ - public function hasItems(array $keys, array $options = array()) + protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $namespaceSep = $baseOptions->getNamespaceSeparator(); - $internalKeys = array(); - foreach ($keys as $key) { - $internalKeys[] = $options['namespace'] . $namespaceSep . $key; - } - - $prefixL = strlen($options['namespace'] . $namespaceSep); - $result = array(); - foreach ($internalKeys as $key) { - if (wincache_ucache_exists($key)) { - $result[] = substr($key, $prefixL); - } - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + return wincache_ucache_exists($prefix . $normalizedKey); } /** * Get metadata of an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) * - ignore_missing_items optional * - Throw exception on missing item or return false * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return array|boolean Metadata or false on failure * @throws Exception * @@ -351,225 +214,89 @@ public function hasItems(array $keys, array $options = array()) * @triggers getMetadata.post(PostEvent) * @triggers getMetadata.exception(ExceptionEvent) */ - public function getMetadata($key, array $options = array()) + protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - - $info = wincache_ucache_info(true, $internalKey); - if (isset($info['ucache_entries'][1])) { - $metadata = $info['ucache_entries'][1]; - } - - if (empty($metadata)) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - $metadata= false; - } else { - $this->normalizeMetadata($metadata); - } - - return $this->triggerPost(__FUNCTION__, $args, $metadata); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $info = wincache_ucache_info(true, $internalKey); + if (isset($info['ucache_entries'][1])) { + $metadata = $info['ucache_entries'][1]; } - } - - /** - * Get all metadata for an item - * - * @param array $keys - * @param array $options - * @return array - * @throws Exception\ItemNotFoundException - * - * @triggers getMetadatas.pre(PreEvent) - * @triggers getMetadatas.post(PostEvent) - * @triggers getMetadatas.exception(ExceptionEvent) - */ - public function getMetadatas(array $keys, array $options = array()) - { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return array(); - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + if (!$metadata) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - - $result= array(); - - foreach ($keys as $key) { - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - - $info = wincache_ucache_info(true, $internalKey); - $metadata = $info['ucache_entries'][1]; - - if (empty($metadata)) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - } else { - $this->normalizeMetadata($metadata); - $prefixL = strlen($options['namespace'] . $baseOptions->getNamespaceSeparator()); - $result[ substr($internalKey, $prefixL) ] = & $metadata; - } - } - - if (!$options['ignore_missing_items']) { - if (count($keys) != count($result)) { - $missing = implode("', '", array_diff($keys, array_keys($result))); - throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); - } - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + return false; } + + $this->normalizeMetadata($metadata); + return $metadata; } /* writing */ /** - * Store an item. + * Internal method to store an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key - * @param mixed $value - * @param array $options + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItem.pre(PreEvent) - * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!wincache_ucache_set($internalKey, $value, $normalizedOptions['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "wincache_ucache_set('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + ); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!wincache_ucache_set($internalKey, $value, $options['ttl'])) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "wincache_ucache_set('{$internalKey}', <{$type}>, {$options['ttl']}) failed" - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Store multiple items. + * Internal method to store multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers setItems.pre(PreEvent) - * @triggers setItems.post(PostEvent) - * @triggers setItems.exception(ExceptionEvent) */ - public function setItems(array $keyValuePairs, array $options = array()) + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeyValuePairs = array(); - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - foreach ($keyValuePairs as $key => &$value) { - $internalKey = $prefix . $key; - $internalKeyValuePairs[$internalKey] = &$value; - } - - $errKeys = wincache_ucache_set($internalKeyValuePairs, null, $options['ttl']); - if ($errKeys!==array()) { - throw new Exception\RuntimeException( - "wincache_ucache_set(, null, {$options['ttl']}) failed for keys: " - . "'" . implode("','", array_keys($errKeys)) . "'" - ); - } + $internalKeyValuePairs = array(); + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $internalKey = $prefix . $normalizedKey; + $internalKeyValuePairs[$internalKey] = $value; + } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $errKeys = wincache_ucache_set($internalKeyValuePairs, null, $normalizedOptions['ttl']); + if ($errKeys) { + throw new Exception\RuntimeException( + "wincache_ucache_set(, null, {$normalizedOptions['ttl']}) failed for keys: " + . "'" . implode("','", array_keys($errKeys)) . "'" + ); } + + return true; } /** @@ -925,7 +652,7 @@ public function decrementItem($key, $value, array $options = array()) } } - /* non-blocking */ + /* find */ /* cleaning */ @@ -1096,15 +823,8 @@ protected function normalizeMetadata(array &$metadata) unset($metadata['value_size']); } - // remove namespace prefix if (isset($metadata['key_name'])) { - $pos = strpos($metadata['key_name'], $this->getOptions()->getNamespaceSeparator()); - if ($pos !== false) { - $metadata['internal_key'] = $metadata['key_name']; - } else { - $metadata['internal_key'] = $metadata['key_name']; - } - + $metadata['internal_key'] = $metadata['key_name']; unset($metadata['key_name']); } } diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index b374590cc..e1ed301c4 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -22,7 +22,7 @@ namespace ZendTest\Cache\Storage\Adapter; use Zend\Cache, - Zend\Cache\Exception\RuntimeException; + Zend\Cache\Exception; /** * @category Zend @@ -45,15 +45,12 @@ class AbstractAdapterTest extends \PHPUnit_Framework_TestCase public function setUp() { $this->_options = new Cache\Storage\Adapter\AdapterOptions(); - $this->_storage = $this->getMockForAbstractClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); - $this->_storage->setOptions($this->_options); - $this->_storage->expects($this->any()) - ->method('getOptions') - ->will($this->returnValue($this->_options)); } public function testGetOptions() { + $this->_storage = $this->getMockForAbstractAdapter(); + $options = $this->_storage->getOptions(); $this->assertInstanceOf('Zend\Cache\Storage\Adapter\AdapterOptions', $options); $this->assertInternalType('boolean', $options->getWritable()); @@ -174,6 +171,8 @@ public function testSetIgnoreMissingItems() public function testPluginRegistry() { + $this->_storage = $this->getMockForAbstractAdapter(); + $plugin = new \ZendTest\Cache\Storage\TestAsset\MockPlugin(); // no plugin registered @@ -200,6 +199,8 @@ public function testPluginRegistry() public function testInternalTriggerPre() { + $this->_storage = $this->getMockForAbstractAdapter(); + $plugin = new \ZendTest\Cache\Storage\TestAsset\MockPlugin(); $this->_storage->addPlugin($plugin); @@ -227,6 +228,8 @@ public function testInternalTriggerPre() public function testInternalTriggerPost() { + $this->_storage = $this->getMockForAbstractAdapter(); + $plugin = new \ZendTest\Cache\Storage\TestAsset\MockPlugin(); $this->_storage->addPlugin($plugin); @@ -258,6 +261,8 @@ public function testInternalTriggerPost() public function testInternalTriggerExceptionThrowRuntimeException() { + $this->_storage = $this->getMockForAbstractAdapter(); + $plugin = new \ZendTest\Cache\Storage\TestAsset\MockPlugin(); $this->_storage->addPlugin($plugin); @@ -271,39 +276,179 @@ public function testInternalTriggerExceptionThrowRuntimeException() $method->setAccessible(true); $this->setExpectedException('Zend\Cache\Exception\RuntimeException', 'test'); - $method->invokeArgs($this->_storage, array('setItem', $params, new RuntimeException('test'))); + $method->invokeArgs($this->_storage, array('setItem', $params, new Exception\RuntimeException('test'))); } - public function testGetItems() + public function testGetItemCallsInternalGetItem() { - $options = array('ttl' => 123); - $items = array( - 'key1' => 'value1', - 'dKey1' => false, - 'key2' => 'value2', - ); + $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); - $i = 0; + $options = array('ttl' => 123); + $key = 'key1'; + $result = 'value1'; + + $this->_storage + ->expects($this->once()) + ->method('internalGetItem') + ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue($result)); + + $rs = $this->_storage->getItem($key, $options); + $this->assertEquals($result, $rs); + } + + public function testGetItemsCallsInternalGetItems() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItems')); + + $options = array('ttl' => 123); + $keys = array('key1', 'key2'); + $result = array('key2' => 'value2'); + + $this->_storage + ->expects($this->once()) + ->method('internalGetItems') + ->with($this->equalTo($keys), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue($result)); + + $rs = $this->_storage->getItems($keys, $options); + $this->assertEquals($result, $rs); + } + + public function testInternalGetItemsCallsInternalGetItemForEachKey() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); + + $options = array('ttl' => 123); + $items = array('key1' => 'value1', 'notFound' => false, 'key2' => 'value2'); + $result = array('key1' => 'value1', 'key2' => 'value2'); + + $normalizedOptions = $this->normalizeOptions($options); + $normalizedOptions['ignore_missing_items'] = false; + + $i = 0; // method call counter foreach ($items as $k => $v) { $this->_storage->expects($this->at($i++)) - ->method('getItem') - ->with($this->equalTo($k), $this->equalTo($options)) - ->will($this->returnValue($v)); + ->method('internalGetItem') + ->with($this->equalTo($k), $this->equalTo($normalizedOptions)) + // return value or throw ItemNotFoundException + ->will($v ? $this->returnValue($v) : $this->throwException(new Exception\ItemNotFoundException())); } $rs = $this->_storage->getItems(array_keys($items), $options); + $this->assertEquals($result, $rs); + } - // remove missing items from array to test - $expected = $items; - foreach ($expected as $key => $value) { - if (false === $value) { - unset($expected[$key]); - } + public function testHasItemCallsInternalHasItem() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalHasItem')); + + $options = array('ttl' => 123); + $key = 'key1'; + $result = true; + + $this->_storage + ->expects($this->once()) + ->method('internalHasItem') + ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue($result)); + + $rs = $this->_storage->hasItem($key, $options); + $this->assertSame($result, $rs); + } + + public function testInternalHasItemCallsInternalGetItemReturnsTrueOnValidFalseValue() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); + + $options = array('ttl' => 123); + $key = 'key1'; + + $this->_storage + ->expects($this->once()) + ->method('internalGetItem') + ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue(false)); // return a valid false value + + $rs = $this->_storage->hasItem($key, $options); + $this->assertTrue($rs); + } + + public function testInternalHasItemCallsInternalGetItemReturnsFalseOnItemNotFoundException() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); + + $options = array('ttl' => 123); + $key = 'key1'; + + $this->_storage + ->expects($this->once()) + ->method('internalGetItem') + ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->will($this->throwException(new Exception\ItemNotFoundException())); // throw ItemNotFoundException + + $rs = $this->_storage->hasItem($key, $options); + $this->assertFalse($rs); + } + + public function testHasItemsCallsInternalHasItems() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalHasItems')); + + $options = array('ttl' => 123); + $keys = array('key1', 'key2'); + $result = array('key2'); + + $this->_storage + ->expects($this->once()) + ->method('internalHasItems') + ->with($this->equalTo($keys), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue($result)); + + $rs = $this->_storage->hasItems($keys, $options); + $this->assertEquals($result, $rs); + } + + public function testInternalHasItemsCallsInternalHasItem() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalHasItem')); + + $options = array('ttl' => 123); + $items = array('key1' => true, 'key2' => false); + $result = array('key1'); + + $i = 0; // method call counter + foreach ($items as $k => $v) { + $this->_storage + ->expects($this->at($i++)) + ->method('internalHasItem') + ->with($this->equalTo($k), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue($v)); } - $this->assertEquals($expected, $rs); + $rs = $this->_storage->hasItems(array_keys($items), $options); + $this->assertEquals($result, $rs); } + public function testGetMetadataCallsInternalGetMetadata() + { + $this->_storage = $this->getMockForAbstractAdapter(array('internalGetMetadata')); + + $options = array('ttl' => 123); + $key = 'key1'; + $result = array(); + + $this->_storage + ->expects($this->once()) + ->method('internalGetMetadata') + ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->will($this->returnValue($result)); + + $rs = $this->_storage->getMetadata($key, $options); + $this->assertSame($result, $rs); + } + +/* public function testGetMetadatas() { $options = array('ttl' => 123); @@ -334,35 +479,6 @@ public function testGetMetadatas() $this->assertEquals($expected, $rs); } - public function testHasItem() - { - $this->_storage->expects($this->at(0)) - ->method('getItem') - ->with($this->equalTo('key')) - ->will($this->returnValue('value')); - - $this->assertTrue($this->_storage->hasItem('key')); - } - - public function testHasItems() - { - $keys = array('key1', 'key2', 'key3'); - - foreach ($keys as $i => $key) { - $this->_storage->expects($this->at($i)) - ->method('getItem') - ->with($this->equalTo($key)) - ->will( - ($i % 2) ? $this->returnValue('value') - : $this->returnValue(false) - ); - } - - $rs = $this->_storage->hasItems($keys); - $this->assertInternalType('array', $rs); - $this->assertEquals(floor(count($keys) / 2), count($rs)); - } - public function testSetItems() { $options = array('ttl' => 123); @@ -517,9 +633,66 @@ public function testRemoveItemsFail() $this->assertFalse($this->_storage->removeItems($items, $options)); } - +*/ // TODO: getDelayed + fatch[All] // TODO: incrementItem[s] + decrementItem[s] // TODO: touchItem[s] + /** + * Generates a mock of the abstract storage adapter by mocking all abstract and the given methods + * Also sets the adapter options + * + * @param array $methods + * @return \Zend\Cache\Storage\Adapter\AbstractAdapter + */ + protected function getMockForAbstractAdapter(array $methods = array()) + { + $class = 'Zend\Cache\Storage\Adapter\AbstractAdapter'; + + if (!$methods) { + $adapter = $this->getMockForAbstractClass($class); + } else { + $reflection = new \ReflectionClass('Zend\Cache\Storage\Adapter\AbstractAdapter'); + foreach ($reflection->getMethods() as $method) { + if ($method->isAbstract()) { + $methods[] = $method->getName(); + } + } + $adapter = $this->getMockBuilder($class)->setMethods(array_unique($methods))->getMock(); + } + + $adapter->setOptions($this->_options); + return $adapter; + } + + protected function normalizeOptions($options) + { + // ttl + if (!isset($options['ttl'])) { + $options['ttl'] = $this->_options->getTtl(); + } + + // namespace + if (!isset($options['namespace'])) { + $options['namespace'] = $this->_options->getNamespace(); + } + + // ignore_missing_items + if (!isset($options['ignore_missing_items'])) { + $options['ignore_missing_items'] = $this->_options->getIgnoreMissingItems(); + } + + // tags + if (!isset($options['tags'])) { + $options['tags'] = null; + } + + // select + if (!isset($options['select'])) { + $options['select'] = array('key', 'value'); + } + + return $options; + } + } diff --git a/test/Storage/TestAsset/MockAdapter.php b/test/Storage/TestAsset/MockAdapter.php index 8e6771228..4f3e4eadc 100644 --- a/test/Storage/TestAsset/MockAdapter.php +++ b/test/Storage/TestAsset/MockAdapter.php @@ -6,15 +6,11 @@ class MockAdapter extends AbstractAdapter { - public function getItem($key = null, array $options = array()) - { - } - - public function getMetadata($key = null, array $options = array()) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { } - public function setItem($value, $key = null, array $options = array()) + protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { } From a512601c93e525158ad6601e9e14ac90e1ace101 Mon Sep 17 00:00:00 2001 From: Mike Willbanks Date: Tue, 28 Feb 2012 07:46:54 -0600 Subject: [PATCH 214/311] updated default value for test --- test/Storage/Adapter/MemcachedTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index ef3c4cae6..bb3848603 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -86,7 +86,7 @@ public function testNoOptionsSetsDefaultServer() { $memcached = new Cache\Storage\Adapter\Memcached(); - $this->assertEquals($memcached->getOptions()->getServers(), array(array('localhost', 11211))); + $this->assertEquals($memcached->getOptions()->getServers(), array(array('127.0.0.1', 11211))); } public function tearDown() From 6d2b276211fe4444623517b2bca7df293c6b7c35 Mon Sep 17 00:00:00 2001 From: Thinkscape Date: Thu, 8 Mar 2012 17:29:22 +0100 Subject: [PATCH 215/311] Refactor Zend\Stdlib\ArrayTools to ArrayUtils, add missing headers. - ArrayTools will now be called ArrayUtils after an anonymous vote (http://framework.zend.com/wiki/display/ZFDEV2/POLL+-+Array+class+name). - Add missing Zend Framework headers to ArrayUtils class file and tests. --- src/PatternFactory.php | 4 ++-- src/StorageFactory.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/PatternFactory.php b/src/PatternFactory.php index 0393419fd..c44dfe71c 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -22,7 +22,7 @@ use Traversable, Zend\Loader\Broker, - Zend\Stdlib\ArrayTools; + Zend\Stdlib\ArrayUtils; /** * @category Zend @@ -50,7 +50,7 @@ class PatternFactory public static function factory($patternName, $options = array()) { if ($options instanceof Traversable) { - $options = ArrayTools::iteratorToArray($options); + $options = ArrayUtils::iteratorToArray($options); } if (is_array($options)) { $options = new Pattern\PatternOptions($options); diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 198713fdf..4da4b8aff 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -23,7 +23,7 @@ use Traversable, Zend\Loader\Broker, - Zend\Stdlib\ArrayTools; + Zend\Stdlib\ArrayUtils; /** * @category Zend @@ -59,7 +59,7 @@ class StorageFactory public static function factory($cfg) { if ($cfg instanceof Traversable) { - $cfg = ArrayTools::iteratorToArray($cfg); + $cfg = ArrayUtils::iteratorToArray($cfg); } if (!is_array($cfg)) { From 16a9bb592532b3dae64f09dddb6fbcb56aaad6cb Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 29 Feb 2012 22:33:12 +0100 Subject: [PATCH 216/311] small changes of Zend\Cache\StorageFactory::factory to not set adapter options after adding plugins --- src/StorageFactory.php | 68 ++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 42 deletions(-) diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 4da4b8aff..b038d18b3 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -71,23 +71,23 @@ public static function factory($cfg) // instantiate the adapter if (!isset($cfg['adapter'])) { - throw new Exception\InvalidArgumentException( - 'Missing "adapter"' - ); - } elseif (is_array($cfg['adapter'])) { + throw new Exception\InvalidArgumentException('Missing "adapter"'); + } + $adapterName = $cfg['adapter']; + $adapterOptions = null; + if (is_array($cfg['adapter'])) { if (!isset($cfg['adapter']['name'])) { - throw new Exception\InvalidArgumentException( - 'Missing "adapter.name"' - ); + throw new Exception\InvalidArgumentException('Missing "adapter.name"'); } - $name = $cfg['adapter']['name']; - $options = isset($cfg['adapter']['options']) - ? $cfg['adapter']['options'] : array(); - $adapter = static::adapterFactory($name, $options); - } else { - $adapter = static::adapterFactory($cfg['adapter']); + $adapterName = $cfg['adapter']['name']; + $adapterOptions = isset($cfg['adapter']['options']) ? $cfg['adapter']['options'] : null; } + if ($adapterOptions && isset($cfg['options'])) { + $adapterOptions = array_merge($adapterOptions, $cfg['options']); + } + + $adapter = static::adapterFactory($adapterName, $adapterOptions); // add plugins if (isset($cfg['plugins'])) { @@ -99,50 +99,33 @@ public static function factory($cfg) foreach ($cfg['plugins'] as $k => $v) { if (is_string($k)) { - $name = $k; - if (!is_array($v)) { - throw new Exception\InvalidArgumentException( - "'plugins.{$k}' needs to be an array" - ); + if (!is_array($v)) { + throw new Exception\InvalidArgumentException( + "'plugins.{$k}' needs to be an array" + ); } - $options = $v; + $pluginName = $k; + $pluginOptions = $v; } elseif (is_array($v)) { if (!isset($v['name'])) { throw new Exception\InvalidArgumentException("Invalid plugins[{$k}] or missing plugins[{$k}].name"); } - $name = (string) $v['name']; + $pluginName = (string) $v['name']; if (isset($v['options'])) { - $options = $v['options']; + $pluginOptions = $v['options']; } else { - $options = array(); + $pluginOptions = array(); } } else { - $name = $v; - $options = array(); + $pluginName = $v; + $pluginOptions = array(); } - $plugin = static::pluginFactory($name, $options); + $plugin = static::pluginFactory($pluginName, $pluginOptions); $adapter->addPlugin($plugin); } } - // set adapter or plugin options - if (isset($cfg['options'])) { - if (!is_array($cfg['options']) - && !$cfg['options'] instanceof Traversable - ) { - throw new Exception\InvalidArgumentException( - 'Options needs to be an array or Traversable object' - ); - } - - // Options at the top-level should be *merged* with existing options - $options = $adapter->getOptions(); - foreach ($cfg['options'] as $key => $value) { - $options->$key = $value; - } - } - return $adapter; } @@ -227,6 +210,7 @@ public static function pluginFactory($pluginName, $options = array()) } $plugin->setOptions($options); + return $plugin; } From f471b3f586ea151fdfc3b4a66d70d22700c0ee5e Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 29 Feb 2012 22:58:55 +0100 Subject: [PATCH 217/311] Zend\Cache\StorageFactoryTest: iterator index not the same as the array index --- test/StorageFactoryTest.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index 9e06cc596..c39cf6d56 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -114,8 +114,9 @@ public function testFactoryWithPlugins() $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $cache); // test plugin structure - foreach ($cache->getPlugins() as $i => $plugin) { - $this->assertInstanceOf('Zend\Cache\Storage\Plugin\\' . $plugins[$i], $plugin); + $i = 0; + foreach ($cache->getPlugins() as $plugin) { + $this->assertInstanceOf('Zend\Cache\Storage\Plugin\\' . $plugins[$i++], $plugin); } } From 9208ac0d96391304ff860fab249c645c828a9b60 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 1 Mar 2012 07:59:53 +0100 Subject: [PATCH 218/311] Make it possible to disable memory_limit of the memory cache adapter to not set it up to 1gb on tests --- src/Storage/Adapter/Memory.php | 6 ++++++ src/Storage/Adapter/MemoryOptions.php | 9 +++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 9517dde6e..f591fedd7 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -1403,6 +1403,12 @@ public function getCapacity(array $options = array()) protected function hasFreeCapacity() { $total = $this->getOptions()->getMemoryLimit(); + + // check memory limit disabled + if ($total <= 0) { + return true; + } + $free = $total - (float) memory_get_usage(true); return ($free > 0); } diff --git a/src/Storage/Adapter/MemoryOptions.php b/src/Storage/Adapter/MemoryOptions.php index f9c7f81ee..f6355dcbe 100644 --- a/src/Storage/Adapter/MemoryOptions.php +++ b/src/Storage/Adapter/MemoryOptions.php @@ -45,8 +45,9 @@ class MemoryOptions extends AdapterOptions /** * Set memory limit * - * If the used memory of PHP exceeds this limit an OutOfCapacityException - * will be thrown. + * - Bytes of less or equal 0 will disable the memory limit + * - If the used memory of PHP exceeds this limit an OutOfCapacityException + * will be thrown. * * @param int $bytes * @return MemoryOptions @@ -72,8 +73,8 @@ public function getMemoryLimit() if ($memoryLimit >= 0) { $this->memoryLimit = floor($memoryLimit / 2); } else { - // use a hard memory limit of 32M if php memory limit is disabled - $this->memoryLimit = 33554432; + // disable memory limit + $this->memoryLimit = 0; } } From e397d3029d872b61c630fec6bc23398e082fbf2b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 1 Mar 2012 22:07:34 +0100 Subject: [PATCH 219/311] cache factories have to instantiate a new object each time called + tests --- src/PatternFactory.php | 13 ++----------- src/StorageFactory.php | 6 +++--- test/PatternFactoryTest.php | 11 +++++++++++ test/StorageFactoryTest.php | 20 ++++++++++++++++---- 4 files changed, 32 insertions(+), 18 deletions(-) diff --git a/src/PatternFactory.php b/src/PatternFactory.php index c44dfe71c..28ae2911c 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -82,7 +82,8 @@ public static function factory($patternName, $options = array()) public static function getBroker() { if (static::$broker === null) { - static::$broker = static::getDefaultBroker(); + static::$broker = new PatternBroker(); + static::$broker->setRegisterPluginsOnLoad(false); } return static::$broker; @@ -108,14 +109,4 @@ public static function resetBroker() { static::$broker = null; } - - /** - * Get internal pattern broker - * - * @return PatternBroker - */ - protected static function getDefaultBroker() - { - return new PatternBroker(); - } } diff --git a/src/StorageFactory.php b/src/StorageFactory.php index b038d18b3..5372ad874 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -87,7 +87,7 @@ public static function factory($cfg) $adapterOptions = array_merge($adapterOptions, $cfg['options']); } - $adapter = static::adapterFactory($adapterName, $adapterOptions); + $adapter = static::adapterFactory((string)$adapterName, $adapterOptions); // add plugins if (isset($cfg['plugins'])) { @@ -185,7 +185,7 @@ public static function setAdapterBroker(Broker $broker) */ public static function resetAdapterBroker() { - static::$adapterBroker = new Storage\AdapterBroker(); + static::$adapterBroker = null; } /** @@ -246,6 +246,6 @@ public static function setPluginBroker(Broker $broker) */ public static function resetPluginBroker() { - static::$pluginBroker = new Storage\PluginBroker(); + static::$pluginBroker = null; } } diff --git a/test/PatternFactoryTest.php b/test/PatternFactoryTest.php index 4009aaa0e..ee66ea314 100644 --- a/test/PatternFactoryTest.php +++ b/test/PatternFactoryTest.php @@ -57,4 +57,15 @@ public function testChangeBroker() $this->assertSame($broker, Cache\PatternFactory::getBroker()); } + public function testFactory() + { + $pattern1 = Cache\PatternFactory::factory('capture'); + $this->assertInstanceOf('Zend\Cache\Pattern\CaptureCache', $pattern1); + + $pattern2 = Cache\PatternFactory::factory('capture'); + $this->assertInstanceOf('Zend\Cache\Pattern\CaptureCache', $pattern2); + + $this->assertNotSame($pattern1, $pattern2); + } + } diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index c39cf6d56..fd62ca36d 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -42,6 +42,8 @@ public function setUp() public function tearDown() { + Cache\StorageFactory::resetAdapterBroker(); + Cache\StorageFactory::resetPluginBroker(); } public function testDefaultAdapterBroker() @@ -59,8 +61,13 @@ public function testChangeAdapterBroker() public function testAdapterFactory() { - $cache = Cache\StorageFactory::adapterFactory('Memory'); - $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $cache); + $adapter1 = Cache\StorageFactory::adapterFactory('Memory'); + $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $adapter1); + + $adapter2 = Cache\StorageFactory::adapterFactory('Memory'); + $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $adapter2); + + $this->assertNotSame($adapter1, $adapter2); } public function testDefaultPluginBroker() @@ -78,8 +85,13 @@ public function testChangePluginBroker() public function testPluginFactory() { - $plugin = Cache\StorageFactory::pluginFactory('Serializer'); - $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $plugin); + $plugin1 = Cache\StorageFactory::pluginFactory('Serializer'); + $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $plugin1); + + $plugin2 = Cache\StorageFactory::pluginFactory('Serializer'); + $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $plugin2); + + $this->assertNotSame($plugin1, $plugin2); } public function testFactoryAdapterAsString() From 1786d34e0a80456e94cc2828bdefb15804d840f8 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 16 Mar 2012 23:03:36 +0100 Subject: [PATCH 220/311] Cache internals: Now all events will be triggered by abstract adapter and calls a protected method which can have to be implemented / overwritten within specific adapters. This also fixes problems if pre-implemented methods at abstract adapter triggering wrong events. (like getItems triggered getItem events of each item) --- src/Storage/Adapter.php | 38 +- src/Storage/Adapter/AbstractAdapter.php | 1501 +++++++++++++++++--- src/Storage/Adapter/AbstractZendServer.php | 226 +-- src/Storage/Adapter/Apc.php | 923 ++++-------- src/Storage/Adapter/Filesystem.php | 1077 +++++++------- src/Storage/Adapter/Memcached.php | 786 ++++------ src/Storage/Adapter/Memory.php | 996 ++++--------- src/Storage/Adapter/WinCache.php | 565 +++----- src/Storage/Adapter/ZendServerDisk.php | 27 +- src/Storage/Adapter/ZendServerShm.php | 38 +- 10 files changed, 2920 insertions(+), 3257 deletions(-) diff --git a/src/Storage/Adapter.php b/src/Storage/Adapter.php index 94dacc043..1b8dbd3ee 100644 --- a/src/Storage/Adapter.php +++ b/src/Storage/Adapter.php @@ -210,7 +210,7 @@ public function addItem($key, $value, array $options = array()); public function addItems(array $keyValuePairs, array $options = array()); /** - * Replace an item. + * Replace an existing item. * * @param string $key * @param mixed $value @@ -221,7 +221,7 @@ public function addItems(array $keyValuePairs, array $options = array()); public function replaceItem($key, $value, array $options = array()); /** - * Replace multiple items. + * Replace multiple existing items. * * @param array $keyValuePairs * @param array $options @@ -231,15 +231,15 @@ public function replaceItem($key, $value, array $options = array()); public function replaceItems(array $keyValuePairs, array $options = array()); /** - * Set item only if token matches + * Set an item only if token matches * - * It uses the token from received from getItem() to check if the item has + * It uses the token received from getItem() to check if the item has * changed before overwriting it. * - * @param mixed $token - * @param string|null $key - * @param mixed $value - * @param array $options + * @param mixed $token + * @param string $key + * @param mixed $value + * @param array $options * @return boolean * @throws \Zend\Cache\Exception * @see getItem() @@ -251,7 +251,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()); * Reset lifetime of an item * * @param string $key - * @param array $options + * @param array $options * @return boolean * @throws \Zend\Cache\Exception */ @@ -271,7 +271,7 @@ public function touchItems(array $keys, array $options = array()); * Remove an item. * * @param string $key - * @param array $options + * @param array $options * @return boolean * @throws \Zend\Cache\Exception */ @@ -291,9 +291,9 @@ public function removeItems(array $keys, array $options = array()); * Increment an item. * * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value of false on failure + * @param int $value + * @param array $options + * @return int|boolean The new value or false on failure * @throws \Zend\Cache\Exception */ public function incrementItem($key, $value, array $options = array()); @@ -312,9 +312,9 @@ public function incrementItems(array $keyValuePairs, array $options = array()); * Decrement an item. * * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value or false or failure + * @param int $value + * @param array $options + * @return int|boolean The new value or false on failure * @throws \Zend\Cache\Exception */ public function decrementItem($key, $value, array $options = array()); @@ -346,7 +346,7 @@ public function getDelayed(array $keys, array $options = array()); /** * Find items. * - * @param int $mode Matching mode (Value of Adapter::*) + * @param int $mode Matching mode (Value of Adapter::MATCH_*) * @param array $options * @return boolean * @throws \Zend\Cache\Exception @@ -378,7 +378,7 @@ public function fetchAll(); /** * Clear items off all namespaces. * - * @param int $mode Matching mode (Value of Adapter::MATCH_*) + * @param int $mode Matching mode (Value of Adapter::MATCH_*) * @param array $options * @return boolean * @throws \Zend\Cache\Exception @@ -389,7 +389,7 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()); /** * Clear items by namespace. * - * @param int $mode Matching mode (Value of Adapter::MATCH_*) + * @param int $mode Matching mode (Value of Adapter::MATCH_*) * @param array $options * @return boolean * @throws \Zend\Cache\Exception diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 896ad11ac..f0317e22b 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -788,6 +788,8 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags * * @param string $key * @param mixed $value @@ -834,6 +836,8 @@ public function setItem($key, $value, array $options = array()) * - The time-to-life * - namespace * - The namespace to use + * - tags + * - An array of tags * * @param string $normalizedKey * @param mixed $value @@ -851,6 +855,8 @@ abstract protected function internalSetItem(& $normalizedKey, & $value, array & * - The time-to-life (Default: ttl of object) * - namespace optional * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags * * @param array $keyValuePairs * @param array $options @@ -867,6 +873,7 @@ public function setItems(array $keyValuePairs, array $options = array()) return false; } + $this->normalizeKeyValuePairs($keyValuePairs); $this->normalizeOptions($options); $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, @@ -894,6 +901,8 @@ public function setItems(array $keyValuePairs, array $options = array()) * - The time-to-life * - namespace * - The namespace to use + * - tags + * - An array of tags * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions @@ -910,28 +919,97 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n } /** - * Add an item + * Add an item. * - * @param string|int $key - * @param mixed $value - * @param array $options - * @return bool - * @throws Exception\RuntimeException + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers addItem.pre(PreEvent) + * @triggers addItem.post(PostEvent) + * @triggers addItem.exception(ExceptionEvent) */ public function addItem($key, $value, array $options = array()) { - if ($this->hasItem($key, $options)) { - throw new Exception\RuntimeException("Key '{$key}' already exists"); + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalAddItem($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to add an item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) + { + if ($this->internalHasItem($normalizedKey, $normalizedOptions)) { + throw new Exception\RuntimeException("Key '{$normalizedKey}' already exists"); } - return $this->setItem($key, $value, $options); + return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); } /** - * Add items + * Add multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags * * @param array $keyValuePairs * @param array $options - * @return bool + * @return boolean + * @throws Exception + * + * @triggers addItems.pre(PreEvent) + * @triggers addItems.post(PostEvent) + * @triggers addItems.exception(ExceptionEvent) */ public function addItems(array $keyValuePairs, array $options = array()) { @@ -939,38 +1017,144 @@ public function addItems(array $keyValuePairs, array $options = array()) return false; } - $ret = true; - foreach ($keyValuePairs as $key => $value) { - $ret = $this->addItem($key, $value, $options) && $ret; + $this->normalizeKeyValuePairs($keyValuePairs); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalAddItems($keyValuePairs, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } + } + /** + * Internal method to add multiple items. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + { + $ret = true; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $ret = $this->internalAddItem($normalizedKey, $value, $normalizedOptions) && $ret; + } return $ret; } /** - * Replace an item + * Replace an existing item. * - * @param string|int $key - * @param mixed $value - * @param array $options - * @return bool - * @throws Exception\ItemNotFoundException + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers replaceItem.pre(PreEvent) + * @triggers replaceItem.post(PostEvent) + * @triggers replaceItem.exception(ExceptionEvent) */ public function replaceItem($key, $value, array $options = array()) { - if (!$this->hasItem($key, $options)) { - throw new Exception\ItemNotFoundException("Key '{$key}' doen't exists"); + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalReplaceItem($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to replace an existing item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) + { + if (!$this->internalhasItem($normalizedKey, $normalizedOptions)) { + throw new Exception\ItemNotFoundException("Key '{$normalizedKey}' doesn't exists"); } - return $this->setItem($key, $value, $options); + return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); } /** - * Replace items + * Replace multiple existing items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags * * @param array $keyValuePairs * @param array $options - * @return bool + * @return boolean + * @throws Exception + * + * @triggers replaceItems.pre(PreEvent) + * @triggers replaceItems.post(PostEvent) + * @triggers replaceItems.exception(ExceptionEvent) */ public function replaceItems(array $keyValuePairs, array $options = array()) { @@ -978,190 +1162,705 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return false; } - $ret = true; - foreach ($keyValuePairs as $key => $value) { - $ret = $this->replaceItem($key, $value, $options) && $ret; + $this->normalizeKeyValuePairs($keyValuePairs); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalReplaceItems($keyValuePairs, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to replace multiple existing items. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalReplaceItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + { + $ret = true; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $ret = $this->internalReplaceItem($normalizedKey, $value, $normalizedOptions) && $ret; + } + + return $ret; + } + + /** + * Set an item only if token matches + * + * It uses the token received from getItem() to check if the item has + * changed before overwriting it. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param mixed $token + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * @see getItem() + * @see setItem() + */ + public function checkAndSetItem($token, $key, $value, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalCheckAndSetItem($token, $key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to set an item only if token matches + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param mixed $token + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see getItem() + * @see setItem() + */ + protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) + { + $oldValue = $this->internalGetItem($normalizedKey, $normalizedOptions); + if ($oldValue !== $token) { + return false; + } + + return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); + } + + /** + * Reset lifetime of an item + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers touchItem.pre(PreEvent) + * @triggers touchItem.post(PostEvent) + * @triggers touchItem.exception(ExceptionEvent) + */ + public function touchItem($key, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalTouchItem($key, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to reset lifetime of an item + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) + { + // do not test validity on reading + // $optsNoValidate = array('ttl' => 0) + $normalizedOptions; + + $value = $this->internalGetItem($normalizedKey, $normalizedOptions); + if ($value === false) { + // add an empty item + $value = ''; + return $this->internalAddItem($normalizedKey, $value, $normalizedOptions); + } + + // rewrite item to update mtime/ttl + if (!isset($normalizedOptions['tags'])) { + $info = $this->internalGetMetadata($normalizedKey, $normalizedOptions); + if (isset($info['tags'])) { + $normalizedOptions['tags'] = & $info['tags']; + } + } + + return $this->internalReplaceItem($normalizedKey, $value, $normalizedOptions); + } + + /** + * Reset lifetime of multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers touchItems.pre(PreEvent) + * @triggers touchItems.post(PostEvent) + * @triggers touchItems.exception(ExceptionEvent) + */ + public function touchItems(array $keys, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeKeys($keys); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalTouchItems($keys, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to reset lifetime of multiple items. + * + * Options: + * - ttl + * - The namespace to us + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalTouchItems(array & $normalizedKeys, array & $normalizedOptions) + { + $ret = true; + foreach ($normalizedKeys as $normalizedKey) { + $ret = $this->internalTouchItem($normalizedKey, $normalizedOptions) && $ret; + } + return $ret; + } + + /** + * Remove an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers removeItem.pre(PreEvent) + * @triggers removeItem.post(PostEvent) + * @triggers removeItem.exception(ExceptionEvent) + */ + public function removeItem($key, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalRemoveItem($key, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to remove an item. + * + * Options: + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + abstract protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions); + + /** + * Remove multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers removeItems.pre(PreEvent) + * @triggers removeItems.post(PostEvent) + * @triggers removeItems.exception(ExceptionEvent) + */ + public function removeItems(array $keys, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKeys($keys); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalRemoveItems($keys, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to remove multiple items. + * + * Options: + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + */ + protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) + { + $ret = true; + $missingKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + try { + $ret = $this->internalRemoveItem($normalizedKey, $normalizedOptions) && $ret; + } catch (Exception\ItemNotFoundException $e) { + $missingKeys[] = $normalizedKey; + } + } + + if ($missingKeys) { + throw new Exception\ItemNotFoundException( + "Keys '".implode(',', $missingKeys)."' not found within namespace '{$normalizedOptions['namespace']}'" + ); + } + + return $ret; + } + + /** + * Increment an item. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item + * + * @param string $key + * @param int $value + * @param array $options + * @return int|boolean The new value or false on failure + * @throws Exception + * + * @triggers incrementItem.pre(PreEvent) + * @triggers incrementItem.post(PostEvent) + * @triggers incrementItem.exception(ExceptionEvent) + */ + public function incrementItem($key, $value, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalIncrementItem($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } - - return $ret; } /** - * Check and set item + * Internal method to increment an item. * - * @param mixed $token - * @param string $key - * @param mixed $value - * @param array $options - * @return bool + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure + * @throws Exception */ - public function checkAndSetItem($token, $key, $value, array $options = array()) + protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $oldValue = $this->getItem($key, $options); - if ($oldValue != $token) { - return false; - } - - return $this->setItem($key, $value, $options); + $value = (int) $value; + $get = (int) $this->internalGetItem($normalizedKey, $normalizedOptions); + $newValue = $get + $value; + $this->internalSetItem($normalizedKey, $newValue, $normalizedOptions); + return $newValue; } /** - * Touch an item + * Increment multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item * - * @param string|int $key + * @param array $keyValuePairs * @param array $options - * @return bool + * @return boolean + * @throws Exception + * + * @triggers incrementItems.pre(PreEvent) + * @triggers incrementItems.post(PostEvent) + * @triggers incrementItems.exception(ExceptionEvent) */ - public function touchItem($key, array $options = array()) + public function incrementItems(array $keyValuePairs, array $options = array()) { - $classOptions = $this->getOptions(); - if (!$classOptions->getWritable() || !$classOptions->getReadable()) { - return false; - } + if (!$this->getOptions()->getWritable()) { + return false; + } - // do not test validity on reading - $optsNoValidate = array('ttl' => 0) + $options; + $this->normalizeOptions($options); + $this->normalizeKeyValuePairs($keyValuePairs); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); - $value = $this->getItem($key, $optsNoValidate); - if ($value === false) { - // add an empty item - return $this->addItem($key, '', $options); - } else { - // rewrite item to update mtime/ttl - if (!isset($options['tags'])) { - $info = $this->getMetadata($key, $optsNoValidate); - if (isset($info['tags'])) { - $options['tags'] = & $info['tags']; - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); } - // rewrite item - return $this->replaceItem($key, $value, $options); + $result = $this->internatIncrementItems($keyValuePairs, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); } } /** - * Touch items + * Internal method to increment multiple items. * - * @param array $keys - * @param array $options - * @return bool + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception */ - public function touchItems(array $keys, array $options = array()) + protected function internatIncrementItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - // Don't check readable because not all adapters needs to read the item before - if (!$this->getOptions()->getWritable()) { - return false; - } - $ret = true; - foreach ($keys as $key) { - $ret = $this->touchItem($key, $options) && $ret; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $ret = ($this->incrementItem($normalizedKey, $value, $normalizedOptions) !== false) && $ret; } return $ret; } /** - * Remove multiple items. + * Decrement an item. * - * @param array $keys - * @param array $options - * @return bool + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item + * + * @param string $key + * @param int $value + * @param array $options + * @return int|boolean The new value or false on failure + * @throws Exception + * + * @triggers decrementItem.pre(PreEvent) + * @triggers decrementItem.post(PostEvent) + * @triggers decrementItem.exception(ExceptionEvent) */ - public function removeItems(array $keys, array $options = array()) + public function decrementItem($key, $value, array $options = array()) { if (!$this->getOptions()->getWritable()) { return false; } - $ret = true; - foreach ($keys as $key) { - $ret = $this->removeItem($key, $options) && $ret; - } + $this->normalizeOptions($options); + $this->normalizeKey($key); + $args = new ArrayObject(array( + 'key' => & $key, + 'value' => & $value, + 'options' => & $options, + )); - return $ret; + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalDecrementItem($key, $value, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** - * Increment an item + * Internal method to decrement an item. * - * @param string|int $key - * @param int|float $value - * @param array $options - * @return bool|int + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure + * @throws Exception */ - public function incrementItem($key, $value, array $options = array()) + protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $classOptions = $this->getOptions(); - if (!$classOptions->getWritable() || !$classOptions->getReadable()) { - return false; - } - - $value = (int) $value; - $get = (int) $this->getItem($key, $options); - $this->setItem($key, $get + $value, $options); - return $get + $value; + $value = (int) $value; + $get = (int) $this->internalGetItem($normalizedKey, $normalizedOptions); + $newValue = $get - $value; + $this->internalSetItem($normalizedKey, $newValue, $normalizedOptions); + return $newValue; } /** - * Increment items + * Decrement multiple items. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item * * @param array $keyValuePairs * @param array $options - * @return bool + * @return boolean + * @throws Exception + * + * @triggers incrementItems.pre(PreEvent) + * @triggers incrementItems.post(PostEvent) + * @triggers incrementItems.exception(ExceptionEvent) */ - public function incrementItems(array $keyValuePairs, array $options = array()) + public function decrementItems(array $keyValuePairs, array $options = array()) { - // Don't check readable because not all adapters needs read the value before if (!$this->getOptions()->getWritable()) { return false; } - $ret = true; - foreach ($keyValuePairs as $key => $value) { - $ret = $this->incrementItem($key, $value, $options) && $ret; - } - return $ret; - } + $this->normalizeOptions($options); + $this->normalizeKeyValuePairs($keyValuePairs); + $args = new ArrayObject(array( + 'keyValuePairs' => & $keyValuePairs, + 'options' => & $options, + )); - /** - * Decrement an item - * - * @param string|int $key - * @param int|float $value - * @param array $options - * @return bool|int - */ - public function decrementItem($key, $value, array $options = array()) - { - $classOptions = $this->getOptions(); - if (!$classOptions->getWritable() || !$classOptions->getReadable()) { - return false; - } + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } - $value = (int) $value; - $get = (int) $this->getItem($key, $options); - $this->setItem($key, $get - $value, $options); - return $get - $value; + $result = $this->internatDecrementItems($keyValuePairs, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } } /** - * Decrement items + * Internal method to decrement multiple items. * - * @param array $keyValuePairs - * @param array $options - * @return bool + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception */ - public function decrementItems(array $keyValuePairs, array $options = array()) + protected function internatDecrementItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - // Don't check readable because not all adapters needs read the value before - if (!$this->getOptions()->getWritable()) { - return false; - } - $ret = true; - foreach ($keyValuePairs as $key => $value) { - $ret = $this->decrementItem($key, $value, $options) && $ret; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $ret = ($this->decrementItem($normalizedKey, $value, $normalizedOptions) !== false) && $ret; } return $ret; } @@ -1169,7 +1868,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) /* non-blocking */ /** - * Get delayed + * Request multiple items. * * Options: * - ttl optional @@ -1184,67 +1883,202 @@ public function decrementItems(array $keyValuePairs, array $options = array()) * - The first argument will be the item array. * - The callback does not have to return anything. * - * @param array $keys - * @param array $options - * @return bool - * @throws Exception\InvalidArgumentException|Exception\RuntimeException + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() + * + * @triggers getDelayed.pre(PreEvent) + * @triggers getDelayed.post(PostEvent) + * @triggers getDelayed.exception(ExceptionEvent) */ public function getDelayed(array $keys, array $options = array()) { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - if (!$this->getOptions()->getReadable()) { return false; } elseif (!$keys) { // empty statement return true; } - - $this->normalizeOptions($options); - if (!isset($options['select'])) { - $options['select'] = array('key', 'value'); - } - - $this->stmtOptions = array_merge($this->getOptions()->toArray(), $options); - $this->stmtKeys = $keys; - $this->stmtActive = true; - - if (isset($options['callback'])) { - $callback = $options['callback']; - if (!is_callable($callback, false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - while ( ($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - return true; + + $this->normalizeKeys($keys); + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'keys' => & $keys, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetDelayed($keys, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to request multiple items. + * + * Options: + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use + * - select + * - An array of the information the returned item contains + * - callback optional + * - An result callback will be invoked for each item in the result set. + * - The first argument will be the item array. + * - The callback does not have to return anything. + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() + */ + protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) + { + if ($this->stmtActive) { + throw new Exception\RuntimeException('Statement already in use'); + } + + $this->stmtOptions = array_merge($this->getOptions()->toArray(), $normalizedOptions); + $this->stmtKeys = & $normalizedKeys; + $this->stmtActive = true; + + if (isset($normalizedOptions['callback'])) { + $callback = $normalizedOptions['callback']; + if (!is_callable($callback, false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } + + while ( ($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + return true; } - /* find */ + /* find */ + + /** + * Find items. + * + * Options: + * - ttl optional + * - The time-to-live (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of + * Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Adapter::MATCH_*) + * @param array $options + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() + * + * @triggers find.pre(PreEvent) + * @triggers find.post(PostEvent) + * @triggers find.exception(ExceptionEvent) + */ + public function find($mode = self::MATCH_ACTIVE, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalFind($mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } /** - * Find + * internal method to find items. * - * @param int $mode - * @param array $options - * @throws Exception\UnsupportedMethodCallException + * Options: + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use + * - tags + * - Tags to search for used with matching modes of + * Adapter::MATCH_TAGS_* + * + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() */ - public function find($mode = self::MATCH_ACTIVE, array $options = array()) + protected function internalFind(& $normalizedMode, array & $normalizedOptions) { throw new Exception\UnsupportedMethodCallException('find isn\'t supported by this adapter'); } /** - * Fetch + * Fetches the next item from result set * - * @return array|bool + * @return array|boolean The next item or false + * @throws Exception + * @see fetchAll() + * + * @triggers fetch.pre(PreEvent) + * @triggers fetch.post(PostEvent) + * @triggers fetch.exception(ExceptionEvent) */ public function fetch() + { + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalFetch(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to fetch the next item from result set + * + * @return array|boolean The next item or false + * @throws Exception + */ + protected function internalFetch() { if (!$this->stmtActive) { return false; @@ -1264,7 +2098,7 @@ public function fetch() if ($select == 'key') { $item['key'] = $key; } elseif ($select == 'value') { - $value = $this->getItem($key, $options); + $value = $this->internalGetItem($key, $options); if ($value === false) { $exist = false; break; @@ -1273,7 +2107,7 @@ public function fetch() $item['value'] = $value; } else { if ($info === null) { - $info = $this->getMetadata($key, $options); + $info = $this->internalGetMetadata($key, $options); if ($info === false) { $exist = false; break; @@ -1285,9 +2119,7 @@ public function fetch() } // goto next if not exists - if ($exist === false - || ($exist === null && !$this->hasItem($key, $options)) - ) { + if ($exist === false || ($exist === null && !$this->internalHasItem($key, $options))) { continue; } @@ -1303,14 +2135,44 @@ public function fetch() } /** - * Fetch all + * Returns all items of result set. * - * @return array + * @return array The result set as array containing all items + * @throws Exception + * @see fetch() + * + * @triggers fetchAll.pre(PreEvent) + * @triggers fetchAll.post(PostEvent) + * @triggers fetchAll.exception(ExceptionEvent) */ public function fetchAll() + { + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalFetchAll(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to return all items of result set. + * + * @return array The result set as array containing all items + * @throws Exception + * @see fetch() + */ + protected function internalFetchAll() { $rs = array(); - while (($item = $this->fetch()) !== false) { + while (($item = $this->internalFetch()) !== false) { $rs[] = $item; } return $rs; @@ -1319,13 +2181,66 @@ public function fetchAll() /* cleaning */ /** - * Clear + * Clear items off all namespaces. * - * @param int $mode + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - tags optional + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* + * + * @param int $mode Matching mode (Value of Adapter::MATCH_*) * @param array $options - * @throws Exception\RuntimeException + * @return boolean + * @throws Exception + * @see clearByNamespace() + * + * @triggers clear.pre(PreEvent) + * @triggers clear.post(PostEvent) + * @triggers clear.exception(ExceptionEvent) */ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalClear($mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to clear items off all namespaces. + * + * Options: + * - ttl + * - The time-to-life + * - tags + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* + * + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see clearByNamespace() + */ + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { throw new Exception\RuntimeException( "This adapter doesn't support to clear items off all namespaces" @@ -1333,13 +2248,70 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) } /** - * Clear by namespace + * Clear items by namespace. + * + * Options: + * - ttl optional + * - The time-to-life (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* * - * @param int $mode + * @param int $mode Matching mode (Value of Adapter::MATCH_*) * @param array $options - * @throws Exception\RuntimeException + * @return boolean + * @throws Exception + * @see clear() + * + * @triggers clearByNamespace.pre(PreEvent) + * @triggers clearByNamespace.post(PostEvent) + * @triggers clearByNamespace.exception(ExceptionEvent) */ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $this->normalizeOptions($options); + $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); + $args = new ArrayObject(array( + 'mode' => & $mode, + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalClearByNamespace($mode, $options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Clear items by namespace. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* + * + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see clear() + */ + protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) { throw new Exception\RuntimeException( "This adapter doesn't support to clear items by namespace" @@ -1347,12 +2319,53 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a } /** - * Optimize + * Optimize adapter storage. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) * * @param array $options - * @return bool + * @return boolean + * @throws Exception + * + * @triggers optimize.pre(PreEvent) + * @triggers optimize.post(PostEvent) + * @triggers optimize.exception(ExceptionEvent) */ public function optimize(array $options = array()) + { + if (!$this->getOptions()->getWritable()) { + return false; + } + + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalOptimize(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to optimize adapter storage. + * + * Options: + * - namespace + * - The namespace to use + * + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalOptimize(array & $normalizedOptions) { return true; } @@ -1363,8 +2376,33 @@ public function optimize(array $options = array()) * Get capabilities of this adapter * * @return Capabilities + * @triggers getCapabilities.pre(PreEvent) + * @triggers getCapabilities.post(PostEvent) + * @triggers getCapabilities.exception(ExceptionEvent) */ public function getCapabilities() + { + $args = new ArrayObject(); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetCapabilities(); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to get capabilities of this adapter + * + * @return Capabilities + */ + protected function internalGetCapabilities() { if ($this->capabilities === null) { $this->capabilityMarker = new stdClass(); @@ -1373,12 +2411,53 @@ public function getCapabilities() return $this->capabilities; } + /** + * Get storage capacity. + * + * @param array $options + * @return array|boolean Capacity as array or false on failure + * @throws Exception + * + * @triggers getCapacity.pre(PreEvent) + * @triggers getCapacity.post(PostEvent) + * @triggers getCapacity.exception(ExceptionEvent) + */ + public function getCapacity(array $options = array()) + { + $this->normalizeOptions($options); + $args = new ArrayObject(array( + 'options' => & $options, + )); + + try { + $eventRs = $this->triggerPre(__FUNCTION__, $args); + if ($eventRs->stopped()) { + return $eventRs->last(); + } + + $result = $this->internalGetCapacity($options); + return $this->triggerPost(__FUNCTION__, $args, $result); + } catch (\Exception $e) { + return $this->triggerException(__FUNCTION__, $args, $e); + } + } + + /** + * Internal method to get storage capacity. + * + * @param array $normalizedOptions + * @return array|boolean Capacity as array or false on failure + * @throws Exception + */ + abstract protected function internalGetCapacity(array & $normalizedOptions); + /* internal */ /** * Validates and normalizes the $options argument * * @param array $options + * @return void */ protected function normalizeOptions(array &$options) { @@ -1424,6 +2503,7 @@ protected function normalizeOptions(array &$options) * Validates and normalize a TTL. * * @param int|float $ttl + * @return void * @throws Exception\InvalidArgumentException */ protected function normalizeTtl(&$ttl) @@ -1446,6 +2526,7 @@ protected function normalizeTtl(&$ttl) * Validates and normalize a namespace. * * @param string $namespace + * @return void * @throws Exception\InvalidArgumentException */ protected function normalizeNamespace(&$namespace) @@ -1465,6 +2546,7 @@ protected function normalizeNamespace(&$namespace) * Validates and normalize tags array * * @param array $tags + * @return void * @throws Exception\InvalidArgumentException */ protected function normalizeTags(&$tags) @@ -1487,6 +2569,7 @@ protected function normalizeTags(&$tags) * Validates and normalize select array * * @param string[]|string + * @return void */ protected function normalizeSelect(&$select) { @@ -1503,6 +2586,7 @@ protected function normalizeSelect(&$select) * @todo normalize matching mode with given tags * @param int $mode Matching mode to normalize * @param int $default Default matching mode + * @return void */ protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOptions) { @@ -1518,7 +2602,7 @@ protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOpt * Validates and normalizes a key * * @param string $key - * @return string + * @return void * @throws Exception\InvalidArgumentException On an invalid key */ protected function normalizeKey(&$key) @@ -1540,7 +2624,7 @@ protected function normalizeKey(&$key) * Validates and normalizes multiple keys * * @param array $keys - * @return array + * @return void * @throws Exception\InvalidArgumentException On an invalid key */ protected function normalizeKeys(array &$keys) @@ -1555,6 +2639,23 @@ protected function normalizeKeys(array &$keys) $keys = array_values(array_unique($keys)); } + /** + * Validates and normalizes an array of key-value paírs + * + * @param array $keyValuePairs + * @return void + * @throws Exception\InvalidArgumentException On an invalid key + */ + protected function normalizeKeyValuePairs(array & $keyValuePairs) + { + $normalizedKeyValuePairs = array(); + foreach ($keyValuePairs as $key => $value) { + $this->normalizeKey($key); + $normalizedKeyValuePairs[$key] = $value; + } + $keyValuePairs = $normalizedKeyValuePairs; + } + /** * Return registry of plugins * diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 8253a5186..5b9b3d5f9 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -211,209 +211,119 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz } /** - * Remove an item. + * Internal method to remove an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; + $internalKey = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR . $normalizedKey; + if (!$this->zdcDelete($internalKey) && !$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - $this->normalizeKey($key); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . self::NAMESPACE_SEPARATOR . $key; - if (!$this->zdcDelete($internalKey) && !$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /* cleaning */ /** - * Clear items off all namespaces. + * Internal method to clear items off all namespaces. * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see clearByNamespace() - * - * @triggers clear.pre(PreEvent) - * @triggers clear.post(PostEvent) - * @triggers clear.exception(ExceptionEvent) + * @see clearByNamespace() */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; + // clear all + if (($normalizedMode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $this->zdcClear(); } - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - // clear all - if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $this->zdcClear(); - } - - // expired items will be deleted automatic + // expired items will be deleted automatic - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** * Clear items by namespace. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean - * @throws Zend\Cache\Exception - * @see clear() - * - * @triggers clearByNamespace.pre(PreEvent) - * @triggers clearByNamespace.post(PostEvent) - * @triggers clearByNamespace.exception(ExceptionEvent) + * @throws Exception + * @see clear() */ - public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; + // clear all + if (($normalizedMode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $this->zdcClearByNamespace($normalizedOptions['namespace']); } - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - // clear all - if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $this->zdcClearByNamespace($options['namespace']); - } - - // expired items will be deleted automatic + // expired items will be deleted automatic - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /* status */ /** - * Get capabilities + * Internal method to get capabilities of this adapter * * @return Capabilities - * - * @triggers getCapabilities.pre(PreEvent) - * @triggers getCapabilities.post(PostEvent) - * @triggers getCapabilities.exception(ExceptionEvent) */ - public function getCapabilities() + protected function internalGetCapabilities() { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'maxTtl' => 0, - 'staticTtl' => true, - 'tagging' => false, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 0, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, - ) - ); - } - - return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array(), + 'maxTtl' => 0, + 'staticTtl' => true, + 'tagging' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => false, + 'expiredRead' => false, + 'maxKeyLength' => 0, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, + 'iterable' => false, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); } + + return $this->capabilities; } /* internal wrapper of zend_[disk|shm]_cache_* functions */ diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 9deccb8c3..5c2459681 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -422,807 +422,494 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * Add an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers addItem.pre(PreEvent) - * @triggers addItem.post(PostEvent) - * @triggers addItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!apc_add($internalKey, $value, $options['ttl'])) { - if (apc_exists($internalKey)) { - throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); - } - - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "apc_add('{$internalKey}', <{$type}>, {$options['ttl']}) failed" - ); + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!apc_add($internalKey, $value, $normalizedOptions['ttl'])) { + if (apc_exists($internalKey)) { + throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "apc_add('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + ); } + + return true; } /** - * Add multiple items. + * Internal method to add multiple items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers addItems.pre(PreEvent) - * @triggers addItems.post(PostEvent) - * @triggers addItems.exception(ExceptionEvent) */ - public function addItems(array $keyValuePairs, array $options = array()) + protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKeyValuePairs = array(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $internalKey = $prefix . $normalizedKey; + $internalKeyValuePairs[$internalKey] = $value; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeyValuePairs = array(); - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - foreach ($keyValuePairs as $key => &$value) { - $internalKey = $prefix . $key; - $internalKeyValuePairs[$internalKey] = &$value; - } - - $errKeys = apc_add($internalKeyValuePairs, null, $options['ttl']); - if ($errKeys) { - throw new Exception\RuntimeException( - "apc_add(, null, {$options['ttl']}) failed for keys: " - . "'" . implode("','", $errKeys) . "'" - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $errKeys = apc_add($internalKeyValuePairs, null, $normalizedOptions['ttl']); + if ($errKeys) { + throw new Exception\RuntimeException( + "apc_add(, null, {$normalizedOptions['ttl']}) failed for keys: " + . "'" . implode("','", $errKeys) . "'" + ); } + + return true; } /** - * Replace an item. + * Internal method to replace an existing item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers replaceItem.pre(PreEvent) - * @triggers replaceItem.post(PostEvent) - * @triggers replaceItem.exception(ExceptionEvent) */ - public function replaceItem($key, $value, array $options = array()) + protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!apc_exists($internalKey)) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' doesn't exist" + ); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!apc_exists($internalKey)) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' doesn't exist" - ); - } - - if (!apc_store($internalKey, $value, $options['ttl'])) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "apc_store('{$internalKey}', <{$type}>, {$options['ttl']}) failed" - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + if (!apc_store($internalKey, $value, $normalizedOptions['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "apc_store('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + ); } + + return true; } /** - * Remove an item. + * Internal method to remove an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!apc_delete($internalKey) && !$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!apc_delete($internalKey)) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Remove multiple items. + * Internal method to remove multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * * @param array $keys * @param array $options * @return boolean * @throws Exception - * - * @triggers removeItems.pre(PreEvent) - * @triggers removeItems.post(PostEvent) - * @triggers removeItems.exception(ExceptionEvent) */ - public function removeItems(array $keys, array $options = array()) + protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKeys = array(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeys = array(); - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - foreach ($keys as $key) { - $internalKeys[] = $prefix . $key; - } - - $errKeys = apc_delete($internalKeys); - if ($errKeys) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); - } - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $errKeys = apc_delete($internalKeys); + if ($errKeys && !$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Keys '" . implode("','", $errKeys) . "' not found"); } + + return true; } /** - * Increment an item. + * Internal method to increment an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers incrementItem.pre(PreEvent) - * @triggers incrementItem.post(PostEvent) - * @triggers incrementItem.exception(ExceptionEvent) */ - public function incrementItem($key, $value, array $options = array()) + protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $value = (int)$value; + $newValue = apc_inc($internalKey, $value); + if ($newValue === false) { + if (apc_exists($internalKey)) { + throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); + } elseif (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' not found" + ); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $value = (int)$value; - $newValue = apc_inc($internalKey, $value); - if ($newValue === false) { - if (apc_exists($internalKey)) { - throw new Exception\RuntimeException("apc_inc('{$internalKey}', {$value}) failed"); - } elseif (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); - } - - $this->addItem($key, $value, $options); - $newValue = $value; + $newValue = $value; + if (!apc_add($internalKey, $newValue, $normalizedOptions['ttl'])) { + throw new Exception\RuntimeException( + "apc_add('{$internalKey}', {$newValue}, {$normalizedOptions['ttl']}) failed" + ); } - - return $this->triggerPost(__FUNCTION__, $args, $newValue); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $newValue; } /** - * Decrement an item. + * Internal method to decrement an item. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value or false or failure + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers decrementItem.pre(PreEvent) - * @triggers decrementItem.post(PostEvent) - * @triggers decrementItem.exception(ExceptionEvent) */ - public function decrementItem($key, $value, array $options = array()) + protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $value = (int)$value; + $newValue = apc_dec($internalKey, $value); + if ($newValue === false) { + if (apc_exists($internalKey)) { + throw new Exception\RuntimeException("apc_dec('{$internalKey}', {$value}) failed"); + } elseif (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' not found" + ); } - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $value = (int)$value; - $newValue = apc_dec($internalKey, $value); - if ($newValue === false) { - if (apc_exists($internalKey)) { - throw new Exception\RuntimeException("apc_dec('{$internalKey}', {$value}) failed"); - } elseif (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); - } - - $this->addItem($key, -$value, $options); - $newValue = -$value; + $newValue = -$value; + if (!apc_add($internalKey, $newValue, $normalizedOptions['ttl'])) { + throw new Exception\RuntimeException( + "apc_add('{$internalKey}', {$newValue}, {$normalizedOptions['ttl']}) failed" + ); } - - return $this->triggerPost(__FUNCTION__, $args, $newValue); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $newValue; } /* non-blocking */ - /** - * Get items that were marked to delay storage for purposes of removing blocking - * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param array $keys - * @param array $options - * @return bool - * @throws Exception - * - * @triggers getDelayed.pre(PreEvent) - * @triggers getDelayed.post(PostEvent) - * @triggers getDelayed.exception(ExceptionEvent) + /** + * Internal method to request multiple items. + * + * Options: + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use + * - select + * - An array of the information the returned item contains + * - callback optional + * - An result callback will be invoked for each item in the result set. + * - The first argument will be the item array. + * - The callback does not have to return anything. + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() */ - public function getDelayed(array $keys, array $options = array()) + protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); - } elseif (!$baseOptions->getReadable()) { - return false; - } elseif (!$keys) { - return true; } - $this->normalizeOptions($options); - if (isset($options['callback']) && !is_callable($options['callback'], false)) { + if (isset($normalizedOptions['callback']) && !is_callable($normalizedOptions['callback'], false)) { throw new Exception\InvalidArgumentException('Invalid callback'); } - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $format = 0; + foreach ($normalizedOptions['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; } + } + + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $search = array(); + foreach ($normalizedKeys as $normalizedKey) { + $search[] = preg_quote($normalizedKey, '/'); + } + $search = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $search) . ')$/'; - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - $prefix = preg_quote($prefix, '/'); - - $format = 0; - foreach ($options['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; - } - } - - $search = array(); - foreach ($keys as $key) { - $search[] = preg_quote($key, '/'); - } - $search = '/^' . $prefix . '(' . implode('|', $search) . ')$/'; - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = &$options; + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = & $normalizedOptions; - if (isset($options['callback'])) { - $callback = $options['callback']; - while (($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } + if (isset($normalizedOptions['callback'])) { + $callback = & $normalizedOptions['callback']; + while (($item = $this->fetch()) !== false) { + call_user_func($callback, $item); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return true; } /* find */ /** - * Find items. + * internal method to find items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see fetch() - * @see fetchAll() - * - * @triggers find.pre(PreEvent) - * @triggers find.post(PostEvent) - * @triggers find.exception(ExceptionEvent) + * @see fetch() + * @see fetchAll() */ - public function find($mode = self::MATCH_ACTIVE, array $options = array()) + protected function internalFind(& $normalizedMode, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); - } elseif (!$baseOptions->getReadable()) { - return false; } - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } + // This adapter doesn't support to read expired items + if (($normalizedMode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $search = '/^' . preg_quote($prefix, '/') . '+/'; - // This adapter doesn't support to read expired items - if (($mode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - $search = '/^' . preg_quote($prefix, '/') . '+/'; - - $format = 0; - foreach ($options['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; - } + $format = 0; + foreach ($normalizedOptions['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; } - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = &$options; } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = & $normalizedOptions; } + + return true; } /** - * Fetches the next item from result set + * Internal method to fetch the next item from result set * * @return array|boolean The next item or false - * @see fetchAll() - * - * @triggers fetch.pre(PreEvent) - * @triggers fetch.post(PostEvent) - * @triggers fetch.exception(ExceptionEvent) + * @throws Exception */ - public function fetch() + protected function internalFetch() { if (!$this->stmtActive) { return false; } - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $prefixL = strlen($this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator()); + $prefix = $this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $prefixL = strlen($prefix); - do { - if (!$this->stmtIterator->valid()) { - // clear stmt - $this->stmtActive = false; - $this->stmtIterator = null; - $this->stmtOptions = null; + do { + if (!$this->stmtIterator->valid()) { + // clear stmt + $this->stmtActive = false; + $this->stmtIterator = null; + $this->stmtOptions = null; - $result = false; - break; - } + return false; + } - // @see http://pecl.php.net/bugs/bug.php?id=22564 - $exist = apc_exists($this->stmtIterator->key()); - if ($exist) { - $result = $this->stmtIterator->current(); - $this->normalizeMetadata($result); - - $select = $this->stmtOptions['select']; - if (in_array('key', $select)) { - $internalKey = $this->stmtIterator->key(); - $result['key'] = substr($internalKey, $prefixL); - } + // @see http://pecl.php.net/bugs/bug.php?id=22564 + $exist = apc_exists($this->stmtIterator->key()); + if ($exist) { + $result = $this->stmtIterator->current(); + $this->normalizeMetadata($result); + + $select = $this->stmtOptions['select']; + if (in_array('key', $select)) { + $internalKey = $this->stmtIterator->key(); + $result['key'] = substr($internalKey, $prefixL); } + } - $this->stmtIterator->next(); - } while (!$exist); + $this->stmtIterator->next(); + } while (!$exist); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $result; } /* cleaning */ /** - * Clear items off all namespaces. + * Internal method to clear items off all namespaces. * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see clearByNamespace() - * - * @triggers clear.pre(PreEvent) - * @triggers clear.post(PostEvent) - * @triggers clear.exception(ExceptionEvent) + * @see clearByNamespace() */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->clearByRegEx('/.*/', $mode, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $this->clearByRegEx('/.*/', $normalizedMode, $normalizedOptions); } /** * Clear items by namespace. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use + * - tags + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean - * @throws Zend\Cache\Exception - * @see clear() - * - * @triggers clearByNamespace.pre(PreEvent) - * @triggers clearByNamespace.post(PostEvent) - * @triggers clearByNamespace.exception(ExceptionEvent) + * @throws Exception + * @see clear() */ - public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - $regex = '/^' . preg_quote($prefix, '/') . '+/'; - $result = $this->clearByRegEx($regex, $mode, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $regex = '/^' . preg_quote($prefix, '/') . '+/'; + return $this->clearByRegEx($regex, $normalizedMode, $normalizedOptions); } /* status */ /** - * Get capabilities + * Internal method to get capabilities of this adapter * * @return Capabilities - * - * @triggers getCapabilities.pre(PreEvent) - * @triggers getCapabilities.post(PostEvent) - * @triggers getCapabilities.exception(ExceptionEvent) */ - public function getCapabilities() + protected function internalGetCapabilities() { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array( - 'atime', - 'ctime', - 'internal_key', - 'mem_size', - 'mtime', - 'num_hits', - 'ref_count', - 'rtime', - 'ttl', - ), - 'maxTtl' => 0, - 'staticTtl' => true, - 'tagging' => false, - 'ttlPrecision' => 1, - 'useRequestTime' => (bool) ini_get('apc.use_request_time'), - 'expiredRead' => false, - 'maxKeyLength' => 5182, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - 'iterable' => true, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, - ) - ); - } - - return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array( + 'atime', + 'ctime', + 'internal_key', + 'mem_size', + 'mtime', + 'num_hits', + 'ref_count', + 'rtime', + 'ttl', + ), + 'maxTtl' => 0, + 'staticTtl' => true, + 'tagging' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => (bool) ini_get('apc.use_request_time'), + 'expiredRead' => false, + 'maxKeyLength' => 5182, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), + 'iterable' => true, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); } + + return $this->capabilities; } /** - * Get storage capacity. + * Internal method to get storage capacity. * - * @param array $options + * @param array $normalizedOptions * @return array|boolean Capacity as array or false on failure - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) + * @throws Exception */ - public function getCapacity(array $options = array()) + protected function internalGetCapacity(array & $normalizedOptions) { - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $mem = apc_sma_info(true); - $result = array( - 'free' => $mem['avail_mem'], - 'total' => $mem['num_seg'] * $mem['seg_size'], - ); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $mem = apc_sma_info(true); + return array( + 'free' => $mem['avail_mem'], + 'total' => $mem['num_seg'] * $mem['seg_size'], + ); } /* internal */ diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index cbbf7cb64..32ba9c966 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -328,6 +328,23 @@ public function getMetadata($key, array $options = array()) return parent::getMetadata($key, $options); } + /** + * Get metadatas + * + * @param array $keys + * @param array $options + * @return array + */ + public function getMetadatas(array $keys, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + clearstatcache(); + } + + return parent::getMetadatas($keys, $options); + } + /** * Get info by key * @@ -365,24 +382,178 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti return $keyInfo; } + /* writing */ + /** - * Get metadatas + * Store an item. * - * @param array $keys - * @param array $options - * @return array + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers setItem.pre(PreEvent) + * @triggers setItem.post(PostEvent) + * @triggers setItem.exception(ExceptionEvent) */ - public function getMetadatas(array $keys, array $options = array()) + public function setItem($key, $value, array $options = array()) { $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { clearstatcache(); } - return parent::getMetadatas($keys, $options); + return parent::setItem($key, $value, $options); } - /* writing */ + /** + * Store multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers setItems.pre(PreEvent) + * @triggers setItems.post(PostEvent) + * @triggers setItems.exception(ExceptionEvent) + */ + public function setItems(array $keyValuePairs, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); + } + + return parent::setItems($keyValuePairs, $options); + } + + /** + * Add an item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers addItem.pre(PreEvent) + * @triggers addItem.post(PostEvent) + * @triggers addItem.exception(ExceptionEvent) + */ + public function addItem($key, $value, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); + } + + return parent::addItem($key, $value, $options); + } + + /** + * Add multiple items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers addItems.pre(PreEvent) + * @triggers addItems.post(PostEvent) + * @triggers addItems.exception(ExceptionEvent) + */ + public function addItems(array $keyValuePairs, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); + } + + return parent::addItems($keyValuePairs, $options); + } + + /** + * Replace an existing item. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers replaceItem.pre(PreEvent) + * @triggers replaceItem.post(PostEvent) + * @triggers replaceItem.exception(ExceptionEvent) + */ + public function replaceItem($key, $value, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); + } + + return parent::replaceItem($key, $value, $options); + } + + /** + * Replace multiple existing items. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param array $keyValuePairs + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers replaceItems.pre(PreEvent) + * @triggers replaceItems.post(PostEvent) + * @triggers replaceItems.exception(ExceptionEvent) + */ + public function replaceItems(array $keyValuePairs, array $options = array()) + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); + } + + return parent::replaceItems($keyValuePairs, $options); + } /** * Internal method to store an item. @@ -390,6 +561,8 @@ public function getMetadatas(array $keys, array $options = array()) * Options: * - namespace * - The namespace to use + * - tags + * - An array of tags * * @param string $normalizedKey * @param mixed $value @@ -471,731 +644,451 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz } /** - * Replace an item + * Set an item only if token matches * - * @param $key - * @param $value - * @param array $options - * @return bool|mixed - * @throws ItemNotFoundException + * It uses the token received from getItem() to check if the item has + * changed before overwriting it. + * + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - tags optional + * - An array of tags + * + * @param mixed $token + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean + * @throws Exception + * @see getItem() + * @see setItem() */ - public function replaceItem($key, $value, array $options = array()) + public function checkAndSetItem($token, $key, $value, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - if ( !$this->internalHasItem($key, $options) ) { - throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); - } - - $result = $this->internalSetItem($key, $value, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::checkAndSetItem($token, $key, $value, $options); } /** - * Replace items + * Internal method to set an item only if token matches * - * @param array $keyValuePairs - * @param array $options - * @return bool|mixed - * @throws ItemNotFoundException + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param mixed $token + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see getItem() + * @see setItem() */ - public function replaceItems(array $keyValuePairs, array $options = array()) + protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { + $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); + if (!$keyInfo) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found within namespace '{$normalizedOptions['namespace']}'" + ); + } return false; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = true; - foreach ($keyValuePairs as $key => $value) { - if ( !$this->internalHasItem($key, $options) ) { - throw new Exception\ItemNotFoundException("Key '{$key}' doesn't exist"); - } - $result = $this->internalSetItem($key, $value, $options) && $result; - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + // use filemtime + filesize as CAS token + $check = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); + if ($token !== $check) { + return false; } + + return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); } /** - * Add an item + * Reset lifetime of an item * - * @param $key - * @param $value - * @param array $options - * @return bool|mixed - * @throws RuntimeException + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers touchItem.pre(PreEvent) + * @triggers touchItem.post(PostEvent) + * @triggers touchItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + public function touchItem($key, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - if ( $this->internalHasItem($key, $options) ) { - throw new Exception\RuntimeException("Key '{$key}' already exist"); - } - - $result = $this->internalSetItem($key, $value, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::touchItem($key, $options); } /** - * Add items + * Reset lifetime of multiple items. * - * @param array $keyValuePairs - * @param array $options - * @return bool|mixed - * @throws RuntimeException + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers touchItems.pre(PreEvent) + * @triggers touchItems.post(PostEvent) + * @triggers touchItems.exception(ExceptionEvent) */ - public function addItems(array $keyValuePairs, array $options = array()) + public function touchItems(array $keys, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - $result = true; - foreach ($keyValuePairs as $key => $value) { - if ( $this->internalHasItem($key, $options) ) { - throw new Exception\RuntimeException("Key '{$key}' already exist"); - } - - $result = $this->internalSetItem($key, $value, $options) && $result; - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::touchItems($keys, $options); } /** - * check and set item + * Internal method to reset lifetime of an item * - * @param string $token - * @param string $key - * @param mixed $value - * @param array $options - * @return bool|mixed - * @throws ItemNotFoundException - */ - public function checkAndSetItem($token, $key, $value, array $options = array()) - { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'token' => & $token, - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - if ( !($keyInfo = $this->getKeyInfo($key, $options['namespace'])) ) { - if ($options['ignore_missing_items']) { - $result = false; - } else { - throw new Exception\ItemNotFoundException("Key '{$key}' not found within namespace '{$options['namespace']}'"); - } - } else { - // use filemtime + filesize as CAS token - $check = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); - if ($token != $check) { - $result = false; - } else { - $result = $this->internalSetItem($key, $value, $options); - } - } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } - } - - /** - * Touch an item + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param $key - * @param array $options - * @return bool|mixed + * @param string $key + * @param array $options + * @return boolean + * @throws Exception */ - public function touchItem($key, array $options = array()) + protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { + $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); + if (!$keyInfo) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found within namespace '{$normalizedOptions['namespace']}'" + ); + } return false; } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } + ErrorHandler::start(); + $touch = touch($keyInfo['filespec'] . '.dat'); + $error = ErrorHandler::stop(); + if (!$touch) { + throw new Exception\RuntimeException( + "Error touching file '{$keyInfo['filespec']}.dat'", 0, $error + ); + } - $this->internalTouchItem($key, $options); - $this->lastInfoId = null; + // remove the buffered info + $this->lastInfoId = null; - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Touch items + * Remove an item. * - * @param array $keys - * @param array $options - * @return bool|mixed + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item + * + * @param string $key + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers removeItem.pre(PreEvent) + * @triggers removeItem.post(PostEvent) + * @triggers removeItem.exception(ExceptionEvent) */ - public function touchItems(array $keys, array $options = array()) + public function removeItem($key, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - foreach ($keys as $key) { - $this->internalTouchItem($key, $options); - } - $this->lastInfoId = null; - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::removeItem($key, $options); } /** - * Remove an item + * Remove multiple items. * - * @param $key - * @param array $options - * @return bool|mixed + * Options: + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - ignore_missing_items optional + * - Throw exception on missing item + * + * @param array $keys + * @param array $options + * @return boolean + * @throws Exception + * + * @triggers removeItems.pre(PreEvent) + * @triggers removeItems.post(PostEvent) + * @triggers removeItems.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + public function removeItems(array $keys, array $options = array()) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + clearstatcache(); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - // unlink is not affected by clearstatcache - $this->internalRemoveItem($key, $options); - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return parent::removeItems($keys, $options); } /** - * Remove items + * Internal method to remove an item. * - * @param array $keys - * @param array $options - * @return bool|mixed + * Options: + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return boolean + * @throws Exception */ - public function removeItems(array $keys, array $options = array()) + protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - // unlink is not affected by clearstatcache - foreach ($keys as $key) { - $this->internalRemoveItem($key, $options); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions['namespace']); + if (!file_exists($filespec . '.dat')) { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$normalizedKey}' with file '{$filespec}.dat' not found"); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + } else { + $this->unlink($filespec . '.dat'); + $this->unlink($filespec . '.ifo'); + $this->lastInfoId = null; } + return true; } /* non-blocking */ /** - * Find + * internal method to find items. * - * @param int $mode - * @param array $options - * @return bool|mixed - * @throws RuntimeException + * Options: + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use + * + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see fetch() + * @see fetchAll() */ - public function find($mode = self::MATCH_ACTIVE, array $options = array()) + protected function internalFind(& $normalizedMode, array & $normalizedOptions) { if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); } - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - $options = array_merge($baseOptions->toArray(), $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - try { - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - $find = $options['cache_dir'] - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options['dir_level']) - . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new GlobIterator($find); - - $this->stmtActive = true; - $this->stmtGlob = $glob; - $this->stmtMatch = $mode; - $this->stmtOptions = $options; - } catch (BaseException $e) { - throw new Exception\RuntimeException('Instantiating glob iterator failed', 0, $e); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $baseOptions = $this->getOptions(); + + $prefix = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator(); + $find = $baseOptions->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $baseOptions->getDirLevel()) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = new GlobIterator($find); + + $this->stmtActive = true; + $this->stmtGlob = $glob; + $this->stmtMatch = $normalizedMode; + $this->stmtOptions = $normalizedOptions; + } catch (BaseException $e) { + throw new Exception\RuntimeException("new GlobIterator({$find}) failed", 0, $e); } + + return true; } /** - * Fetch + * Internal method to fetch the next item from result set * - * @return bool|mixed + * @return array|boolean The next item or false + * @throws Exception */ - public function fetch() + protected function internalFetch() { if (!$this->stmtActive) { return false; } - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($this->stmtGlob !== null) { - $result = $this->fetchByGlob(); + if ($this->stmtGlob !== null) { + $result = $this->fetchByGlob(); - if ($result === false) { - // clear statement - $this->stmtActive = false; - $this->stmtGlob = null; - $this->stmtMatch = null; - $this->stmtOptions = null; - } - } else { - $result = parent::fetch(); + if ($result === false) { + // clear statement + $this->stmtActive = false; + $this->stmtGlob = null; + $this->stmtMatch = null; + $this->stmtOptions = null; } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + } else { + $result = parent::internalFetch(); } + + return $result; } /* cleaning */ /** - * Clear + * Internal method to clear items off all namespaces. * - * @param int $mode - * @param array $options - * @return mixed + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see clearByNamespace() */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->clearByPrefix('', $mode, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $this->clearByPrefix('', $normalizedMode, $normalizedOptions); } /** - * Clear by namespace + * Clear items by namespace. * - * @param int $mode - * @param array $options - * @return mixed + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* + * + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see clear() */ - public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) { - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $prefix = $options['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $result = $this->clearByPrefix($prefix, $mode, $options); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + return $this->clearByPrefix($prefix, $normalizedMode, $normalizedOptions); } /** - * Optimize + * Internal method to optimize adapter storage. * - * @param array $options - * @return bool|mixed + * Options: + * - namespace + * - The namespace to use + * + * @param array $normalizedOptions + * @return boolean + * @throws Exception */ - public function optimize(array $options = array()) + protected function internalOptimize(array & $normalizedOptions) { $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if ($baseOptions->getDirLevel()) { + // removes only empty directories + $this->rmDir( + $baseOptions->getCacheDir(), + $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator() + ); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($baseOptions->getDirLevel()) { - // removes only empty directories - $this->rmDir( - $baseOptions->getCacheDir(), - $options['namespace'] . $baseOptions->getNamespaceSeparator() - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /* status */ /** - * Get capabilities + * Internal method to get capabilities of this adapter * - * @return mixed + * @return Capabilities */ - public function getCapabilities() + protected function internalGetCapabilities() { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => 'string', - 'boolean' => 'string', - 'integer' => 'string', - 'double' => 'string', - 'string' => true, - 'array' => false, - 'object' => false, - 'resource' => false, - ), - 'supportedMetadata' => array('mtime', 'filespec'), - 'maxTtl' => 0, - 'staticTtl' => false, - 'tagging' => true, - 'ttlPrecision' => 1, - 'expiredRead' => true, - 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - 'iterable' => true, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, - ) - ); - - // set dynamic capibilities - $this->updateCapabilities(); - } + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => 'string', + 'boolean' => 'string', + 'integer' => 'string', + 'double' => 'string', + 'string' => true, + 'array' => false, + 'object' => false, + 'resource' => false, + ), + 'supportedMetadata' => array('mtime', 'filespec'), + 'maxTtl' => 0, + 'staticTtl' => false, + 'tagging' => true, + 'ttlPrecision' => 1, + 'expiredRead' => true, + 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), + 'iterable' => true, + 'clearAllNamespaces' => true, + 'clearByNamespace' => true, + ) + ); - $result = $this->capabilities; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + // set dynamic capibilities + $this->updateCapabilities(); } - } - /** - * Get capacity - * - * @param array $options - * @return mixed - */ - public function getCapacity(array $options = array()) - { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = Utils::getDiskCapacity($this->getOptions()->getCacheDir()); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $this->capabilities; } - /* internal */ - /** - * Remove a key + * Internal method to get storage capacity. * - * @param $key - * @param array $options - * @throws ItemNotFoundException + * @param array $normalizedOptions + * @return array|boolean Capacity as array or false on failure + * @throws Exception */ - protected function internalRemoveItem($key, array &$options) + protected function internalGetCapacity(array & $normalizedOptions) { - $filespec = $this->getFileSpec($key, $options['namespace']); - - if (!$options['ignore_missing_items'] && !file_exists($filespec . '.dat')) { - throw new Exception\ItemNotFoundException("Key '{$key}' with file '{$filespec}.dat' not found"); - } - - $this->unlink($filespec . '.dat'); - $this->unlink($filespec . '.ifo'); - $this->lastInfoId = null; + return Utils::getDiskCapacity($this->getOptions()->getCacheDir()); } - /** - * Touch a key - * - * @param string $key - * @param array $options - * @return bool - * @throws ItemNotFoundException|RuntimeException - */ - protected function internalTouchItem($key, array &$options) - { - $keyInfo = $this->getKeyInfo($key, $options['namespace']); - if (!$keyInfo) { - if ($options['ignore_missing_items']) { - return false; - } else { - throw new Exception\ItemNotFoundException( - "Key '{$key}' not found within namespace '{$options['namespace']}'" - ); - } - } - - ErrorHandler::start(); - $touch = touch($keyInfo['filespec'] . '.dat'); - $error = ErrorHandler::stop(); - if (!$touch) { - throw new Exception\RuntimeException( - "Error touching file '{$keyInfo['filespec']}.dat'", 0, $error - ); - } - } + /* internal */ /** * Fetch by glob diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 53d458ac1..e833f2f16 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -344,565 +344,358 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * Add an item. * * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers addItem.pre(PreEvent) - * @triggers addItem.post(PostEvent) - * @triggers addItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->add($key, $value, $expiration)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $expiration = $this->expirationTime($normalizedOptions['ttl']); + if (!$this->memcached->add($normalizedKey, $value, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + + return true; } /** - * Replace an item. + * Internal method to replace an existing item. * * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers replaceItem.pre(PreEvent) - * @triggers replaceItem.post(PostEvent) - * @triggers replaceItem.exception(ExceptionEvent) */ - public function replaceItem($key, $value, array $options = array()) + protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->replace($key, $value, $expiration)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $expiration = $this->expirationTime($normalizedOptions['ttl']); + if (!$this->memcached->replace($normalizedKey, $value, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + + return true; } /** - * Check and set item + * Internal method to set an item only if token matches + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - An array of tags * - * @param float $token - * @param string $key + * @param mixed $token + * @param string $normalizedKey * @param mixed $value - * @param array $options - * @return bool + * @param array $normalizedOptions + * @return boolean + * @throws Exception + * @see getItem() + * @see setItem() */ - public function checkAndSetItem($token, $key, $value, array $options = array()) + protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'token' => & $token, - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $expiration = $this->expirationTime($options['ttl']); - $result = $this->memcached->cas($token, $key, $value, $expiration); + $expiration = $this->expirationTime($normalizedOptions['ttl']); + $result = $this->memcached->cas($token, $normalizedKey, $value, $expiration); - if ($result === false) { - $rsCode = $this->memcached->getResultCode(); - if ($rsCode !== 0 && $rsCode != MemcachedResource::RES_DATA_EXISTS) { - throw $this->getExceptionByResultCode($rsCode); - } + if ($result === false) { + $rsCode = $this->memcached->getResultCode(); + if ($rsCode !== 0 && $rsCode != MemcachedResource::RES_DATA_EXISTS) { + throw $this->getExceptionByResultCode($rsCode); } + } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return $result; } /** - * Remove an item. + * Internal method to remove an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - $result = $this->memcached->delete($key); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); + $result = $this->memcached->delete($normalizedKey); - if ($result === false) { - if (($rsCode = $this->memcached->getResultCode()) != 0 - && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) - ) { - throw $this->getExceptionByResultCode($rsCode); - } + if ($result === false) { + $rsCode = $this->memcached->getResultCode(); + if ($rsCode != 0 && ($rsCode != MemcachedResource::RES_NOTFOUND || !$normalizedOptions['ignore_missing_items'])) { + throw $this->getExceptionByResultCode($rsCode); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return true; } /** - * Remove items. + * Internal method to remove multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * * @param array $keys * @param array $options * @return boolean * @throws Exception - * - * @triggers removeItems.pre(PreEvent) - * @triggers removeItems.post(PostEvent) - * @triggers removeItems.exception(ExceptionEvent) */ - public function removeItems(array $keys, array $options = array()) + protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + // support for removing multiple items at once has been added in ext/memcached 2 + if (static::$extMemcachedMajorVersion < 2) { + return parent::internalRemoveItems($normalizedKeys, $normalizedOptions); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $rsCodes = array(); - if (static::$extMemcachedMajorVersion >= 2) { - $rsCodes = $this->memcached->deleteMulti($keys); - } else { - foreach ($keys as $key) { - $rs = $this->memcached->delete($key); - if ($rs === false) { - $rsCodes[$key] = $this->memcached->getResultCode(); - } - } - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); + $rsCodes = $this->memcached->deleteMulti($normalizedKeys); - $missingKeys = null; - foreach ($rsCodes as $key => $rsCode) { - if ($rsCode !== true && $rsCode != 0) { - if ($rsCode != MemcachedResource::RES_NOTFOUND) { - throw $this->getExceptionByResultCode($rsCode); - } elseif (!$options['ignore_missing_items']) { - $missingKeys[] = $key; - } + $missingKeys = null; + foreach ($rsCodes as $key => $rsCode) { + if ($rsCode !== true && $rsCode != 0) { + if ($rsCode != MemcachedResource::RES_NOTFOUND) { + throw $this->getExceptionByResultCode($rsCode); } + $missingKeys[] = $key; } - if ($missingKeys) { - throw new Exception\ItemNotFoundException( - "Keys '" . implode("','", $missingKeys) . "' not found" - ); - } + } - return true; - } catch (MemcachedException $e) { - throw new RuntimeException($e->getMessage(), 0, $e); + if ($missingKeys && !$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Keys '" . implode("','", $missingKeys) . "' not found within namespace '{$normalizedOptions['namespace']}'" + ); } + + return true; } /** - * Increment an item. + * Internal method to increment an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers incrementItem.pre(PreEvent) - * @triggers incrementItem.post(PostEvent) - * @triggers incrementItem.exception(ExceptionEvent) */ - public function incrementItem($key, $value, array $options = array()) + protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $value = (int)$value; - $newValue = $this->memcached->increment($key, $value); - - if ($newValue === false) { - if (($rsCode = $this->memcached->getResultCode()) != 0 - && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) - ) { - throw $this->getExceptionByResultCode($rsCode); - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->add($key, $value, $expiration)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } + $value = (int)$value; + $newValue = $this->memcached->increment($normalizedKey, $value); - $newValue = $value; + if ($newValue === false) { + $rsCode = $this->memcached->getResultCode(); + if ($rsCode != 0 && ($rsCode != MemcachedResource::RES_NOTFOUND || !$normalizedOptions['ignore_missing_items'])) { + throw $this->getExceptionByResultCode($rsCode); } - return $this->triggerPost(__FUNCTION__, $args, $newValue); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $newValue = $value; + $expiration = $this->expirationTime($normalizedOptions['ttl']); + if (!$this->memcached->add($normalizedKey, $newValue, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } } + + return $newValue; } /** - * Decrement an item. + * Internal method to decrement an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value or false or failure + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers decrementItem.pre(PreEvent) - * @triggers decrementItem.post(PostEvent) - * @triggers decrementItem.exception(ExceptionEvent) */ - public function decrementItem($key, $value, array $options = array()) + protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - $value = (int)$value; - $newValue = $this->memcached->decrement($key, $value); + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - if ($newValue === false) { - if (($rsCode = $this->memcached->getResultCode()) != 0 - && ($rsCode != MemcachedResource::RES_NOTFOUND || !$options['ignore_missing_items']) - ) { - throw $this->getExceptionByResultCode($rsCode); - } + $value = (int)$value; + $newValue = $this->memcached->decrement($normalizedKey, $value); - $expiration = $this->expirationTime($options['ttl']); - if (!$this->memcached->add($key, -$value, $expiration)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - $newValue = -$value; + if ($newValue === false) { + $rsCode = $this->memcached->getResultCode(); + if ($rsCode != 0 && ($rsCode != MemcachedResource::RES_NOTFOUND || !$normalizedOptions['ignore_missing_items'])) { + throw $this->getExceptionByResultCode($rsCode); } - return $this->triggerPost(__FUNCTION__, $args, $newValue); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $newValue = -$value; + $expiration = $this->expirationTime($normalizedOptions['ttl']); + if (!$this->memcached->add($normalizedKey, $newValue, $expiration)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } } + + return $newValue; } /* non-blocking */ /** - * Get items that were marked to delay storage for purposes of removing blocking + * Internal method to request multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - select optional + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use + * - select * - An array of the information the returned item contains - * (Default: array('key', 'value')) * - callback optional * - An result callback will be invoked for each item in the result set. * - The first argument will be the item array. * - The callback does not have to return anything. * - * @param array $keys - * @param array $options - * @return bool + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return boolean * @throws Exception - * - * @triggers getDelayed.pre(PreEvent) - * @triggers getDelayed.post(PostEvent) - * @triggers getDelayed.exception(ExceptionEvent) + * @see fetch() + * @see fetchAll() */ - public function getDelayed(array $keys, array $options = array()) + protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); - } elseif (!$baseOptions->getReadable()) { - return false; - } elseif (!$keys) { - return true; } - $this->normalizeOptions($options); - if (isset($options['callback']) && !is_callable($options['callback'], false)) { + if (isset($normalizedOptions['callback']) && !is_callable($normalizedOptions['callback'], false)) { throw new Exception\InvalidArgumentException('Invalid callback'); } - if (!isset($options['select'])) { - $options['select'] = array('key', 'value'); - } - - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); - - // redirect callback - if (isset($options['callback'])) { - $cb = function (MemcachedResource $memc, array &$item) use (&$options, $baseOptions) { - $select = & $options['select']; - // handle selected key - if (!in_array('key', $select)) { - unset($item['key']); - } - - // handle selected value - if (!in_array('value', $select)) { - unset($item['value']); - } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - call_user_func($options['callback'], $item); - }; + // redirect callback + if (isset($normalizedOptions['callback'])) { + $cb = function (MemcachedResource $memc, array & $item) use (& $normalizedOptions) { + $select = & $normalizedOptions['select']; - if (!$this->memcached->getDelayed($keys, false, $cb)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + // handle selected key + if (!in_array('key', $select)) { + unset($item['key']); } - } else { - if (!$this->memcached->getDelayed($keys)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + + // handle selected value + if (!in_array('value', $select)) { + unset($item['value']); } - $this->stmtActive = true; - $this->stmtOptions = &$options; + call_user_func($normalizedOptions['callback'], $item); + }; + + if (!$this->memcached->getDelayed($normalizedKeys, false, $cb)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } + } else { + if (!$this->memcached->getDelayed($normalizedKeys)) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $this->stmtActive = true; + $this->stmtOptions = & $normalizedOptions; } + + return true; } /** - * Fetches the next item from result set + * Internal method to fetch the next item from result set * * @return array|boolean The next item or false - * @see fetchAll() - * - * @triggers fetch.pre(PreEvent) - * @triggers fetch.post(PostEvent) - * @triggers fetch.exception(ExceptionEvent) + * @throws Exception */ - public function fetch() + protected function internalFetch() { if (!$this->stmtActive) { return false; } - $args = new ArrayObject(); + $result = $this->memcached->fetch(); + if (!empty($result)) { + $select = & $this->stmtOptions['select']; - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + // handle selected key + if (!in_array('key', $select)) { + unset($result['key']); } - $result = $this->memcached->fetch(); - if (!empty($result)) { - $select = & $this->stmtOptions['select']; - - // handle selected key - if (!in_array('key', $select)) { - unset($result['key']); - } - - // handle selected value - if (!in_array('value', $select)) { - unset($result['value']); - } - - } else { - // clear stmt - $this->stmtActive = false; - $this->stmtOptions = null; + // handle selected value + if (!in_array('value', $select)) { + unset($result['value']); } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + } else { + // clear stmt + $this->stmtActive = false; + $this->stmtOptions = null; } + + return $result; } /** - * FetchAll + * Internal method to return all items of result set. * + * @return array The result set as array containing all items * @throws Exception - * @return array + * @see fetch() */ - public function fetchAll() + protected function internalFetchAll() { $result = $this->memcached->fetchAll(); if ($result === false) { @@ -910,8 +703,7 @@ public function fetchAll() } $select = $this->stmtOptions['select']; - - foreach ($result as &$elem) { + foreach ($result as & $elem) { if (!in_array('key', $select)) { unset($elem['key']); } @@ -923,145 +715,85 @@ public function fetchAll() /* cleaning */ /** - * Clear items off all namespaces. + * Internal method to clear items off all namespaces. * - * Options: - * - No options available for this adapter - * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see clearByNamespace() - * - * @triggers clear.pre(PreEvent) - * @triggers clear.post(PostEvent) - * @triggers clear.exception(ExceptionEvent) + * @see clearByNamespace() */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; + if (!$this->memcached->flush()) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$this->memcached->flush()) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /* status */ /** - * Get capabilities + * Internal method to get capabilities of this adapter * * @return Capabilities - * - * @triggers getCapabilities.pre(PreEvent) - * @triggers getCapabilities.post(PostEvent) - * @triggers getCapabilities.exception(ExceptionEvent) */ - public function getCapabilities() + protected function internalGetCapabilities() { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array(), - 'maxTtl' => 0, - 'staticTtl' => true, - 'tagging' => false, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'maxKeyLength' => 255, - 'namespaceIsPrefix' => true, - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => false, - ) - ); - } - - return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array(), + 'maxTtl' => 0, + 'staticTtl' => true, + 'tagging' => false, + 'ttlPrecision' => 1, + 'useRequestTime' => false, + 'expiredRead' => false, + 'maxKeyLength' => 255, + 'namespaceIsPrefix' => true, + 'iterable' => false, + 'clearAllNamespaces' => true, + 'clearByNamespace' => false, + ) + ); } + + return $this->capabilities; } /** - * Get storage capacity. + * Internal method to get storage capacity. * - * @param array $options + * @param array $normalizedOptions * @return array|boolean Capacity as array or false on failure - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) + * @throws Exception */ - public function getCapacity(array $options = array()) + protected function internalGetCapacity(array & $normalizedOptions) { - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $stats = $this->memcached->getStats(); - if ($stats === false) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - $mem = array_pop($stats); - $result = array( - 'free' => $mem['limit_maxbytes'] - $mem['bytes'], - 'total' => $mem['limit_maxbytes'], - ); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $stats = $this->memcached->getStats(); + if ($stats === false) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } + + $mem = array_pop($stats); + return array( + 'free' => $mem['limit_maxbytes'] - $mem['bytes'], + 'total' => $mem['limit_maxbytes'], + ); } /* internal */ diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 7a93a840a..944c7930d 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -277,6 +277,8 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti * Options: * - namespace * - The namespace to use + * - tags + * - An array of tags * * @param string $normalizedKey * @param mixed $value @@ -303,10 +305,10 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz * Internal method to store multiple items. * * Options: - * - ttl - * - The time-to-life * - namespace * - The namespace to use + * - tags + * - An array of tags * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions @@ -339,9 +341,9 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * Add an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional + * - namespace + * - The namespace to use + * - tags * - An array of tags * * @param string $key @@ -349,870 +351,473 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * @param array $options * @return boolean * @throws Exception - * - * @triggers addItem.pre(PreEvent) - * @triggers addItem.post(PostEvent) - * @triggers addItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if (!$this->hasFreeCapacity()) { + $memoryLimit = $this->getOptions()->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$this->hasFreeCapacity()) { - $memoryLimit = $baseOptions->getMemoryLimit(); - throw new Exception\OutOfCapacityException( - 'Memory usage exceeds limit ({$memoryLimit}).' - ); - } - - $ns = $options['namespace']; - if (isset($this->data[$ns][$key])) { - throw new Exception\RuntimeException("Key '{$key}' already exists within namespace '$ns'"); - } - $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $ns = $normalizedOptions['namespace']; + if (isset($this->data[$ns][$normalizedKey])) { + throw new Exception\RuntimeException("Key '{$normalizedKey}' already exists within namespace '$ns'"); } + $this->data[$ns][$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); + + return true; } /** - * Add multiple items. + * Internal method to add multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional + * - namespace + * - The namespace to use + * - tags * - An array of tags * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers addItems.pre(PreEvent) - * @triggers addItems.post(PostEvent) - * @triggers addItems.exception(ExceptionEvent) */ - public function addItems(array $keyValuePairs, array $options = array()) + protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + if (!$this->hasFreeCapacity()) { + $memoryLimit = $this->getOptions()->getMemoryLimit(); + throw new Exception\OutOfCapacityException( + 'Memory usage exceeds limit ({$memoryLimit}).' + ); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$this->hasFreeCapacity()) { - $memoryLimit = $baseOptions->getMemoryLimit(); - throw new Exception\OutOfCapacityException( - 'Memory usage exceeds limit ({$memoryLimit}).' - ); - } - - $ns = $options['namespace']; - if (!isset($this->data[$ns])) { - $this->data[$ns] = array(); - } + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns])) { + $this->data[$ns] = array(); + } - $data = & $this->data[$ns]; - foreach ($keyValuePairs as $key => $value) { - if (isset($data[$key])) { - throw new Exception\RuntimeException("Key '{$key}' already exists within namespace '$ns'"); - } - $data[$key] = array($value, microtime(true), $options['tags']); + $data = & $this->data[$ns]; + $now = microtime(true); + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + if (isset($data[$normalizedKey])) { + throw new Exception\RuntimeException("Key '{$normalizedKey}' already exists within namespace '{$ns}'"); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $data[$normalizedKey] = array($value, $now, $normalizedOptions['tags']); } + + return true; } /** - * Replace an item. + * Internal method to replace an existing item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags * - An array of tags * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers replaceItem.pre(PreEvent) - * @triggers replaceItem.post(PostEvent) - * @triggers replaceItem.exception(ExceptionEvent) */ - public function replaceItem($key, $value, array $options = array()) + protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns][$normalizedKey])) { + throw new Exception\ItemNotFoundException("Key '{$normalizedKey}' doesn't exist within namespace '{$ns}'"); } + $this->data[$ns][$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if (!isset($this->data[$ns][$key])) { - throw new Exception\ItemNotFoundException("Key '{$key}' doen't exists within namespace '$ns'"); - } - $this->data[$ns][$key] = array($value, microtime(true), $options['tags']); - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Replace multiple items. + * Internal method to replace multiple existing items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags * - An array of tags * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers replaceItems.pre(PreEvent) - * @triggers replaceItems.post(PostEvent) - * @triggers replaceItems.exception(ExceptionEvent) */ - public function replaceItems(array $keyValuePairs, array $options = array()) + protected function internalReplaceItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $ns = $normalizedOptions['namespace']; + if (!isset($this->data[$ns])) { + throw new Exception\ItemNotFoundException("Namespace '$ns' doesn't exist"); } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if (!isset($this->data[$ns])) { - throw new Exception\ItemNotFoundException("Namespace '$ns' doesn't exist"); - } - - $data = & $this->data[$ns]; - foreach ($keyValuePairs as $key => $value) { - if (!isset($data[$key])) { - throw new Exception\ItemNotFoundException( - "Key '{$key}' doen't exists within namespace '$ns'" - ); - } - $data[$key] = array($value, microtime(true), $options['tags']); + $data = & $this->data[$ns]; + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + if (!isset($data[$normalizedKey])) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' doesn't exist within namespace '{$ns}'" + ); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } - } - - /** - * Reset lifetime of an item - * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param string $key - * @param array $options - * @return boolean - * @throws Exception - * - * @triggers touchItem.pre(PreEvent) - * @triggers touchItem.post(PostEvent) - * @triggers touchItem.exception(ExceptionEvent) - */ - public function touchItem($key, array $options = array()) - { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $data[$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if (isset($this->data[$ns][$key])) { - // update mtime - $this->data[$ns][$key][1] = microtime(true); - } else { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$key}' not found within namespace '{$ns}'" - ); - } - - // add an empty item - $this->data[$ns][$key] = array('', microtime(true), null); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Remove an item. + * Internal method to reset lifetime of an item * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if (isset($this->data[$ns][$key])) { - unset($this->data[$ns][$key]); - - // remove empty namespace - if (!$this->data[$ns]) { - unset($this->data[$ns]); - } - - } else { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$key}' not found on namespace '{$ns}'"); - } + $ns = $normalizedOptions['namespace']; + if (isset($this->data[$ns][$normalizedKey])) { + // update mtime + $this->data[$ns][$normalizedKey][1] = microtime(true); + } else { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found within namespace '{$ns}'" + ); } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + // add an empty item + $this->data[$ns][$normalizedKey] = array('', microtime(true), null); } + + return true; } /** - * Remove multiple items. + * Internal method to remove an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param array $keys - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers removeItems.pre(PreEvent) - * @triggers removeItems.post(PostEvent) - * @triggers removeItems.exception(ExceptionEvent) */ - public function removeItems(array $keys, array $options = array()) + protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - if ($options['ignore_missing_items'] === false) { - if (!isset($this->data[$ns])) { - throw new Exception\ItemNotFoundException("Namespace '{$ns}' is empty"); - } - - $data = &$this->data[$ns]; - - $missingItems = null; - foreach ($keys as $key) { - if (isset($data[$key])) { - unset($data[$key]); - } else { - $missingItems[] = $key; - } - } - - if ($missingItems) { - throw new Exception\ItemNotFoundException( - "Keys '" . implode("','", $missingItems) . "' not found on namespace '{$ns}'" - ); - } - } elseif (isset($this->data[$ns])) { - $data = & $this->data[$ns]; - foreach ($keys as $key) { - unset($data[$key]); - } + $ns = $normalizedOptions['namespace']; + if (isset($this->data[$ns][$normalizedKey])) { + unset($this->data[$ns][$normalizedKey]); - // remove empty namespace - if (!$data) { - unset($this->data[$ns]); - } + // remove empty namespace + if (!$this->data[$ns]) { + unset($this->data[$ns]); } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + } elseif (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$normalizedKey}' not found on namespace '{$ns}'"); } + + return true; } /** - * Increment an item. + * Internal method to increment an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value of false on failure + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers incrementItem.pre(PreEvent) - * @triggers incrementItem.post(PostEvent) - * @triggers incrementItem.exception(ExceptionEvent) */ - public function incrementItem($key, $value, array $options = array()) + protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $value = (int) $value; - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - $data = & $this->data[$ns]; - if (isset($data[$key])) { - $data[$key][0]+= $value; - $data[$key][1] = microtime(true); - $result = $data[$key][0]; - } else { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$key}' not found within namespace '{$ns}'" - ); - } - - // add a new item - $data[$key] = array($value, microtime(true), null); - $result = $value; + $ns = $normalizedOptions['namespace']; + $data = & $this->data[$ns]; + if (isset($data[$normalizedKey])) { + $data[$normalizedKey][0]+= $value; + $data[$normalizedKey][1] = microtime(true); + $newValue = $data[$normalizedKey][0]; + } else { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found within namespace '{$ns}'" + ); } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + // add a new item + $newValue = $value; + $data[$normalizedKey] = array($newValue, microtime(true), null); } + + return $newValue; } /** - * Decrement an item. + * Internal method to decrement an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value or false or failure + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers decrementItem.pre(PreEvent) - * @triggers decrementItem.post(PostEvent) - * @triggers decrementItem.exception(ExceptionEvent) */ - public function decrementItem($key, $value, array $options = array()) + protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $value = (int) $value; - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $ns = $options['namespace']; - $data = & $this->data[$ns]; - if (isset($data[$key])) { - $data[$key][0]-= $value; - $data[$key][1] = microtime(true); - $result = $data[$key][0]; - } else { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$key}' not found within namespace '{$ns}'" - ); - } - - // add a new item - $data[$key] = array(-$value, microtime(true), null); - $result = -$value; + $ns = $normalizedOptions['namespace']; + $data = & $this->data[$ns]; + if (isset($data[$normalizedKey])) { + $data[$normalizedKey][0]-= $value; + $data[$normalizedKey][1] = microtime(true); + $newValue = $data[$normalizedKey][0]; + } else { + if (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$normalizedKey}' not found within namespace '{$ns}'" + ); } - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + // add a new item + $newValue = -$value; + $data[$normalizedKey] = array($newValue, microtime(true), null); } + + return $newValue; } /* find */ /** - * Find items. + * internal method to find items. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional + * - ttl + * - The time-to-live + * - namespace + * - The namespace to use + * - tags * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * Adapter::MATCH_TAGS_* * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see fetch() - * @see fetchAll() - * - * @triggers find.pre(PreEvent) - * @triggers find.post(PostEvent) - * @triggers find.exception(ExceptionEvent) + * @see fetch() + * @see fetchAll() */ - public function find($mode = self::MATCH_ACTIVE, array $options=array()) + protected function internalFind(& $normalizedMode, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getReadable()) { - return false; - } - if ($this->stmtActive) { throw new Exception\RuntimeException('Statement already in use'); } - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $tags = & $options['tags']; - $emptyTags = $keys = array(); - foreach ($this->data[ $options['namespace'] ] as $key => &$item) { + $tags = & $normalizedOptions['tags']; + $emptyTags = $keys = array(); + foreach ($this->data[ $normalizedOptions['namespace'] ] as $key => &$item) { - // compare expired / active - if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { + // compare expired / active + if (($normalizedMode & self::MATCH_ALL) != self::MATCH_ALL) { - // if MATCH_EXPIRED -> filter active items - if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($this->internalHasItem($key, $options)) { - continue; - } + // if MATCH_EXPIRED -> filter active items + if (($normalizedMode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { + if ($this->internalHasItem($key, $normalizedOptions)) { + continue; + } - // if MATCH_ACTIVE -> filter expired items - } else { - if (!$this->internalHasItem($key, $options)) { - continue; - } + // if MATCH_ACTIVE -> filter expired items + } else { + if (!$this->internalHasItem($key, $normalizedOptions)) { + continue; } } + } - // compare tags - if ($tags !== null) { - $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; - - if ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); - } elseif ( ($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - $matched = (count(array_diff($tags, $tagsStored)) == 0); - } + // compare tags + if ($tags !== null) { + $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; - // negate - if ( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - $matched = !$matched; - } + if ( ($normalizedMode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { + $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); + } elseif ( ($normalizedMode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { + $matched = (count(array_diff($tags, $tagsStored)) == 0); + } - if (!$matched) { - continue; - } + // negate + if ( ($normalizedMode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { + $matched = !$matched; } - $keys[] = $key; + if (!$matched) { + continue; + } } - // don't check expiry on fetch - $options['ttl'] = 0; + $keys[] = $key; + } - $this->stmtKeys = $keys; - $this->stmtOptions = $options; - $this->stmtActive = true; + // don't check expiry on fetch + $normalizedOptions['ttl'] = 0; - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $this->stmtKeys = $keys; + $this->stmtOptions = $normalizedOptions; + $this->stmtActive = true; + + return true; } /** - * Fetches the next item from result set + * Internal method to fetch the next item from result set * * @return array|boolean The next item or false * @throws Exception - * @see fetchAll() - * - * @triggers fetch.pre(PreEvent) - * @triggers fetch.post(PostEvent) - * @triggers fetch.exception(ExceptionEvent) */ - public function fetch() + protected function internalFetch() { if (!$this->stmtActive) { return false; } - try { - $args = new ArrayObject(); - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); + $options = & $this->stmtOptions; + + // get the next valid item + do { + $key = array_shift($this->stmtKeys); + if ($key === null) { + break; } - $options = & $this->stmtOptions; + if (!$this->internalHasItem($key, $options)) { + continue; + } - // get the next valid item - do { - $key = array_shift($this->stmtKeys); - if ($key === null) { - break; - } - if (!$this->internalHasItem($key, $options)) { - continue; - } - $ref = & $this->data[ $options['namespace'] ][$key]; - break; - } while (true); - - // get item data - if ($key) { - $item = array(); - foreach ($options['select'] as $select) { - if ($select == 'key') { - $item['key'] = $key; - } elseif ($select == 'value') { - $item['value'] = $ref[0]; - } elseif ($select == 'mtime') { - $item['mtime'] = $ref[1]; - } elseif ($select == 'tags') { - $item['tags'] = $ref[2]; - } else { - $item[$select] = null; - } - } + break; + } while (true); - $result = $item; + // free statement after last item + if (!$key) { + $this->stmtActive = false; + $this->stmtKeys = null; + $this->stmtOptions = null; - } else { - // free statement after last item - $this->stmtActive = false; - $this->stmtKeys = null; - $this->stmtOptions = null; + return false; + } - $result = false; + $ref = & $this->data[ $options['namespace'] ][$key]; + $result = array(); + foreach ($options['select'] as $select) { + if ($select == 'key') { + $result['key'] = $key; + } elseif ($select == 'value') { + $result['value'] = $ref[0]; + } elseif ($select == 'mtime') { + $result['mtime'] = $ref[1]; + } elseif ($select == 'tags') { + $result['tags'] = $ref[2]; + } else { + $result[$select] = null; } - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return $result; } /* cleaning */ /** - * Clear items off all namespaces. - * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * Internal method to clear items off all namespaces. * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see clearByNamespace() - * - * @triggers clear.pre(PreEvent) - * @triggers clear.post(PostEvent) - * @triggers clear.exception(ExceptionEvent) + * @see clearByNamespace() */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { - $this->data = array(); - } else { - foreach ($this->data as &$data) { - $this->clearNamespacedDataArray($data, $mode, $options); - } + if (!$normalizedOptions['tags'] && ($normalizedMode & self::MATCH_ALL) == self::MATCH_ALL) { + $this->data = array(); + } else { + foreach ($this->data as & $data) { + $this->clearNamespacedDataArray($data, $normalizedMode, $normalizedOptions); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return true; } /** * Clear items by namespace. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - tags + * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean - * @throws Zend\Cache\Exception - * @see clear() - * - * @triggers clearByNamespace.pre(PreEvent) - * @triggers clearByNamespace.post(PostEvent) - * @triggers clearByNamespace.exception(ExceptionEvent) + * @throws Exception + * @see clear() */ - public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if (isset($this->data[ $options['namespace'] ])) { - if (!$options['tags'] && ($mode & self::MATCH_ALL) == self::MATCH_ALL) { - unset($this->data[ $options['namespace'] ]); - } else { - $this->clearNamespacedDataArray($this->data[ $options['namespace'] ], $mode, $options); - } + if (isset($this->data[ $normalizedOptions['namespace'] ])) { + if (!$normalizedOptions['tags'] && ($normalizedMode & self::MATCH_ALL) == self::MATCH_ALL) { + unset($this->data[ $normalizedOptions['namespace'] ]); + } else { + $this->clearNamespacedDataArray($this->data[ $normalizedOptions['namespace'] ], $normalizedMode, $normalizedOptions); } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); } + + return true; } /* status */ /** - * Get capabilities + * Internal method to get capabilities of this adapter * * @return Capabilities - * - * @triggers getCapabilities.pre(PreEvent) - * @triggers getCapabilities.post(PostEvent) - * @triggers getCapabilities.exception(ExceptionEvent) */ - public function getCapabilities() + protected function internalGetCapabilities() { - $args = new ArrayObject(); - - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - if ($this->capabilities === null) { $this->capabilityMarker = new stdClass(); $this->capabilities = new Capabilities( @@ -1247,39 +852,24 @@ public function getCapabilities() ); } - return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); + return $this->capabilities; } /** - * Get storage capacity. + * Internal method to get storage capacity. * - * @param array $options + * @param array $normalizedOptions * @return array|boolean Capacity as array or false on failure * @throws Exception - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) */ - public function getCapacity(array $options = array()) + protected function internalGetCapacity(array & $normalizedOptions) { - $args = new ArrayObject(array( - 'options' => & $options, - )); - - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - $total = $this->getOptions()->getMemoryLimit(); $free = $total - (float) memory_get_usage(true); - $result = array( + return array( 'total' => $total, 'free' => ($free >= 0) ? $free : 0, ); - - return $this->triggerPost(__FUNCTION__, $args, $result); } /* internal */ diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 346372277..e79602234 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -303,499 +303,284 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * Add an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * * @param string $key * @param mixed $value * @param array $options * @return boolean * @throws Exception - * - * @triggers addItem.pre(PreEvent) - * @triggers addItem.post(PostEvent) - * @triggers addItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!wincache_ucache_add($internalKey, $value, $options['ttl'])) { - if (wincache_ucache_exists($internalKey)) { - throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); - } - - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "wincache_ucache_add('{$internalKey}', <{$type}>, {$options['ttl']}) failed" - ); + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!wincache_ucache_add($internalKey, $value, $normalizedOptions['ttl'])) { + // TODO: check if this is really needed + if (wincache_ucache_exists($internalKey)) { + throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); } - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "wincache_ucache_add('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + ); } + + return true; } /** - * Add multiple items. + * Internal method to add multiple items. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param array $keyValuePairs - * @param array $options + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers addItems.pre(PreEvent) - * @triggers addItems.post(PostEvent) - * @triggers addItems.exception(ExceptionEvent) */ - public function addItems(array $keyValuePairs, array $options = array()) + protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKeyValuePairs = array(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { + $internalKey = $prefix . $normalizedKey; + $internalKeyValuePairs[$internalKey] = $value; } - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKeyValuePairs = array(); - $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); - foreach ($keyValuePairs as $key => &$value) { - $internalKey = $prefix . $key; - $internalKeyValuePairs[$internalKey] = &$value; - } - - $errKeys = wincache_ucache_add($internalKeyValuePairs, null, $options['ttl']); - if ($errKeys!==array()) { - throw new Exception\RuntimeException( - "wincache_ucache_add(, null, {$options['ttl']}) failed for keys: " - . "'" . implode("','", array_keys($errKeys)) . "'" - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $errKeys = wincache_ucache_add($internalKeyValuePairs, null, $normalizedOptions['ttl']); + if ($errKeys !== array()) { + throw new Exception\RuntimeException( + "wincache_ucache_add(, null, {$normalizedOptions['ttl']}) failed for keys: " + . "'" . implode("','", array_keys($errKeys)) . "'" + ); } + + return true; } /** - * Replace an item. + * Internal method to replace an existing item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers replaceItem.pre(PreEvent) - * @triggers replaceItem.post(PostEvent) - * @triggers replaceItem.exception(ExceptionEvent) */ - public function replaceItem($key, $value, array $options = array()) + protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!wincache_ucache_exists($internalKey)) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' doesn't exist" + ); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!wincache_ucache_exists($internalKey)) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' doesn't exist" - ); - } - - if (!wincache_ucache_set($internalKey, $value, $options['ttl'])) { - $type = is_object($value) ? get_class($value) : gettype($value); - throw new Exception\RuntimeException( - "wincache_ucache_set('{$internalKey}', <{$type}>, {$options['ttl']}) failed" - ); - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + if (!wincache_ucache_set($internalKey, $value, $normalizedOptions['ttl'])) { + $type = is_object($value) ? get_class($value) : gettype($value); + throw new Exception\RuntimeException( + "wincache_ucache_set('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + ); } + + return true; } /** - * Remove an item. + * Internal method to remove an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param array $options + * @param string $normalizedKey + * @param array $normalizedOptions * @return boolean * @throws Exception - * - * @triggers removeItem.pre(PreEvent) - * @triggers removeItem.post(PostEvent) - * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + if (!wincache_ucache_delete($internalKey) && !$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); } - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - if (!wincache_ucache_delete($internalKey)) { - if (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - } - - $result = true; - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return true; } /** - * Increment an item. + * Internal method to increment an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers incrementItem.pre(PreEvent) - * @triggers incrementItem.post(PostEvent) - * @triggers incrementItem.exception(ExceptionEvent) */ - public function incrementItem($key, $value, array $options = array()) + protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $value = (int)$value; - $newValue = wincache_ucache_inc($internalKey, $value); - if ($newValue === false) { - if (wincache_ucache_exists($internalKey)) { - throw new Exception\RuntimeException("wincache_ucache_inc('{$internalKey}', {$value}) failed"); - } elseif (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); - } - - $this->addItem($key, $value, $options); - $newValue = $value; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $value = (int)$value; + $newValue = wincache_ucache_inc($internalKey, $value); + if ($newValue === false) { + if (wincache_ucache_exists($internalKey)) { + throw new Exception\RuntimeException("wincache_ucache_inc('{$internalKey}', {$value}) failed"); + } elseif (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' not found" + ); } - return $this->triggerPost(__FUNCTION__, $args, $newValue); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $newValue = $value; + $this->addItem($normalizedKey, $newValue, $normalizedOptions); } + + return $newValue; } /** - * Decrement an item. + * Internal method to decrement an item. * * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * - ignore_missing_items + * - Throw exception on missing item * - * @param string $key - * @param int $value - * @param array $options - * @return int|boolean The new value or false or failure + * @param string $normalizedKey + * @param int $value + * @param array $normalizedOptions + * @return int|boolean The new value or false on failure * @throws Exception - * - * @triggers decrementItem.pre(PreEvent) - * @triggers decrementItem.post(PostEvent) - * @triggers decrementItem.exception(ExceptionEvent) */ - public function decrementItem($key, $value, array $options = array()) + protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeKey($key); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key; - $value = (int)$value; - $newValue = wincache_ucache_dec($internalKey, $value); - if ($newValue === false) { - if (wincache_ucache_exists($internalKey)) { - throw new Exception\RuntimeException("wincache_ucache_dec('{$internalKey}', {$value}) failed"); - } elseif (!$options['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); - } - - $this->addItem($key, -$value, $options); - $newValue = -$value; + $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $value = (int)$value; + $newValue = wincache_ucache_dec($internalKey, $value); + if ($newValue === false) { + if (wincache_ucache_exists($internalKey)) { + throw new Exception\RuntimeException("wincache_ucache_inc('{$internalKey}', {$value}) failed"); + } elseif (!$normalizedOptions['ignore_missing_items']) { + throw new Exception\ItemNotFoundException( + "Key '{$internalKey}' not found" + ); } - return $this->triggerPost(__FUNCTION__, $args, $newValue); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $newValue = -$value; + $this->addItem($normalizedKey, $newValue, $normalizedOptions); } - } - - /* find */ + return $newValue; + } /* cleaning */ /** - * Clear items off all namespaces. + * Internal method to clear items off all namespaces. * * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - tags optional - * - Tags to search for used with matching modes of - * Zend\Cache\Storage\Adapter::MATCH_TAGS_* - * - * @param int $mode Matching mode (Value of Zend\Cache\Storage\Adapter::MATCH_*) - * @param array $options + * - ttl + * - The time-to-life + * + * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) + * @param array $normalizedOptions * @return boolean * @throws Exception - * @see clearByNamespace() - * - * @triggers clear.pre(PreEvent) - * @triggers clear.post(PostEvent) - * @triggers clear.exception(ExceptionEvent) + * @see clearByNamespace() */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) + protected function internalClear(& $normalizedMode, array & $normalizedOptions) { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = wincache_ucache_clear(); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return wincache_ucache_clear(); } /* status */ /** - * Get capabilities + * Internal method to get capabilities of this adapter * * @return Capabilities - * - * @triggers getCapabilities.pre(PreEvent) - * @triggers getCapabilities.post(PostEvent) - * @triggers getCapabilities.exception(ExceptionEvent) */ - public function getCapabilities() + protected function internalGetCapabilities() { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, - array( - 'supportedDatatypes' => array( - 'NULL' => true, - 'boolean' => true, - 'integer' => true, - 'double' => true, - 'string' => true, - 'array' => true, - 'object' => 'object', - 'resource' => false, - ), - 'supportedMetadata' => array( - 'ttl', - 'num_hits', - 'internal_key', - 'mem_size' - ), - 'maxTtl' => 0, - 'staticTtl' => true, - 'ttlPrecision' => 1, - 'useRequestTime' => false, - 'expiredRead' => false, - 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => false, - ) - ); - } - - return $this->triggerPost(__FUNCTION__, $args, $this->capabilities); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + if ($this->capabilities === null) { + $this->capabilityMarker = new stdClass(); + $this->capabilities = new Capabilities( + $this->capabilityMarker, + array( + 'supportedDatatypes' => array( + 'NULL' => true, + 'boolean' => true, + 'integer' => true, + 'double' => true, + 'string' => true, + 'array' => true, + 'object' => 'object', + 'resource' => false, + ), + 'supportedMetadata' => array( + 'ttl', + 'num_hits', + 'internal_key', + 'mem_size' + ), + 'maxTtl' => 0, + 'staticTtl' => true, + 'ttlPrecision' => 1, + 'useRequestTime' => false, + 'expiredRead' => false, + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), + 'iterable' => false, + 'clearAllNamespaces' => true, + 'clearByNamespace' => false, + ) + ); } + + return $this->capabilities; } /** - * Get storage capacity. + * Internal method to get storage capacity. * - * @param array $options + * @param array $normalizedOptions * @return array|boolean Capacity as array or false on failure - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) + * @throws Exception */ - public function getCapacity(array $options = array()) + protected function internalGetCapacity(array & $normalizedOptions) { - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $mem = wincache_ucache_meminfo (); - $result = array( - 'free' => $mem['memory_free'], - 'total' => $mem['memory_total'], - ); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $mem = wincache_ucache_meminfo(); + return array( + 'free' => $mem['memory_free'], + 'total' => $mem['memory_total'], + ); } /* internal */ diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index 85a930f54..f41522245 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -54,32 +54,15 @@ public function __construct($options = array()) } /** - * Get storage capacity. + * Internal method to get storage capacity. * - * @param array $options + * @param array $normalizedOptions * @return array|boolean Capacity as array or false on failure - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) + * @throws Exception */ - public function getCapacity(array $options = array()) + protected function internalGetCapacity(array & $normalizedOptions) { - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = Utils::getDiskCapacity(ini_get('zend_datacache.disk.save_path')); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + return Utils::getDiskCapacity(ini_get('zend_datacache.disk.save_path')); } /** diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index f04b64bf1..82c8112b7 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -53,38 +53,20 @@ public function __construct($options = array()) } /** - * Get storage capacity. + * Internal method to get storage capacity. * - * @param array $options + * @param array $normalizedOptions * @return array|boolean Capacity as array or false on failure - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) + * @throws Exception */ - public function getCapacity(array $options = array()) + protected function internalGetCapacity(array & $normalizedOptions) { - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $total = (int)ini_get('zend_datacache.shm.memory_cache_size'); - $total*= 1048576; // MB -> Byte - $result = array( - 'total' => $total, - // TODO: How to get free capacity status - ); - - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); - } + $total = (int)ini_get('zend_datacache.shm.memory_cache_size'); + $total*= 1048576; // MB -> Byte + return array( + 'total' => $total, + // TODO: How to get free capacity status + ); } /** From 4d2ee5f52c8efa986850eb9314677f6726956da6 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 18 Mar 2012 06:26:04 +0100 Subject: [PATCH 221/311] fixed testDisabledFileBlocking on windows --- src/Storage/Adapter/FilesystemOptions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index 0d983fd3b..33e5d5fde 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -329,7 +329,7 @@ public function getDirUmask() public function setFileBlocking($flag) { $flag = (bool) $flag; - if ($flag && substr(\PHP_OS, 0, 3) == 'WIN') { + if (!$flag && substr(\PHP_OS, 0, 3) == 'WIN') { throw new Exception\InvalidArgumentException( "This option can't be disabled on windows" ); From 3dc87fd07834a0c99c6a3efaf3ad1e7eeef145b1 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sun, 18 Mar 2012 20:46:01 +0100 Subject: [PATCH 222/311] dos2unix --- src/Storage/Adapter/AbstractAdapter.php | 162 ++++++++++---------- src/Storage/Adapter/Apc.php | 70 ++++----- src/StorageFactory.php | 8 +- test/PatternFactoryTest.php | 10 +- test/Storage/Adapter/WinCacheTest.php | 4 +- test/Storage/Adapter/ZendServerDiskTest.php | 4 +- test/Storage/Adapter/ZendServerShmTest.php | 4 +- test/StorageFactoryTest.php | 6 +- 8 files changed, 134 insertions(+), 134 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index f0317e22b..0734a8dce 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -670,19 +670,19 @@ public function getMetadata($key, array $options = array()) } } - /** - * Internal method to get metadata of an item. - * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - * @param string $normalizedKey - * @param array $normalizedOptions - * @return array|boolean Metadata or false on failure - * @throws Exception + /** + * Internal method to get metadata of an item. + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param string $normalizedKey + * @param array $normalizedOptions + * @return array|boolean Metadata or false on failure + * @throws Exception */ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { @@ -743,19 +743,19 @@ public function getMetadatas(array $keys, array $options = array()) } } - /** - * Internal method to get multiple metadata - * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - * @param array $normalizedKeys - * @param array $normalizedOptions - * @return array Associative array of existing cache ids and its metadata - * @throws Exception + /** + * Internal method to get multiple metadata + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing cache ids and its metadata + * @throws Exception */ protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) { @@ -780,8 +780,8 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal /* writing */ - /** - * Store an item. + /** + * Store an item. * * Options: * - ttl optional @@ -790,17 +790,17 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal * - The namespace to use (Default: namespace of object) * - tags optional * - An array of tags - * - * @param string $key - * @param mixed $value - * @param array $options - * @return boolean + * + * @param string $key + * @param mixed $value + * @param array $options + * @return boolean * @throws Exception * * @triggers setItem.pre(PreEvent) * @triggers setItem.post(PostEvent) - * @triggers setItem.exception(ExceptionEvent) - */ + * @triggers setItem.exception(ExceptionEvent) + */ public function setItem($key, $value, array $options = array()) { if (!$this->getOptions()->getWritable()) { @@ -828,8 +828,8 @@ public function setItem($key, $value, array $options = array()) } } - /** - * Internal method to store an item. + /** + * Internal method to store an item. * * Options: * - ttl @@ -838,13 +838,13 @@ public function setItem($key, $value, array $options = array()) * - The namespace to use * - tags * - An array of tags - * - * @param string $normalizedKey - * @param mixed $value - * @param array $normalizedOptions - * @return boolean - * @throws Exception - */ + * + * @param string $normalizedKey + * @param mixed $value + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ abstract protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions); /** @@ -893,8 +893,8 @@ public function setItems(array $keyValuePairs, array $options = array()) } } - /** - * Internal method to store multiple items. + /** + * Internal method to store multiple items. * * Options: * - ttl @@ -903,19 +903,19 @@ public function setItems(array $keyValuePairs, array $options = array()) * - The namespace to use * - tags * - An array of tags - * - * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions - * @return boolean - * @throws Exception - */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { $result = true; foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { $result = $this->internalSetItem($normalizedKey, $value, $normalizedOptions) && $result; } - return $result; + return $result; } /** @@ -1865,24 +1865,24 @@ protected function internatDecrementItems(array & $normalizedKeyValuePairs, arra return $ret; } - /* non-blocking */ - - /** - * Request multiple items. - * - * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - select optional - * - An array of the information the returned item contains - * (Default: array('key', 'value')) - * - callback optional - * - An result callback will be invoked for each item in the result set. - * - The first argument will be the item array. - * - The callback does not have to return anything. - * + /* non-blocking */ + + /** + * Request multiple items. + * + * Options: + * - ttl optional + * - The time-to-live (Default: ttl of object) + * - namespace optional + * - The namespace to use (Default: namespace of object) + * - select optional + * - An array of the information the returned item contains + * (Default: array('key', 'value')) + * - callback optional + * - An result callback will be invoked for each item in the result set. + * - The first argument will be the item array. + * - The callback does not have to return anything. + * * @param array $keys * @param array $options * @return boolean @@ -1893,15 +1893,15 @@ protected function internatDecrementItems(array & $normalizedKeyValuePairs, arra * @triggers getDelayed.pre(PreEvent) * @triggers getDelayed.post(PostEvent) * @triggers getDelayed.exception(ExceptionEvent) - */ - public function getDelayed(array $keys, array $options = array()) - { - if (!$this->getOptions()->getReadable()) { - return false; - } elseif (!$keys) { - // empty statement - return true; - } + */ + public function getDelayed(array $keys, array $options = array()) + { + if (!$this->getOptions()->getReadable()) { + return false; + } elseif (!$keys) { + // empty statement + return true; + } $this->normalizeKeys($keys); $this->normalizeOptions($options); diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 5c2459681..9968410b3 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -656,8 +656,8 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no return $newValue; } - /* non-blocking */ - + /* non-blocking */ + /** * Internal method to request multiple items. * @@ -680,42 +680,42 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no * @see fetch() * @see fetchAll() */ - protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - if (isset($normalizedOptions['callback']) && !is_callable($normalizedOptions['callback'], false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - + protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) + { + if ($this->stmtActive) { + throw new Exception\RuntimeException('Statement already in use'); + } + + if (isset($normalizedOptions['callback']) && !is_callable($normalizedOptions['callback'], false)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } + $format = 0; - foreach ($normalizedOptions['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; - } - } + foreach ($normalizedOptions['select'] as $property) { + if (isset(self::$selectMap[$property])) { + $format = $format | self::$selectMap[$property]; + } + } $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $search = array(); - foreach ($normalizedKeys as $normalizedKey) { - $search[] = preg_quote($normalizedKey, '/'); - } - $search = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $search) . ')$/'; - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = & $normalizedOptions; - - if (isset($normalizedOptions['callback'])) { - $callback = & $normalizedOptions['callback']; - while (($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - return true; + $search = array(); + foreach ($normalizedKeys as $normalizedKey) { + $search[] = preg_quote($normalizedKey, '/'); + } + $search = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $search) . ')$/'; + + $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); + $this->stmtActive = true; + $this->stmtOptions = & $normalizedOptions; + + if (isset($normalizedOptions['callback'])) { + $callback = & $normalizedOptions['callback']; + while (($item = $this->fetch()) !== false) { + call_user_func($callback, $item); + } + } + + return true; } /* find */ diff --git a/src/StorageFactory.php b/src/StorageFactory.php index 5372ad874..ef39a5cb2 100644 --- a/src/StorageFactory.php +++ b/src/StorageFactory.php @@ -99,10 +99,10 @@ public static function factory($cfg) foreach ($cfg['plugins'] as $k => $v) { if (is_string($k)) { - if (!is_array($v)) { - throw new Exception\InvalidArgumentException( - "'plugins.{$k}' needs to be an array" - ); + if (!is_array($v)) { + throw new Exception\InvalidArgumentException( + "'plugins.{$k}' needs to be an array" + ); } $pluginName = $k; $pluginOptions = $v; diff --git a/test/PatternFactoryTest.php b/test/PatternFactoryTest.php index ee66ea314..93b5cfddf 100644 --- a/test/PatternFactoryTest.php +++ b/test/PatternFactoryTest.php @@ -57,15 +57,15 @@ public function testChangeBroker() $this->assertSame($broker, Cache\PatternFactory::getBroker()); } - public function testFactory() - { + public function testFactory() + { $pattern1 = Cache\PatternFactory::factory('capture'); $this->assertInstanceOf('Zend\Cache\Pattern\CaptureCache', $pattern1); - + $pattern2 = Cache\PatternFactory::factory('capture'); $this->assertInstanceOf('Zend\Cache\Pattern\CaptureCache', $pattern2); - - $this->assertNotSame($pattern1, $pattern2); + + $this->assertNotSame($pattern1, $pattern2); } } diff --git a/test/Storage/Adapter/WinCacheTest.php b/test/Storage/Adapter/WinCacheTest.php index 35264936a..c414fc7e9 100644 --- a/test/Storage/Adapter/WinCacheTest.php +++ b/test/Storage/Adapter/WinCacheTest.php @@ -36,8 +36,8 @@ class WinCacheTest extends CommonAdapterTest public function setUp() { - if (!defined('TESTS_ZEND_CACHE_WINCACHE_ENABLED') || !TESTS_ZEND_CACHE_WINCACHE_ENABLED) { - $this->markTestSkipped("Skipped by TestConfiguration (TESTS_ZEND_CACHE_WINCACHE_ENABLED)"); + if (!defined('TESTS_ZEND_CACHE_WINCACHE_ENABLED') || !TESTS_ZEND_CACHE_WINCACHE_ENABLED) { + $this->markTestSkipped("Skipped by TestConfiguration (TESTS_ZEND_CACHE_WINCACHE_ENABLED)"); } if (!extension_loaded('wincache')) { diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php index 2fefd40af..22f8e3b71 100644 --- a/test/Storage/Adapter/ZendServerDiskTest.php +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -37,8 +37,8 @@ class ZendServerDiskTest extends CommonAdapterTest public function setUp() { - if (!defined('TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED') || !TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED) { - $this->markTestSkipped("Skipped by TestConfiguration (TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED)"); + if (!defined('TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED') || !TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED) { + $this->markTestSkipped("Skipped by TestConfiguration (TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED)"); } if (!function_exists('zend_disk_cache_store') || PHP_SAPI == 'cli') { diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index b2c3142fa..965f65695 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -37,8 +37,8 @@ class ZendServerShmTest extends CommonAdapterTest public function setUp() { - if (!defined('TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED') || !TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED) { - $this->markTestSkipped("Skipped by TestConfiguration (TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED)"); + if (!defined('TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED') || !TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED) { + $this->markTestSkipped("Skipped by TestConfiguration (TESTS_ZEND_CACHE_ZEND_SERVER_ENABLED)"); } if (strtolower(PHP_SAPI) == 'cli') { diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index fd62ca36d..8940e04ad 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -42,7 +42,7 @@ public function setUp() public function tearDown() { - Cache\StorageFactory::resetAdapterBroker(); + Cache\StorageFactory::resetAdapterBroker(); Cache\StorageFactory::resetPluginBroker(); } @@ -64,7 +64,7 @@ public function testAdapterFactory() $adapter1 = Cache\StorageFactory::adapterFactory('Memory'); $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $adapter1); - $adapter2 = Cache\StorageFactory::adapterFactory('Memory'); + $adapter2 = Cache\StorageFactory::adapterFactory('Memory'); $this->assertInstanceOf('Zend\Cache\Storage\Adapter\Memory', $adapter2); $this->assertNotSame($adapter1, $adapter2); @@ -88,7 +88,7 @@ public function testPluginFactory() $plugin1 = Cache\StorageFactory::pluginFactory('Serializer'); $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $plugin1); - $plugin2 = Cache\StorageFactory::pluginFactory('Serializer'); + $plugin2 = Cache\StorageFactory::pluginFactory('Serializer'); $this->assertInstanceOf('Zend\Cache\Storage\Plugin\Serializer', $plugin2); $this->assertNotSame($plugin1, $plugin2); From b1cb0435d183a31aca76eb061e10adcac346532f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 22 Mar 2012 22:29:00 +0100 Subject: [PATCH 223/311] Cache: now storage adapter options triggers 'option' event on change option(s), the adapter can listen to it to update capabilities and to update internal instances --- src/Storage/Adapter/AbstractAdapter.php | 30 ++++- src/Storage/Adapter/AdapterOptions.php | 148 ++++++++++++++++------ src/Storage/Adapter/Apc.php | 18 ++- src/Storage/Adapter/ApcOptions.php | 4 +- src/Storage/Adapter/Filesystem.php | 90 ++++++------- src/Storage/Adapter/FilesystemOptions.php | 73 ++++------- src/Storage/Adapter/Memcached.php | 2 +- src/Storage/Adapter/MemcachedOptions.php | 16 ++- src/Storage/Adapter/MemoryOptions.php | 4 +- src/Storage/Adapter/WinCache.php | 18 ++- src/Storage/Adapter/WinCacheOptions.php | 4 +- 11 files changed, 259 insertions(+), 148 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 0734a8dce..31ad92f76 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -51,6 +51,12 @@ abstract class AbstractAdapter implements Adapter */ protected $events = null; + /** + * Event handles of this adapter + * @var array + */ + protected $eventHandles = array(); + /** * The plugin registry * @@ -128,6 +134,13 @@ public function __destruct() foreach ($this->getPlugins() as $plugin) { $this->removePlugin($plugin); } + + if ($this->eventHandles) { + $events = $this->events(); + foreach ($this->eventHandles as $handle) { + $events->detach($handle); + } + } } /* configuration */ @@ -141,11 +154,20 @@ public function __destruct() */ public function setOptions($options) { - if (!$options instanceof AdapterOptions) { - $options = new AdapterOptions($options); - } + if ($this->options !== $options) { + if (!$options instanceof AdapterOptions) { + $options = new AdapterOptions($options); + } - $this->options = $options; + if ($this->options) { + $this->options->setAdapter(null); + } + $options->setAdapter($this); + $this->options = $options; + + $event = new Event('option', $this, new ArrayObject($options->toArray())); + $this->events()->trigger($event); + } return $this; } diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 46daef1d2..508ed1be7 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -21,7 +21,10 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception, +use ArrayObject, + Zend\Cache\Exception, + Zend\Cache\Storage\Adapter, + Zend\Cache\Storage\Event, Zend\Stdlib\Options; /** @@ -35,6 +38,14 @@ */ class AdapterOptions extends Options { + + /** + * The adapter using these options + * + * @var null|Filesystem + */ + protected $adapter; + /** * Ignore missing items * @@ -103,6 +114,18 @@ public function toArray() return $array; } + /** + * Adapter using this instance + * + * @param Adapter|null $adapter + * @return AdapterOptions + */ + public function setAdapter(Adapter $adapter = null) + { + $this->adapter = $adapter; + return $this; + } + /** * Enables or disables ignoring of missing items. * @@ -121,7 +144,11 @@ public function toArray() */ public function setIgnoreMissingItems($flag) { - $this->ignoreMissingItems = (bool) $flag; + $flag = (bool) $flag; + if ($this->ignoreMissingItems !== $flag) { + $this->triggerOptionEvent('ignore_missing_items', $flag); + $this->ignoreMissingItems = $flag; + } return $this; } @@ -144,19 +171,20 @@ public function getIgnoreMissingItems() */ public function setKeyPattern($pattern) { - if (($pattern = (string) $pattern) === '') { - $this->keyPattern = ''; - return $this; - } + $pattern = (string) $pattern; + if ($this->keyPattern !== $pattern) { + // validate pattern + if ($pattern !== '') { + if (@preg_match($pattern, '') === false) { + $err = error_get_last(); + throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); + } + } - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); + $this->triggerOptionEvent('key_pattern', $pattern); + $this->keyPattern = $pattern; } - $this->keyPattern = $pattern; - return $this; } @@ -179,18 +207,23 @@ public function getKeyPattern() public function setNamespace($namespace) { $namespace = (string)$namespace; - if ($namespace === '') { - throw new Exception\InvalidArgumentException('No namespace given'); - } + if ($this->namespace !== $namespace) { + if ($namespace === '') { + // TODO: allow empty namespaces + throw new Exception\InvalidArgumentException('No namespace given'); + } + + $pattern = $this->getNamespacePattern(); + if ($pattern && !preg_match($pattern, $namespace)) { + throw new Exception\InvalidArgumentException( + "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" + ); + } - if (($pattern = $this->getNamespacePattern()) - && !preg_match($pattern, $namespace) - ) { - throw new Exception\InvalidArgumentException( - "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" - ); + $this->triggerOptionEvent('namespace', $namespace); + $this->namespace = $namespace; } - $this->namespace = (string) $namespace; + return $this; } @@ -212,26 +245,27 @@ public function getNamespace() */ public function setNamespacePattern($pattern) { - if (($pattern = (string) $pattern) === '') { - $this->namespacePattern = ''; - return $this; - } + $pattern = (string) $pattern; + if ($this->namespacePattern !== $pattern) { + if ($pattern !== '') { + // validate pattern + if (@preg_match($pattern, '') === false) { + $err = error_get_last(); + throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); + + // validate current namespace + } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { + throw new Exception\RuntimeException( + "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" + . " - please change the namespace first" + ); + } + } - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - - // validate current namespace - } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { - throw new Exception\RuntimeException( - "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" - . " - please change the namespace first" - ); + $this->triggerOptionEvent('namespace_pattern', $pattern); + $this->namespacePattern = $pattern; } - $this->namespacePattern = $pattern; - return $this; } @@ -253,7 +287,11 @@ public function getNamespacePattern() */ public function setReadable($flag) { - $this->readable = (bool) $flag; + $flag = (bool) $flag; + if ($this->readable !== $flag) { + $this->triggerOptionEvent('readable', $flag); + $this->readable = $flag; + } return $this; } @@ -276,7 +314,10 @@ public function getReadable() public function setTtl($ttl) { $this->normalizeTtl($ttl); - $this->ttl = $ttl; + if ($this->ttl !== $ttl) { + $this->triggerOptionEvent('ttl', $ttl); + $this->ttl = $ttl; + } return $this; } @@ -298,7 +339,11 @@ public function getTtl() */ public function setWritable($flag) { - $this->writable = (bool) $flag; + $flag = (bool) $flag; + if ($this->writable !== $flag) { + $this->triggerOptionEvent('writable', $flag); + $this->writable = $flag; + } return $this; } @@ -312,11 +357,30 @@ public function getWritable() return $this->writable; } + /** + * Triggers an option.change event + * if the this options instance has a connection too an adapter instance + * + * @param string $optionName + * @param mixed $optionValue + * @return void + */ + protected function triggerOptionEvent($optionName, $optionValue) + { + if (!$this->adapter) { + return; + } + + $event = new Event('option', $this->adapter, new ArrayObject(array($optionName => $optionValue))); + $this->adapter->events()->trigger($event); + } + /** * Validates and normalize a TTL. * * @param int|float $ttl * @throws Exception\InvalidArgumentException + * @return void */ protected function normalizeTtl(&$ttl) { diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 9968410b3..bb9748091 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -852,9 +852,9 @@ protected function internalClearByNamespace(& $normalizedMode, array & $normaliz protected function internalGetCapabilities() { if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, + $marker = new stdClass(); + $capabilities = new Capabilities( + $marker, array( 'supportedDatatypes' => array( 'NULL' => true, @@ -891,6 +891,18 @@ protected function internalGetCapabilities() 'clearByNamespace' => true, ) ); + + // update namespace separator on change option + $this->events()->attach('option', function ($event) use ($capabilities, $marker) { + $params = $event->getParams(); + + if (isset($params['namespace_separator'])) { + $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); + } + }); + + $this->capabilities = $capabilities; + $this->capabilityMarker = $marker; } return $this->capabilities; diff --git a/src/Storage/Adapter/ApcOptions.php b/src/Storage/Adapter/ApcOptions.php index adf39b5f5..e14b6f0e6 100644 --- a/src/Storage/Adapter/ApcOptions.php +++ b/src/Storage/Adapter/ApcOptions.php @@ -47,7 +47,9 @@ class ApcOptions extends AdapterOptions */ public function setNamespaceSeparator($separator) { - $this->namespaceSeparator = (string) $separator; + $separator = (string) $separator; + $this->triggerOptionEvent('namespace_separator', $separator); + $this->namespaceSeparator = $separator; return $this; } diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index c8eec183f..b2bf10ad5 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -83,9 +83,7 @@ public function setOptions($options) $options = new FilesystemOptions($options); } - $this->options = $options; - $options->setAdapter($this); - return $this; + return parent::setOptions($options); } /** @@ -1040,9 +1038,20 @@ protected function internalOptimize(array & $normalizedOptions) protected function internalGetCapabilities() { if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, + $marker = new stdClass(); + $options = $this->getOptions(); + + // detect metadata + $metadata = array('mtime', 'filespec'); + if (!$options->getNoAtime()) { + $metadata[] = 'atime'; + } + if (!$options->getNoCtime()) { + $metadata[] = 'ctime'; + } + + $capabilities = new Capabilities( + $marker, array( 'supportedDatatypes' => array( 'NULL' => 'string', @@ -1054,7 +1063,7 @@ protected function internalGetCapabilities() 'object' => false, 'resource' => false, ), - 'supportedMetadata' => array('mtime', 'filespec'), + 'supportedMetadata' => $metadata, 'maxTtl' => 0, 'staticTtl' => false, 'tagging' => true, @@ -1062,15 +1071,42 @@ protected function internalGetCapabilities() 'expiredRead' => true, 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) 'namespaceIsPrefix' => true, - 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), + 'namespaceSeparator' => $options->getNamespaceSeparator(), 'iterable' => true, 'clearAllNamespaces' => true, 'clearByNamespace' => true, ) ); - // set dynamic capibilities - $this->updateCapabilities(); + // update capabilities on change options + $this->events()->attach('option', function ($event) use ($capabilities, $marker) { + $params = $event->getParams(); + + if (isset($params['namespace_separator'])) { + $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); + } + + if (isset($params['no_atime']) || isset($params['no_ctime'])) { + $metadata = $capabilities->getSupportedMetadata(); + + if (isset($params['no_atime']) && !$params['no_atime']) { + $metadata[] = 'atime'; + } elseif (isset($params['no_atime']) && ($index = array_search('atime', $metadata)) !== false) { + unset($metadata[$index]); + } + + if (isset($params['no_ctime']) && !$params['no_ctime']) { + $metadata[] = 'ctime'; + } elseif (isset($params['no_ctime']) && ($index = array_search('ctime', $metadata)) !== false) { + unset($metadata[$index]); + } + + $capabilities->setSupportedMetadata($marker, $metadata); + } + }); + + $this->capabilityMarker = $marker; + $this->capabilities = $capabilities; } return $this->capabilities; @@ -1578,38 +1614,4 @@ protected function unlink($file) ); } } - - /** - * Update dynamic capabilities only if already created - * - * @return void - */ - public function updateCapabilities() - { - if ($this->capabilities) { - $options = $this->getOptions(); - - // update namespace separator - $this->capabilities->setNamespaceSeparator( - $this->capabilityMarker, - $options->getNamespaceSeparator() - ); - - // update metadata capabilities - $metadata = array('mtime', 'filespec'); - - if (!$options->getNoCtime()) { - $metadata[] = 'ctime'; - } - - if (!$options->getNoAtime()) { - $metadata[] = 'atime'; - } - - $this->capabilities->setSupportedMetadata( - $this->capabilityMarker, - $metadata - ); - } - } } diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index 33e5d5fde..ce20ad9c7 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -35,12 +35,6 @@ */ class FilesystemOptions extends AdapterOptions { - /** - * The adapter using these options - * - * @var null|Filesystem - */ - protected $adapter; /** * Directory to store cache files @@ -151,19 +145,6 @@ class FilesystemOptions extends AdapterOptions */ protected $readControlAlgo = 'crc32'; - /** - * Filesystem adapter using this instance - * - * @param Filesystem $filesystem - * @return FilesystemOptions - */ - public function setAdapter(Filesystem $filesystem) - { - $this->adapter = $filesystem; - $this->updateCapabilities(); - return $this; - } - /** * Set cache dir * @@ -189,8 +170,11 @@ public function setCacheDir($dir) } $dir = rtrim(realpath($dir), \DIRECTORY_SEPARATOR); + } else { + $dir = sys_get_temp_dir(); } + $this->triggerOptionEvent('cache_dir', $dir); $this->cacheDir = $dir; return $this; } @@ -203,7 +187,7 @@ public function setCacheDir($dir) public function getCacheDir() { if ($this->cacheDir === null) { - $this->setCacheDir(sys_get_temp_dir()); + $this->setCacheDir(null); } return $this->cacheDir; @@ -217,7 +201,9 @@ public function getCacheDir() */ public function setClearStatCache($flag) { - $this->clearStatCache = (bool) $flag; + $flag = (bool) $flag; + $this->triggerOptionEvent('clear_stat_cache', $flag); + $this->clearStatCache = $flag; return $this; } @@ -246,6 +232,7 @@ public function setDirLevel($level) "Directory level '{$level}' must be between 0 and 16" ); } + $this->triggerOptionEvent('dir_level', $level); $this->dirLevel = $level; return $this; } @@ -302,6 +289,7 @@ public function setDirUmask($umask) } }); + $this->triggerOptionEvent('dir_umask', $umask); $this->dirUmask = $umask; return $this; } @@ -335,7 +323,8 @@ public function setFileBlocking($flag) ); } - $this->fileBlocking = (bool) $flag; + $this->triggerOptionEvent('file_blocking', $flag); + $this->fileBlocking = $flag; return $this; } @@ -361,7 +350,9 @@ public function getFileBlocking() */ public function setFileLocking($flag) { - $this->fileLocking = (bool)$flag; + $flag = (bool) $flag; + $this->triggerOptionEvent('file_locking', $flag); + $this->fileLocking = $flag; return $this; } @@ -422,6 +413,7 @@ public function setFileUmask($umask) } }); + $this->triggerOptionEvent('file_umask', $umask); $this->fileUmask = $umask; return $this; } @@ -444,8 +436,9 @@ public function getFileUmask() */ public function setNamespaceSeparator($separator) { - $this->namespaceSeparator = (string) $separator; - $this->updateCapabilities(); + $separator = (string) $separator; + $this->triggerOptionEvent('namespace_separator', $separator); + $this->namespaceSeparator = $separator; return $this; } @@ -467,8 +460,9 @@ public function getNamespaceSeparator() */ public function setNoAtime($flag) { - $this->noAtime = (bool) $flag; - $this->updateCapabilities(); + $flag = (bool) $flag; + $this->triggerOptionEvent('no_atime', $flag); + $this->noAtime = $flag; return $this; } @@ -490,8 +484,9 @@ public function getNoAtime() */ public function setNoCtime($flag) { - $this->noCtime = (bool) $flag; - $this->updateCapabilities(); + $flag = (bool) $flag; + $this->triggerOptionEvent('no_ctime', $flag); + $this->noCtime = $flag; return $this; } @@ -513,7 +508,9 @@ public function getNoCtime() */ public function setReadControl($flag) { - $this->readControl = (bool) $flag; + $flag = (bool) $flag; + $this->triggerOptionEvent('read_control', $flag); + $this->readControl = $flag; return $this; } @@ -542,6 +539,7 @@ public function setReadControlAlgo($algo) throw new Exception\InvalidArgumentException("Unsupported hash algorithm '{$algo}"); } + $this->triggerOptionEvent('read_control_algo', $algo); $this->readControlAlgo = $algo; return $this; } @@ -577,19 +575,4 @@ protected function normalizeUmask($umask, $callback = null) return $umask; } - - /** - * Update target capabilities - * - * Returns immediately if no adapter is present. - * - * @return void - */ - protected function updateCapabilities() - { - if (!$this->adapter) { - return; - } - $this->adapter->updateCapabilities(); - } } diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index e833f2f16..bdfbfc431 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -477,7 +477,7 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio */ protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) { - // support for removing multiple items at once has been added in ext/memcached 2 + // support for removing multiple items at once has been added in ext/memcached-2.0.0 if (static::$extMemcachedMajorVersion < 2) { return parent::internalRemoveItems($normalizedKeys, $normalizedOptions); } diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index ba4eaa37e..266d7d990 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -45,7 +45,7 @@ class MemcachedOptions extends AdapterOptions private $optionsMap = array( 'binary_protocol' => MemcachedResource::OPT_BINARY_PROTOCOL, 'buffer_writes' => MemcachedResource::OPT_BUFFER_WRITES, - 'cache_lookups' => MemcachedResource::OPT_CACHE_LOOKUPS, + //'cache_lookups' => MemcachedResource::OPT_CACHE_LOOKUPS, 'compression' => MemcachedResource::OPT_COMPRESSION, 'connect_timeout' => MemcachedResource::OPT_CONNECT_TIMEOUT, 'distribution' => MemcachedResource::OPT_DISTRIBUTION, @@ -54,10 +54,10 @@ class MemcachedOptions extends AdapterOptions 'no_block' => MemcachedResource::OPT_NO_BLOCK, 'poll_timeout' => MemcachedResource::OPT_POLL_TIMEOUT, 'recv_timeout' => MemcachedResource::OPT_RECV_TIMEOUT, - 'retry_timeout' => MemcachedResource::OPT_RETRY_TIMEOUT, + //'retry_timeout' => MemcachedResource::OPT_RETRY_TIMEOUT, 'send_timeout' => MemcachedResource::OPT_SEND_TIMEOUT, 'serializer' => MemcachedResource::OPT_SERIALIZER, - 'server_failure_limit' => MemcachedResource::OPT_SERVER_FAILURE_LIMIT, + //'server_failure_limit' => MemcachedResource::OPT_SERVER_FAILURE_LIMIT, 'socket_recv_size' => MemcachedResource::OPT_SOCKET_RECV_SIZE, 'socket_send_size' => MemcachedResource::OPT_SOCKET_SEND_SIZE, 'tcp_nodelay' => MemcachedResource::OPT_TCP_NODELAY, @@ -287,6 +287,16 @@ public function getServers() return $this->servers; } + /** + * Get overwrittern libmemcached options + * + * @return array + */ + public function getLibOptions() + { + return $this->libOptions; + } + /** * Set flag indicating whether or not to enable binary protocol for * communication with server diff --git a/src/Storage/Adapter/MemoryOptions.php b/src/Storage/Adapter/MemoryOptions.php index f6355dcbe..777ba2b04 100644 --- a/src/Storage/Adapter/MemoryOptions.php +++ b/src/Storage/Adapter/MemoryOptions.php @@ -54,7 +54,9 @@ class MemoryOptions extends AdapterOptions */ public function setMemoryLimit($bytes) { - $this->memoryLimit = (int) $bytes; + $bytes = (int) $bytes; + $this->triggerOptionEvent('memory_limit', $bytes); + $this->memoryLimit = $bytes; return $this; } diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index e79602234..a92bb637a 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -530,9 +530,9 @@ protected function internalClear(& $normalizedMode, array & $normalizedOptions) protected function internalGetCapabilities() { if ($this->capabilities === null) { - $this->capabilityMarker = new stdClass(); - $this->capabilities = new Capabilities( - $this->capabilityMarker, + $marker = new stdClass(); + $capabilities = new Capabilities( + $marker, array( 'supportedDatatypes' => array( 'NULL' => true, @@ -562,6 +562,18 @@ protected function internalGetCapabilities() 'clearByNamespace' => false, ) ); + + // update namespace separator on change option + $this->events()->attach('option', function ($event) use ($capabilities, $marker) { + $params = $event->getParams(); + + if (isset($params['namespace_separator'])) { + $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); + } + }); + + $this->capabilities = $capabilities; + $this->capabilityMarker = $marker; } return $this->capabilities; diff --git a/src/Storage/Adapter/WinCacheOptions.php b/src/Storage/Adapter/WinCacheOptions.php index e2256e953..09db0fadd 100644 --- a/src/Storage/Adapter/WinCacheOptions.php +++ b/src/Storage/Adapter/WinCacheOptions.php @@ -49,7 +49,9 @@ class WinCacheOptions extends AdapterOptions */ public function setNamespaceSeparator($separator) { - $this->namespaceSeparator = (string) $separator; + $separator = (string) $separator; + $this->triggerOptionEvent('namespace_separator', $separator); + $this->namespaceSeparator = $separator; return $this; } From d4aeeeddb682a6503b072f2e5864179798796f8d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 22 Mar 2012 23:21:33 +0100 Subject: [PATCH 224/311] memcached adapter: be more free to set libmemcached options and update options after passing it to the adapter instance --- src/Storage/Adapter/Memcached.php | 47 +- src/Storage/Adapter/MemcachedOptions.php | 740 ++--------------------- 2 files changed, 79 insertions(+), 708 deletions(-) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index bdfbfc431..5ac6373e8 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -73,20 +73,47 @@ public function __construct($options = null) throw new Exception\ExtensionNotLoadedException('Need ext/memcached version >= 1.0.0'); } - $this->memcached = new MemcachedResource(); - parent::__construct($options); - // It's ok to add server as soon as possible because + // It's ok to init the memcached instance as soon as possible because // ext/memcached auto-connects to the server on first use + $this->memcached = new MemcachedResource(); $options = $this->getOptions(); + // set lib options + if (static::$extMemcachedMajorVersion > 1) { + $this->memcached->setOptions($options->getLibOptions()); + } else { + foreach ($options->getLibOptions() as $k => $v) { + $this->memcached->setOption($k, $v); + } + } + $servers = $options->getServers(); if (!$servers) { $options->addServer('127.0.0.1', 11211); $servers = $options->getServers(); } $this->memcached->addServers($servers); + + // get notified on change options + $memc = $this->memcached; + $memcMV = static::$extMemcachedMajorVersion; + $this->events()->attach('option', function ($event) use ($memc, $memcMV) { + $params = $event->getParams(); + + if (isset($params['lib_options'])) { + if ($memcMV > 1) { + $memc->setOptions($params['lib_options']); + } else { + foreach ($params['lib_options'] as $k => $v) { + $memc->setOption($k, $v); + } + } + } + + // TODO: update on change/add server(s) + }); } /* options */ @@ -104,19 +131,7 @@ public function setOptions($options) $options = new MemcachedOptions($options); } - $this->options = $options; - - // Set memcached options, using options map to map to Memcached constants - $map = $options->getOptionsMap(); - foreach ($options->toArray() as $key => $value) { - if (!array_key_exists($key, $map)) { - // skip keys for which there are not equivalent options - continue; - } - $this->memcached->setOption($map[$key], $value); - } - - return $this; + return parent::setOptions($options); } /** diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index 266d7d990..a9f91cdcc 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -37,35 +37,6 @@ class MemcachedOptions extends AdapterOptions { - /** - * Map of option keys to \Memcached options - * - * @var array - */ - private $optionsMap = array( - 'binary_protocol' => MemcachedResource::OPT_BINARY_PROTOCOL, - 'buffer_writes' => MemcachedResource::OPT_BUFFER_WRITES, - //'cache_lookups' => MemcachedResource::OPT_CACHE_LOOKUPS, - 'compression' => MemcachedResource::OPT_COMPRESSION, - 'connect_timeout' => MemcachedResource::OPT_CONNECT_TIMEOUT, - 'distribution' => MemcachedResource::OPT_DISTRIBUTION, - 'hash' => MemcachedResource::OPT_HASH, - 'libketama_compatible' => MemcachedResource::OPT_LIBKETAMA_COMPATIBLE, - 'no_block' => MemcachedResource::OPT_NO_BLOCK, - 'poll_timeout' => MemcachedResource::OPT_POLL_TIMEOUT, - 'recv_timeout' => MemcachedResource::OPT_RECV_TIMEOUT, - //'retry_timeout' => MemcachedResource::OPT_RETRY_TIMEOUT, - 'send_timeout' => MemcachedResource::OPT_SEND_TIMEOUT, - 'serializer' => MemcachedResource::OPT_SERIALIZER, - //'server_failure_limit' => MemcachedResource::OPT_SERVER_FAILURE_LIMIT, - 'socket_recv_size' => MemcachedResource::OPT_SOCKET_RECV_SIZE, - 'socket_send_size' => MemcachedResource::OPT_SOCKET_SEND_SIZE, - 'tcp_nodelay' => MemcachedResource::OPT_TCP_NODELAY, - - // The prefix_key act as namespace an will be set directly - // 'prefix_key' => MemcachedResource::OPT_PREFIX_KEY, - ); - /** * Memcached server address * @@ -74,130 +45,11 @@ class MemcachedOptions extends AdapterOptions protected $servers = array(); /** - * Whether or not to enable binary protocol for communication with server + * Libmemcached options * - * @var bool - */ - protected $binaryProtocol = false; - - /** - * Enable or disable buffered I/O - * - * @var bool - */ - protected $bufferWrites = false; - - /** - * Whether or not to cache DNS lookups - * - * @var bool - */ - protected $cacheLookups = false; - - /** - * Whether or not to use compression - * - * @var bool - */ - protected $compression = true; - - /** - * Time at which to issue connection timeout, in ms - * - * @var int - */ - protected $connectTimeout = 1000; - - /** - * Server distribution algorithm - * - * @var int - */ - protected $distribution = MemcachedResource::DISTRIBUTION_MODULA; - - /** - * Hashing algorithm to use - * - * @var int - */ - protected $hash = MemcachedResource::HASH_DEFAULT; - - /** - * Whether or not to enable compatibility with libketama-like behavior. - * - * @var bool - */ - protected $libketamaCompatible = false; - - /** - * Whether or not to enable asynchronous I/O - * - * @var bool - */ - protected $noBlock = false; - - /** - * Timeout for connection polling, in ms - * - * @var int - */ - protected $pollTimeout = 1000; - - /** - * Maximum allowed time for a recv operation, in ms - * - * @var int - */ - protected $recvTimeout = 0; - - /** - * Time to wait before retrying a connection, in seconds - * - * @var int - */ - protected $retryTimeout = 0; - - /** - * Maximum allowed time for a send operation, in ms - * - * @var int - */ - protected $sendTimeout = 0; - - /** - * Serializer to use - * - * @var int - */ - protected $serializer = MemcachedResource::SERIALIZER_PHP; - - /** - * Maximum number of server connection errors - * - * @var int - */ - protected $serverFailureLimit = 0; - - /** - * Maximum socket send buffer in bytes - * - * @var int - */ - protected $socketSendSize; - - /** - * Maximum socket recv buffer in bytes - * - * @var int - */ - protected $socketRecvSize; - - /** - * Whether or not to enable no-delay feature for connecting sockets - * - * @var bool + * @var array */ - protected $tcpNodelay = false; + protected $libOptions = array(); /** * Set namespace. @@ -241,12 +93,9 @@ public function addServer($host, $port = 11211) )); } - if ((!is_int($port) && !is_numeric($port)) - || 0 > $port - ) { + if (!is_numeric($port) || $port <= 0) { throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ + '%s expects a positive integer', __METHOD__ )); } @@ -274,6 +123,7 @@ public function setServers(array $servers) $this->addServer($server[0], $server[1]); } } + return $this; } @@ -288,580 +138,86 @@ public function getServers() } /** - * Get overwrittern libmemcached options - * - * @return array - */ - public function getLibOptions() - { - return $this->libOptions; - } - - /** - * Set flag indicating whether or not to enable binary protocol for - * communication with server - * - * @param bool $binaryProtocol - * @return MemcachedOptions - */ - public function setBinaryProtocol($binaryProtocol) - { - $this->binaryProtocol = (bool) $binaryProtocol; - return $this; - } - - /** - * Whether or not to enable binary protocol for communication with server - * - * @return bool - */ - public function getBinaryProtocol() - { - return $this->binaryProtocol; - } - - /** - * Set flag indicating whether or not buffered I/O is enabled + * Set libmemcached options * - * @param bool $bufferWrites + * @param array $libOptions * @return MemcachedOptions + * @link http://php.net/manual/memcached.constants.php */ - public function setBufferWrites($bufferWrites) + public function setLibOptions(array $libOptions) { - $this->bufferWrites = (bool) $bufferWrites; - return $this; - } - - /** - * Whether or not buffered I/O is enabled - * - * @return bool - */ - public function getBufferWrites() - { - return $this->bufferWrites; - } - - /** - * Set flag indicating whether or not to cache DNS lookups - * - * @param bool $cacheLookups - * @return MemcachedOptions - */ - public function setCacheLookups($cacheLookups) - { - $this->cacheLookups = (bool) $cacheLookups; - return $this; - } - - /** - * Whether or not to cache DNS lookups - * - * @return bool - */ - public function getCacheLookups() - { - return $this->cacheLookups; - } - - /** - * Set flag indicating whether or not to use compression - * - * @param bool $compression - * @return MemcachedOptions - */ - public function setCompression($compression) - { - $this->compression = (bool) $compression; - return $this; - } - - /** - * Whether or not compression is enabled - * - * @return bool - */ - public function getCompression() - { - return $this->compression; - } - - /** - * Set interval for connection timeouts, in ms - * - * @param int $connectTimeout - * @return MemcachedOptions - */ - public function setConnectTimeout($connectTimeout) - { - if ((!is_int($connectTimeout) && !is_numeric($connectTimeout)) - || 0 > $connectTimeout - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); + $normalizedOptions = array(); + foreach ($libOptions as $key => $value) { + $this->normalizeLibOptionKey($key); + $normalizedOptions[$key] = $value; } - $this->connectTimeout = (int) $connectTimeout; - return $this; - } - - /** - * Get connection timeout value - * - * @return int - */ - public function getConnectTimeout() - { - return $this->connectTimeout; - } - - /** - * Set server distribution algorithm - * - * @param int $distribution - * @return MemcachedOptions - */ - public function setDistribution($distribution) - { - if (!in_array($distribution, array( - MemcachedResource::DISTRIBUTION_MODULA, - MemcachedResource::DISTRIBUTION_CONSISTENT, - ))) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects either Memcached::DISTRIBUTION_MODULA or Memcached::DISTRIBUTION_CONSISTENT', - __METHOD__ - )); - } + $this->triggerOptionEvent('lib_options', $normalizedOptions); + $this->libOptions = array_merge($this->libOptions, $normalizedOptions); - $this->distribution = $distribution; return $this; } /** - * Get server distribution algorithm - * - * @return int - */ - public function getDistribution() - { - return $this->distribution; - } - - /** - * Set hashing algorithm + * Set libmemcached option * - * @param int $hash + * @param string|int $key + * @param mixed $value * @return MemcachedOptions + * @link http://php.net/manual/memcached.constants.php */ - public function setHash($hash) - { - if (!in_array($hash, array( - MemcachedResource::HASH_DEFAULT, - MemcachedResource::HASH_MD5, - MemcachedResource::HASH_CRC, - MemcachedResource::HASH_FNV1_64, - MemcachedResource::HASH_FNV1A_64, - MemcachedResource::HASH_FNV1_32, - MemcachedResource::HASH_FNV1A_32, - MemcachedResource::HASH_HSIEH, - MemcachedResource::HASH_MURMUR, - ))) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects one of the Memcached::HASH_* constants', - __METHOD__ - )); - } - - $this->hash = $hash; - return $this; - } - - /** - * Get hash algorithm - * - * @return int - */ - public function getHash() + public function setLibOption($key, $value) { - return $this->hash; - } + $this->normalizeLibOptionKey($key); + $this->triggerOptionEvent('lib_options', array($key, $value)); + $this->libOptions[$key] = $value; - /** - * Set flag indicating whether or not to enable libketama compatibility - * - * @param bool $libketamaCompatible - * @return MemcachedOptions - */ - public function setLibketamaCompatible($libketamaCompatible) - { - $this->libketamaCompatible = (bool) $libketamaCompatible; return $this; } /** - * Whether or not to enable libketama compatibility - * - * @return bool - */ - public function getLibketamaCompatible() - { - return $this->libketamaCompatible; - } - - /** - * Set flag indicating whether or not to enable asynchronous I/O + * Get libmemcached options * - * @param bool $noBlock - * @return MemcachedOptions - */ - public function setNoBlock($noBlock) - { - $this->noBlock = (bool) $noBlock; - return $this; - } - - /** - * Whether or not to enable asynchronous I/O - * - * @return bool - */ - public function getNoBlock() - { - return $this->noBlock; - } - - /** - * Set interval for connection polling timeout, in ms - * - * @param int $pollTimeout - * @return MemcachedOptions - */ - public function setPollTimeout($pollTimeout) - { - if ((!is_int($pollTimeout) && !is_numeric($pollTimeout)) - || 0 > $pollTimeout - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); - } - - $this->pollTimeout = (int) $pollTimeout; - return $this; - } - - /** - * Get connection polling timeout value - * - * @return int - */ - public function getPollTimeout() - { - return $this->pollTimeout; - } - - /** - * Set prefix for keys - * - * The prefix key act as namespace. - * - * @param string $prefixKey - * @return MemcachedOptions - */ - public function setPrefixKey($prefixKey) - { - return $this->setNamespace($prefixKey); - } - - /** - * Get prefix key - * - * The prefix key act as namespace. - * - * @return string - */ - public function getPrefixKey() - { - return $this->getNamespace(); - } - - /** - * Set interval for recv timeout, in ms - * - * @param int $recvTimeout - * @return MemcachedOptions - */ - public function setRecvTimeout($recvTimeout) - { - if ((!is_int($recvTimeout) && !is_numeric($recvTimeout)) - || 0 > $recvTimeout - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); - } - - $this->recvTimeout = (int) $recvTimeout; - return $this; - } - - /** - * Get recv timeout value - * - * @return int - */ - public function getRecvTimeout() - { - return $this->recvTimeout; - } - - /** - * Set retry interval, in seconds - * - * @param int $retryTimeout - * @return MemcachedOptions - */ - public function setRetryTimeout($retryTimeout) - { - if ((!is_int($retryTimeout) && !is_numeric($retryTimeout)) - || 0 > $retryTimeout - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); - } - - $this->retryTimeout = (int) $retryTimeout; - return $this; - } - - /** - * Get retry timeout value, in seconds - * - * @return int + * @return array + * @link http://php.net/manual/memcached.constants.php */ - public function getRetryTimeout() + public function getLibOptions() { - return $this->retryTimeout; + return $this->libOptions; } /** - * Set interval for send timeout, in ms + * Get libmemcached option * - * @param int $sendTimeout - * @return MemcachedOptions + * @return mixed + * @link http://php.net/manual/memcached.constants.php */ - public function setSendTimeout($sendTimeout) + public function getLibOption($key) { - if ((!is_int($sendTimeout) && !is_numeric($sendTimeout)) - || 0 > $sendTimeout - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); + $this->normalizeLibOptionKey($key); + if (isset($this->libOptions[$key])) { + return $this->libOptions[$key]; } - - $this->sendTimeout = (int) $sendTimeout; - return $this; - } - - /** - * Get send timeout value - * - * @return int - */ - public function getSendTimeout() - { - return $this->sendTimeout; + return null; } /** - * Set serializer + * Normalize libmemcached option name into it's constant value * - * @param int $serializer - * @return MemcachedOptions + * @param string|int $key + * @throws Exception\InvalidArgumentException */ - public function setSerializer($serializer) + protected function normalizeLibOptionKey(& $key) { - if (!in_array($serializer, array( - MemcachedResource::SERIALIZER_PHP, - MemcachedResource::SERIALIZER_IGBINARY, - MemcachedResource::SERIALIZER_JSON, - ))) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects one of the Memcached::SERIALIZER_* constants', - __METHOD__ - )); - } - - if ($serializer == MemcachedResource::SERIALIZER_IGBINARY) { - if (!MemcachedResource::HAVE_IGBINARY) { - throw new Exception\RuntimeException(sprintf( - '%s: cannot set to igbinary; not available', - __METHOD__ - )); - } - } - - if ($serializer == MemcachedResource::SERIALIZER_JSON) { - if (!MemcachedResource::HAVE_JSON) { - throw new Exception\RuntimeException(sprintf( - '%s: cannot set to json; not available', - __METHOD__ - )); + if (is_string($key)) { + $const = 'Memcached::OPT_' . str_replace(array(' ', '-'), '_', strtoupper($key)); + if (!defined($const)) { + throw new Exception\InvalidArgumentException("Unknown libmemcached option '{$key}' ({$const})"); } + $key = constant($const); + } else { + $key = (int) $key; } - - $this->serializer = $serializer; - return $this; - } - - /** - * Get serializer - * - * @return int - */ - public function getSerializer() - { - return $this->serializer; - } - - /** - * Set maximum number of server connection failures - * - * @param int $serverFailureLimit - * @return MemcachedOptions - */ - public function setServerFailureLimit($serverFailureLimit) - { - if ((!is_int($serverFailureLimit) && !is_numeric($serverFailureLimit)) - || 0 > $serverFailureLimit - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); - } - - $this->serverFailureLimit = (int) $serverFailureLimit; - return $this; - } - - /** - * Get maximum server failures allowed - * - * @return int - */ - public function getServerFailureLimit() - { - return $this->serverFailureLimit; - } - - /** - * Set maximum socket send buffer in bytes - * - * @param int $socketSendSize - * @return MemcachedOptions - */ - public function setSocketSendSize($socketSendSize) - { - if ($socketSendSize === null) { - return $this; - } - - if ((!is_int($socketSendSize) && !is_numeric($socketSendSize)) - || 0 > $socketSendSize - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); - } - - $this->socketSendSize = (int) $socketSendSize; - return $this; - } - - /** - * Get maximum socket send buffer in bytes - * - * @return int - */ - public function getSocketSendSize() - { - return $this->socketSendSize; - } - - /** - * Set maximum socket recv buffer in bytes - * - * @param int $socketRecvSize - * @return MemcachedOptions - */ - public function setSocketRecvSize($socketRecvSize) - { - if ($socketRecvSize === null) { - return $this; - } - - if ((!is_int($socketRecvSize) && !is_numeric($socketRecvSize)) - || 0 > $socketRecvSize - ) { - throw new Exception\InvalidArgumentException(sprintf( - '%s expects a positive integer', - __METHOD__ - )); - } - - $this->socketRecvSize = (int) $socketRecvSize; - return $this; - } - - /** - * Get maximum socket recv buffer in bytes - * - * @return int - */ - public function getSocketRecvSize() - { - return $this->socketRecvSize; - } - - /** - * Set whether or not to enable no-delay feature when connecting sockets - * - * @param bool $tcpNodelay - * @return MemcachedOptions - */ - public function setTcpNodelay($tcpNodelay) - { - $this->tcpNodelay = (bool) $tcpNodelay; - return $this; } - /** - * Whether or not to enable no-delay feature when connecting sockets - * - * @return bool - */ - public function getTcpNodelay() - { - return $this->tcpNodelay; - } - - /** - * Get map of option keys to \Memcached constants - * - * @return array - */ - public function getOptionsMap() - { - return $this->optionsMap; - } } From 227a0ed641d87d2ce486ecd46262e186eee56024 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 22 Mar 2012 23:34:05 +0100 Subject: [PATCH 225/311] make sure the 'option' event will be triggered on setOptions --- src/Storage/Adapter/Apc.php | 3 +-- src/Storage/Adapter/Memory.php | 3 +-- src/Storage/Adapter/WinCache.php | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index bb9748091..463749706 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -122,8 +122,7 @@ public function setOptions($options) $options = new ApcOptions($options); } - $this->options = $options; - return $this; + return parent::setOptions($options); } /** diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 38a4983a1..9a6fd2f71 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -68,8 +68,7 @@ public function setOptions($options) $options = new MemoryOptions($options); } - $this->options = $options; - return $this; + return parent::setOptions($options); } /** diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index a92bb637a..1f88d78b9 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -85,8 +85,7 @@ public function setOptions($options) $options = new WinCacheOptions($options); } - $this->options = $options; - return $this; + return parent::setOptions($options); } /** From 21327efe5b6aa6cf6309fdea13b99315fab5e25c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 22 Mar 2012 23:41:37 +0100 Subject: [PATCH 226/311] Cache adapter: allow empty namespaces --- src/Storage/Adapter/AbstractAdapter.php | 8 +++----- src/Storage/Adapter/AdapterOptions.php | 5 ----- src/Storage/Adapter/MemcachedOptions.php | 2 +- test/Storage/Adapter/AbstractAdapterTest.php | 6 ------ 4 files changed, 4 insertions(+), 17 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 31ad92f76..b1d0eefd9 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -2554,12 +2554,10 @@ protected function normalizeTtl(&$ttl) protected function normalizeNamespace(&$namespace) { $namespace = (string) $namespace; - - if ($namespace === '') { - throw new Exception\InvalidArgumentException('Empty namespaces are not allowed'); - } elseif (($p = $this->getOptions()->getNamespacePattern()) && !preg_match($p, $namespace)) { + $pattern = $this->getOptions()->getNamespacePattern(); + if ($pattern && !preg_match($pattern, $namespace)) { throw new Exception\InvalidArgumentException( - "The namespace '{$namespace}' doesn't match against pattern '{$p}'" + "The namespace '{$namespace}' doesn't match against pattern '{$pattern}'" ); } } diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 508ed1be7..9eb49f184 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -208,11 +208,6 @@ public function setNamespace($namespace) { $namespace = (string)$namespace; if ($this->namespace !== $namespace) { - if ($namespace === '') { - // TODO: allow empty namespaces - throw new Exception\InvalidArgumentException('No namespace given'); - } - $pattern = $this->getNamespacePattern(); if ($pattern && !preg_match($pattern, $namespace)) { throw new Exception\InvalidArgumentException( diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index a9f91cdcc..e04271ede 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -62,7 +62,7 @@ class MemcachedOptions extends AdapterOptions */ public function setNamespace($namespace) { - $namespace = (string)$namespace; + $namespace = (string) $namespace; if (128 < strlen($namespace)) { throw new Exception\InvalidArgumentException(sprintf( diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index e1ed301c4..722719324 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -123,12 +123,6 @@ public function testSetNamespace0() $this->assertSame('0', $this->_options->getNamespace()); } - public function testSetEmptyNamespaceThrowsException() - { - $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_options->setNamespace(''); - } - public function testSetNamespacePatternThrowsExceptionOnInvalidPattern() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); From 277bf167a9469def65e22af55c7e9e55e6fc5afe Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 26 Mar 2012 21:01:40 +0200 Subject: [PATCH 227/311] fixed missing reset of umask --- src/Storage/Adapter/Filesystem.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index d7d253a09..1957feea1 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -650,6 +650,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz $mkdir = mkdir($path, 0777, true); $error = ErrorHandler::stop(); if (!$mkdir) { + umask($oldUmask); throw new Exception\RuntimeException( "Error creating directory '{$path}'", 0, $error ); @@ -673,7 +674,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz } try { - if ($oldUmask !== null) { // $oldUmask could be defined on set directory_umask + if ($oldUmask !== null) { // $oldUmask could be defined on create directory umask($baseOptions->getFileUmask()); } else { $oldUmask = umask($baseOptions->getFileUmask()); From 6828829faf918566bfb161611a98b3f04a2bb7e7 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 26 Mar 2012 21:52:06 +0200 Subject: [PATCH 228/311] removed internal method getKeyInfo: now getFilespec will be buffered and please use internalHasItem instead --- src/Storage/Adapter/Filesystem.php | 199 +++++++++++++---------------- 1 file changed, 88 insertions(+), 111 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 1957feea1..883fb2ad5 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -55,20 +55,18 @@ class Filesystem extends AbstractAdapter protected $stmtMatch = null; /** - * Last buffered identified of internal method getKeyInfo() + * Key (namespace + separator + key) of buffered information * * @var string|null */ - protected $lastInfoId = null; + protected $bufferKey = null; /** - * Buffered result of internal method getKeyInfo() + * The buffered filespec * - * @var array|null + * @var string|null */ - protected $lastInfo = null; - - /* configuration */ + protected $bufferedFilespec = null; /** * Set options. @@ -178,24 +176,23 @@ public function getItems(array $keys, array $options = array()) */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) { - if ( !$this->internalHasItem($normalizedKey, $normalizedOptions) - || !($keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace'])) - ) { - if ($normalizedOptions['ignore_missing_items']) { - return false; - } else { + if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$normalizedOptions['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$normalizedKey}' not found within namespace '{$normalizedOptions['namespace']}'" ); } + + return false; } - $baseOptions = $this->getOptions(); try { - $data = $this->getFileContent($keyInfo['filespec'] . '.dat'); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $baseOptions = $this->getOptions(); + $data = $this->getFileContent($filespec . '.dat'); if ($baseOptions->getReadControl()) { - if ( ($info = $this->readInfoFile($keyInfo['filespec'] . '.ifo')) + if ( ($info = $this->readInfoFile($filespec . '.ifo')) && isset($info['hash'], $info['algo']) && Utils::generateHash($info['algo'], $data, true) != $info['hash'] ) { @@ -207,7 +204,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) if (array_key_exists('token', $normalizedOptions)) { // use filemtime + filesize as CAS token - $normalizedOptions['token'] = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); + $normalizedOptions['token'] = filemtime($filespec . '.dat') . filesize($filespec . '.dat'); } return $data; @@ -250,14 +247,13 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized // read items foreach ($normalizedKeys as $i => $normalizedKey) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions) - || !($keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace'])) - ) { + if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { unset($normalizedKeys[$i]); continue; } - $data = $this->getFileContent($keyInfo['filespec'] . '.dat', $wouldblock); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $data = $this->getFileContent($filespec . '.dat', $wouldblock); if ($data === false) { continue; } else { @@ -265,7 +261,7 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized } if ($baseOptions->getReadControl()) { - $info = $this->readInfoFile($keyInfo['filespec'] . '.ifo'); + $info = $this->readInfoFile($filespec . '.ifo'); if (isset($info['hash'], $info['algo']) && Utils::generateHash($info['algo'], $data, true) != $info['hash'] ) { @@ -359,17 +355,29 @@ public function hasItems(array $keys, array $options = array()) */ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) { - $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); - if (!$keyInfo) { - return false; // missing or corrupted cache data + $ttl = $normalizedOptions['ttl']; + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + + if (!file_exists($filespec . '.dat')) { + return false; } - $ttl = $normalizedOptions['ttl']; - if (!$ttl || time() < ($keyInfo['mtime'] + $ttl)) { - return true; + if ($ttl) { + ErrorHandler::start(); + $mtime = filemtime($filespec . '.dat'); + $error = ErrorHandler::stop(); + if (!$mtime) { + throw new Exception\RuntimeException( + "Error getting mtime of file '{$filespec}.dat'", 0, $error + ); + } + + if (time() >= ($mtime + $ttl)) { + return false; + } } - return false; + return true; } /** @@ -416,31 +424,36 @@ public function getMetadatas(array $keys, array $options = array()) */ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { - $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); - if (!$keyInfo) { + if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { if (!$normalizedOptions['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$normalizedKey}' not found on namespace '{$normalizedOptions['namespace']}'" ); } + return false; } $baseOptions = $this->getOptions(); - if (!$baseOptions->getNoCtime()) { - $keyInfo['ctime'] = filectime($keyInfo['filespec'] . '.dat'); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + + $metadata = $this->readInfoFile($filespec . '.ifo'); + if (!$metadata) { + $metadata = array(); } - if (!$baseOptions->getNoAtime()) { - $keyInfo['atime'] = fileatime($keyInfo['filespec'] . '.dat'); + $metadata['filespec'] = $filespec; + $metadata['mtime'] = filemtime($filespec . '.dat'); + + if (!$baseOptions->getNoCtime()) { + $metadata['ctime'] = filectime($filespec . '.dat'); } - $info = $this->readInfoFile($keyInfo['filespec'] . '.ifo'); - if ($info) { - return $keyInfo + $info; + if (!$baseOptions->getNoAtime()) { + $metadata['atime'] = fileatime($filespec . '.dat'); } - return $keyInfo; + return $metadata; } /* writing */ @@ -636,12 +649,12 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz $baseOptions = $this->getOptions(); $oldUmask = null; - $lastInfoId = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator() . $normalizedKey; - if ($this->lastInfoId == $lastInfoId) { + $bufferKey = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator() . $normalizedKey; + if ($this->bufferKey == $bufferKey) { $filespec = $this->lastInfo['filespec']; // if lastKeyInfo is available I'm sure that the cache directory exist } else { - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions['namespace']); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); if ($baseOptions->getDirLevel() > 0) { $path = dirname($filespec); if (!file_exists($path)) { @@ -691,7 +704,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz } } - $this->lastInfoId = null; + $this->bufferKey = null; // reset file_umask umask($oldUmask); @@ -758,18 +771,19 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) */ protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) { - $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); - if (!$keyInfo) { + if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { if (!$normalizedOptions['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$normalizedKey}' not found within namespace '{$normalizedOptions['namespace']}'" ); } + return false; } // use filemtime + filesize as CAS token - $check = $keyInfo['mtime'] . filesize($keyInfo['filespec'] . '.dat'); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $check = filemtime($filespec . '.dat') . filesize($filespec . '.dat'); if ($token !== $check) { return false; } @@ -845,27 +859,29 @@ public function touchItems(array $keys, array $options = array()) */ protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) { - $keyInfo = $this->getKeyInfo($normalizedKey, $normalizedOptions['namespace']); - if (!$keyInfo) { + if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { if (!$normalizedOptions['ignore_missing_items']) { throw new Exception\ItemNotFoundException( "Key '{$normalizedKey}' not found within namespace '{$normalizedOptions['namespace']}'" ); } + return false; } + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + ErrorHandler::start(); - $touch = touch($keyInfo['filespec'] . '.dat'); + $touch = touch($filespec . '.dat'); $error = ErrorHandler::stop(); if (!$touch) { throw new Exception\RuntimeException( - "Error touching file '{$keyInfo['filespec']}.dat'", 0, $error + "Error touching file '{$filespec}.dat'", 0, $error ); } // remove the buffered info - $this->lastInfoId = null; + $this->bufferKey = null; return true; } @@ -942,7 +958,7 @@ public function removeItems(array $keys, array $options = array()) */ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions['namespace']); + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); if (!file_exists($filespec . '.dat')) { if (!$normalizedOptions['ignore_missing_items']) { throw new Exception\ItemNotFoundException("Key '{$normalizedKey}' with file '{$filespec}.dat' not found"); @@ -950,7 +966,7 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio } else { $this->unlink($filespec . '.dat'); $this->unlink($filespec . '.ifo'); - $this->lastInfoId = null; + $this->bufferKey = null; } return true; } @@ -1431,73 +1447,34 @@ protected function rmDir($dir, $prefix) return $ret; } - /** - * Get an array of information about the cache key. - * NOTE: returns false if cache doesn't hit. - * - * @param string $key - * @param string $ns - * @return array|boolean - */ - protected function getKeyInfo($key, $ns) - { - $lastInfoId = $ns . $this->getOptions()->getNamespaceSeparator() . $key; - if ($this->lastInfoId == $lastInfoId) { - return $this->lastInfo; - } - - $filespec = $this->getFileSpec($key, $ns); - $file = $filespec . '.dat'; - - if (!file_exists($file)) { - return false; - } - - ErrorHandler::start(); - $mtime = filemtime($file); - $error = ErrorHandler::stop(); - if (!$mtime) { - throw new Exception\RuntimeException( - "Error getting mtime of file '{$file}'", 0, $error - ); - } - - $this->lastInfoId = $lastInfoId; - $this->lastInfo = array( - 'filespec' => $filespec, - 'mtime' => $mtime, - ); - - return $this->lastInfo; - } - /** * Get file spec of the given key and namespace * - * @param string $key - * @param string $ns + * @param string $normalizedKey + * @param array $normalizedOptions * @return string */ - protected function getFileSpec($key, $ns) + protected function getFileSpec($normalizedKey, array & $normalizedOptions) { - $options = $this->getOptions(); - $prefix = $ns . $options->getNamespaceSeparator(); - $lastInfoId = $prefix . $key; - if ($this->lastInfoId == $lastInfoId) { - return $this->lastInfo['filespec']; - } - - $path = $options->getCacheDir(); - $level = $options->getDirLevel(); - if ( $level > 0 ) { - // create up to 256 directories per directory level - $hash = md5($key); - for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { - $path .= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; + $baseOptions = $this->getOptions(); + $prefix = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator(); + $bufferKey = $prefix . $normalizedKey; + + if ($this->bufferKey !== $bufferKey) { + $path = $baseOptions->getCacheDir(); + $level = $baseOptions->getDirLevel(); + if ( $level > 0 ) { + // create up to 256 directories per directory level + $hash = md5($normalizedKey); + for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { + $path .= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; + } } + + $this->bufferedFilespec = $path . \DIRECTORY_SEPARATOR . $prefix . $normalizedKey; } - return $path . \DIRECTORY_SEPARATOR . $prefix . $key; + return $this->bufferedFilespec; } /** From deb3fe27044f4fa75679f0442f0ef1eaadc2fa3d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 26 Mar 2012 23:08:41 +0200 Subject: [PATCH 229/311] It's not sure that a cache directory exists after getting filespec --- src/Storage/Adapter/Filesystem.php | 34 ++++++++++++------------------ 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 883fb2ad5..7fd1e6faf 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -647,27 +647,21 @@ public function replaceItems(array $keyValuePairs, array $options = array()) protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { $baseOptions = $this->getOptions(); - $oldUmask = null; + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $oldUmask = null; - $bufferKey = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator() . $normalizedKey; - if ($this->bufferKey == $bufferKey) { - $filespec = $this->lastInfo['filespec']; - // if lastKeyInfo is available I'm sure that the cache directory exist - } else { - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - if ($baseOptions->getDirLevel() > 0) { - $path = dirname($filespec); - if (!file_exists($path)) { - $oldUmask = umask($baseOptions->getDirUmask()); - ErrorHandler::start(); - $mkdir = mkdir($path, 0777, true); - $error = ErrorHandler::stop(); - if (!$mkdir) { - umask($oldUmask); - throw new Exception\RuntimeException( - "Error creating directory '{$path}'", 0, $error - ); - } + if ($baseOptions->getDirLevel() > 0) { + $path = dirname($filespec); + if (!file_exists($path)) { + $oldUmask = umask($baseOptions->getDirUmask()); + ErrorHandler::start(); + $mkdir = mkdir($path, 0777, true); + $error = ErrorHandler::stop(); + if (!$mkdir) { + umask($oldUmask); + throw new Exception\RuntimeException( + "Error creating directory '{$path}'", 0, $error + ); } } } From f462b4aab8216cdc32e117fa0585849d8079ba23 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 26 Mar 2012 23:12:28 +0200 Subject: [PATCH 230/311] added missing flock(LOCK_UN) & fclose on error --- src/Storage/Adapter/Filesystem.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 7fd1e6faf..afdf6c8e1 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1606,12 +1606,15 @@ protected function putFileContent($file, $data) } if (!fwrite($fp, $data)) { + flock($fp, \LOCK_UN); fclose($fp); $err = ErrorHandler::stop(); throw new Exception\RuntimeException("Error writing file '{$file}'", 0, $err); } if (!ftruncate($fp, strlen($data))) { + flock($fp, \LOCK_UN); + fclose($fp); $err = ErrorHandler::stop(); throw new Exception\RuntimeException("Error truncating file '{$file}'", 0, $err); } From d4b75e85e6e172f36fc9aafecd1858286dd4c656 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 26 Mar 2012 23:33:48 +0200 Subject: [PATCH 231/311] removed option 'file_blocking' because skipping writing data if the file is locked would only make sense if the file is blocked by another process writing the file (LOCK_EX) but it is also blocked on readers (LOCK_SH) --- src/Storage/Adapter/Filesystem.php | 22 +++++--- src/Storage/Adapter/FilesystemOptions.php | 49 ---------------- test/Storage/Adapter/FilesystemTest.php | 69 ----------------------- 3 files changed, 13 insertions(+), 127 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index afdf6c8e1..5962b7170 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1573,20 +1573,21 @@ protected function getFileContent($file, $wouldblock = false) /** * Write content to a file * - * @param string $file File complete path - * @param string $data Data to write - * @return bool + * @param string $file File complete path + * @param string $data Data to write + * @param boolean $wouldblock Return FALSE if the lock would block + * @return boolean TRUE on success, FALSE if lock would block * @throws Exception\RuntimeException */ - protected function putFileContent($file, $data) + protected function putFileContent($file, $data, $wouldblock = false) { - $options = $this->getOptions(); - $locking = $options->getFileLocking(); - $blocking = $locking ? $options->getFileBlocking() : false; + $locking = $this->getOptions()->getFileLocking(); + $wouldblock = $locking && $wouldblock; ErrorHandler::start(); - if ($locking && !$blocking) { + // file_put_contents can't used + if ($locking && $wouldblock) { $fp = fopen($file, 'cb'); if (!$fp) { $err = ErrorHandler::stop(); @@ -1595,11 +1596,12 @@ protected function putFileContent($file, $data) ); } + $wouldblock = null; if(!flock($fp, \LOCK_EX | \LOCK_NB, $wouldblock)) { fclose($fp); $err = ErrorHandler::stop(); if ($wouldblock) { - throw new Exception\LockedException("File '{$file}' locked", 0, $err); + return false; } else { throw new Exception\RuntimeException("Error locking file '{$file}'", 0, $err); } @@ -1621,6 +1623,8 @@ protected function putFileContent($file, $data) flock($fp, \LOCK_UN); fclose($fp); + + // file_put_contents can be used } else { $flags = 0; if ($locking) { diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index ce20ad9c7..d69ca3bc1 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -65,17 +65,6 @@ class FilesystemOptions extends AdapterOptions */ protected $dirUmask = 0007; - /** - * Block writing files until writing by another process finished. - * - * NOTE: this only attempts if fileLocking is enabled - * NOTE: if disabled writing operations can throw a LockedException - * NOTE: This option can't be disabled on windows - * - * @var boolean - */ - protected $fileBlocking = true; - /** * Lock files on writing * @@ -304,44 +293,6 @@ public function getDirUmask() return $this->dirUmask; } - /** - * Set block writing files until writing by another process finished. - * - * NOTE: this only attempts if fileLocking is enabled - * NOTE: if disabled writing operations can throw a LockedException - * NOTE: This option can't be disabled on windows - * - * @param bool $flag - * @return FilesystemOptions - */ - public function setFileBlocking($flag) - { - $flag = (bool) $flag; - if (!$flag && substr(\PHP_OS, 0, 3) == 'WIN') { - throw new Exception\InvalidArgumentException( - "This option can't be disabled on windows" - ); - } - - $this->triggerOptionEvent('file_blocking', $flag); - $this->fileBlocking = $flag; - return $this; - } - - /** - * Get block writing files until writing by another process finished. - * - * NOTE: this only attempts if fileLocking is enabled - * NOTE: if disabled writing operations can throw a LockedException - * NOTE: This option can't be disabled on windows - * - * @return bool - */ - public function getFileBlocking() - { - return $this->fileBlocking; - } - /** * Set file locking * diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 2c96244bf..879f8b82b 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -262,75 +262,6 @@ public function testSetReadControlAlgoInvalidException() $this->_options->setReadControlAlgo('unknown'); } - public function testDisabledFileBlocking() - { - if (substr(\PHP_OS, 0, 3) == 'WIN') { - $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - } - - $this->_options->setFileLocking(true); - $this->_options->setFileBlocking(false); - - // create cache item and get data file - $this->assertTrue($this->_storage->setItem('key', 'value')); - $meta = $this->_storage->getMetadata('key'); - $this->assertInternalType('array', $meta); - $this->assertArrayHasKey('filespec', $meta); - $file = $meta['filespec'] . '.dat'; - - /****************** - * first test with exclusive lock - */ - - // open file and create a lock - $fp = @fopen($file, 'cb'); - $this->assertInternalType('resource', $fp); - flock($fp, LOCK_EX); - - // rewriting file should fail in part of open lock - try { - $this->_storage->setItem('key', 'lock'); - - // close - flock($fp, LOCK_UN); - fclose($fp); - - $this->fail('Missing expected exception Zend\Cache\Exception\LockedException'); - } catch (\Zend\Cache\Exception\LockedException $e) { - // expected exception was thrown - - // close - flock($fp, LOCK_UN); - fclose($fp); - } - - /****************** - * second test with shared lock - */ - - // open file and create a lock - $fp = @fopen($file, 'rb'); - $this->assertInternalType('resource', $fp); - flock($fp, LOCK_SH); - - // rewriting file should fail in part of open lock - try { - $this->_storage->setItem('key', 'lock'); - - // close - flock($fp, LOCK_UN); - fclose($fp); - - $this->fail('Missing expected exception Zend\Cache\Exception\LockedException'); - } catch (\Zend\Cache\Exception\LockedException $e) { - // expected exception was thrown - - // close - flock($fp, LOCK_UN); - fclose($fp); - } - } - public function testGetMetadataWithCtime() { $this->_options->setNoCtime(false); From af2a849cb33fb78bb2e14bab87199495151ea2ef Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 26 Mar 2012 23:37:13 +0200 Subject: [PATCH 232/311] The method unlink don't need to check if the file exists because it's already checked before and on error it will also be checked before throwing an exception --- src/Storage/Adapter/Filesystem.php | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 5962b7170..45c1041ca 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1653,11 +1653,6 @@ protected function putFileContent($file, $data, $wouldblock = false) */ protected function unlink($file) { - // If file does not exist, nothing to do - if (!file_exists($file)) { - return; - } - ErrorHandler::start(); $res = unlink($file); $err = ErrorHandler::stop(); From 0eab73b76b8ee2f1f32aec7d6146d2a8f50840f3 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 29 Mar 2012 08:16:24 +0200 Subject: [PATCH 233/311] Cache filesystem adapter: - no need to buffer filespec generation - implement $wouldblock argument by reference - optimized internalGetMetadatas with non blocking - optimized single writes with non blocking if *.dat AND *.ifo file have to be written --- src/Storage/Adapter/Filesystem.php | 225 ++++++++++++++++++----------- 1 file changed, 141 insertions(+), 84 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 45c1041ca..213dae8fc 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -54,20 +54,6 @@ class Filesystem extends AbstractAdapter */ protected $stmtMatch = null; - /** - * Key (namespace + separator + key) of buffered information - * - * @var string|null - */ - protected $bufferKey = null; - - /** - * The buffered filespec - * - * @var string|null - */ - protected $bufferedFilespec = null; - /** * Set options. * @@ -239,25 +225,30 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized { $baseOptions = $this->getOptions(); + // Don't change arguments passed by reference + $keys = $normalizedKeys; + $options = $normalizedOptions; + $result = array(); - while (true) { + while ($keys) { // LOCK_NB if more than one items have to read - $wouldblock = count($normalizedKeys) > 1; + $nonBlocking = count($keys) > 1; + $wouldblock = null; // read items - foreach ($normalizedKeys as $i => $normalizedKey) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { - unset($normalizedKeys[$i]); + foreach ($keys as $i => $key) { + if (!$this->internalHasItem($key, $options)) { + unset($keys[$i]); continue; } - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - $data = $this->getFileContent($filespec . '.dat', $wouldblock); - if ($data === false) { + $filespec = $this->getFileSpec($key, $options); + $data = $this->getFileContent($filespec . '.dat', $nonBlocking, $wouldblock); + if ($nonBlocking && $wouldblock) { continue; } else { - unset($normalizedKeys[$i]); + unset($keys[$i]); } if ($baseOptions->getReadControl()) { @@ -271,13 +262,11 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized } } - $result[$normalizedKey] = $data; + $result[$key] = $data; } - // no more items to read - if (!$normalizedKeys) { - break; - } + // Don't check ttl after first iteration + $options['ttl'] = 0; } return $result; @@ -456,6 +445,72 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti return $metadata; } + /** + * Internal method to get multiple metadata + * + * Options: + * - ttl + * - The time-to-life + * - namespace + * - The namespace to use + * + * @param array $normalizedKeys + * @param array $normalizedOptions + * @return array Associative array of existing cache ids and its metadata + * @throws Exception + */ + protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + { + $baseOptions = $this->getOptions(); + $result = array(); + + // Don't change arguments passed by reference + $keys = $normalizedKeys; + $options = $normalizedOptions; + + while ($keys) { + + // LOCK_NB if more than one items have to read + $nonBlocking = count($keys) > 1; + $wouldblock = null; + + foreach ($keys as $i => $key) { + if (!$this->internalHasItem($key, $options)) { + unset($keys[$i]); + continue; + } + + $filespec = $this->getFileSpec($key, $options); + + $metadata = $this->readInfoFile($filespec . '.ifo', $nonBlocking, $wouldblock); + if ($nonBlocking && $wouldblock) { + continue; + } elseif (!$metadata) { + $metadata = array(); + } + + $metadata['filespec'] = $filespec; + $metadata['mtime'] = filemtime($filespec . '.dat'); + + if (!$baseOptions->getNoCtime()) { + $metadata['ctime'] = filectime($filespec . '.dat'); + } + + if (!$baseOptions->getNoAtime()) { + $metadata['atime'] = fileatime($filespec . '.dat'); + } + + $result[$key] = $metadata; + unset($keys[$i]); + } + + // Don't check ttl after first iteration + $options['ttl'] = 0; + } + + return $result; + } + /* writing */ /** @@ -687,23 +742,29 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz $oldUmask = umask($baseOptions->getFileUmask()); } - $ret = $this->putFileContent($filespec . '.dat', $value); - if ($ret && $info) { - // Don't throw exception if writing of info file failed - // -> only return false - try { - $ret = $this->putFileContent($filespec . '.ifo', serialize($info)); - } catch (Exception\RuntimeException $e) { - $ret = false; - } + $contents = array($filespec . '.dat' => $value); + if ($info) { + $contents[$filespec . '.ifo'] = serialize($info); + } else { + $this->unlink($filespec . '.ifo'); } - $this->bufferKey = null; + while ($contents) { + $nonBlocking = count($contents) > 1; + $wouldblock = null; + + foreach ($contents as $file => $content) { + $this->putFileContent($file, $content, $nonBlocking, $wouldblock); + if (!$nonBlocking || !$wouldblock) { + unset($contents[$file]); + } + } + } // reset file_umask umask($oldUmask); - return $ret; + return true; } catch (Exception $e) { // reset umask on exception @@ -874,9 +935,6 @@ protected function internalTouchItem(& $normalizedKey, array & $normalizedOption ); } - // remove the buffered info - $this->bufferKey = null; - return true; } @@ -960,7 +1018,6 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio } else { $this->unlink($filespec . '.dat'); $this->unlink($filespec . '.ifo'); - $this->bufferKey = null; } return true; } @@ -1452,39 +1509,39 @@ protected function getFileSpec($normalizedKey, array & $normalizedOptions) { $baseOptions = $this->getOptions(); $prefix = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator(); - $bufferKey = $prefix . $normalizedKey; - - if ($this->bufferKey !== $bufferKey) { - $path = $baseOptions->getCacheDir(); - $level = $baseOptions->getDirLevel(); - if ( $level > 0 ) { - // create up to 256 directories per directory level - $hash = md5($normalizedKey); - for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { - $path .= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; - } - } - $this->bufferedFilespec = $path . \DIRECTORY_SEPARATOR . $prefix . $normalizedKey; + $path = $baseOptions->getCacheDir(); + $level = $baseOptions->getDirLevel(); + if ( $level > 0 ) { + // create up to 256 directories per directory level + $hash = md5($normalizedKey); + for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { + $path .= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; + } } - return $this->bufferedFilespec; + return $path . \DIRECTORY_SEPARATOR . $prefix . $normalizedKey; } /** * Read info file * - * @param string $file + * @param string $file + * @param boolean $nonBlocking Don't block script if file is locked + * @param boolean $wouldblock The optional argument is set to TRUE if the lock would block * @return array|boolean The info array or false if file wasn't found * @throws Exception\RuntimeException */ - protected function readInfoFile($file) + protected function readInfoFile($file, $nonBlocking = false, & $wouldblock = null) { if (!file_exists($file)) { return false; } - $content = $this->getFileContent($file); + $content = $this->getFileContent($file, $nonBlocking, $wouldblock); + if ($nonBlocking && $wouldblock) { + return false; + } ErrorHandler::start(); $ifo = unserialize($content); @@ -1501,14 +1558,16 @@ protected function readInfoFile($file) /** * Read a complete file * - * @param string $file File complete path - * @param boolean $wouldblock Return FALSE if the lock would block - * @return string|boolean + * @param string $file File complete path + * @param boolean $nonBlocking Don't block script if file is locked + * @param boolean $wouldblock The optional argument is set to TRUE if the lock would block + * @return string * @throws Exception\RuntimeException */ - protected function getFileContent($file, $wouldblock = false) + protected function getFileContent($file, $nonBlocking = false, & $wouldblock = null) { - $locking = $this->getOptions()->getFileLocking(); + $locking = $this->getOptions()->getFileLocking(); + $wouldblock = null; ErrorHandler::start(); @@ -1522,13 +1581,12 @@ protected function getFileContent($file, $wouldblock = false) ); } - if ($wouldblock) { - $wouldblock = null; + if ($nonBlocking) { $lock = flock($fp, \LOCK_SH | \LOCK_NB, $wouldblock); if ($wouldblock) { fclose($fp); ErrorHandler::stop(); - return false; + return; } } else { $lock = flock($fp, \LOCK_SH); @@ -1573,21 +1631,23 @@ protected function getFileContent($file, $wouldblock = false) /** * Write content to a file * - * @param string $file File complete path - * @param string $data Data to write - * @param boolean $wouldblock Return FALSE if the lock would block - * @return boolean TRUE on success, FALSE if lock would block + * @param string $file File complete path + * @param string $data Data to write + * @param boolean $nonBlocking Don't block script if file is locked + * @param boolean $wouldblock The optional argument is set to TRUE if the lock would block + * @return void * @throws Exception\RuntimeException */ - protected function putFileContent($file, $data, $wouldblock = false) + protected function putFileContent($file, $data, $nonBlocking = false, & $wouldblock = null) { - $locking = $this->getOptions()->getFileLocking(); - $wouldblock = $locking && $wouldblock; + $locking = $this->getOptions()->getFileLocking(); + $nonBlocking = $locking && $nonBlocking; + $wouldblock = null; ErrorHandler::start(); - // file_put_contents can't used - if ($locking && $wouldblock) { + // if locking and non blocking is enabled -> file_put_contents can't used + if ($locking && $nonBlocking) { $fp = fopen($file, 'cb'); if (!$fp) { $err = ErrorHandler::stop(); @@ -1596,12 +1656,11 @@ protected function putFileContent($file, $data, $wouldblock = false) ); } - $wouldblock = null; if(!flock($fp, \LOCK_EX | \LOCK_NB, $wouldblock)) { fclose($fp); $err = ErrorHandler::stop(); if ($wouldblock) { - return false; + return; } else { throw new Exception\RuntimeException("Error locking file '{$file}'", 0, $err); } @@ -1624,24 +1683,22 @@ protected function putFileContent($file, $data, $wouldblock = false) flock($fp, \LOCK_UN); fclose($fp); - // file_put_contents can be used + // else -> file_put_contents can be used } else { $flags = 0; if ($locking) { $flags = $flags | \LOCK_EX; } - $bytes = strlen($data); - if (file_put_contents($file, $data, $flags) !== $bytes) { + if (file_put_contents($file, $data, $flags) === false) { $err = ErrorHandler::stop(); throw new Exception\RuntimeException( - "Error putting {$bytes} bytes to file '{$file}'", 0, $err + "Error writing file '{$file}'", 0, $err ); } } ErrorHandler::stop(); - return true; } /** From 0f8bfc4e91b8f2c736f4fa662ad73f18b2793277 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 29 Mar 2012 21:12:57 +0200 Subject: [PATCH 234/311] optimized writing multiple items of filesystem adapter using non blocking locks --- src/Storage/Adapter/Filesystem.php | 108 ++++++++++++++++++++++++++--- 1 file changed, 99 insertions(+), 9 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 213dae8fc..294139c63 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -702,8 +702,8 @@ public function replaceItems(array $keyValuePairs, array $options = array()) protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { $baseOptions = $this->getOptions(); - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); $oldUmask = null; + $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); if ($baseOptions->getDirLevel() > 0) { $path = dirname($filespec); @@ -726,23 +726,20 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz $info['hash'] = Utils::generateHash($baseOptions->getReadControlAlgo(), $value, true); $info['algo'] = $baseOptions->getReadControlAlgo(); } - - if (isset($options['tags']) && $normalizedOptions['tags']) { - $tags = $normalizedOptions['tags']; - if (!is_array($tags)) { - $tags = array($tags); - } - $info['tags'] = array_values(array_unique($tags)); + if (isset($options['tags'])) { + $info['tags'] = $normalizedOptions['tags']; } + // write files try { + // set umask for files if ($oldUmask !== null) { // $oldUmask could be defined on create directory umask($baseOptions->getFileUmask()); } else { $oldUmask = umask($baseOptions->getFileUmask()); } - $contents = array($filespec . '.dat' => $value); + $contents = array($filespec . '.dat' => & $value); if ($info) { $contents[$filespec . '.ifo'] = serialize($info); } else { @@ -773,6 +770,99 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz } } + /** + * Internal method to store multiple items. + * + * Options: + * - namespace + * - The namespace to use + * - tags + * - An array of tags + * + * @param array $normalizedKeyValuePairs + * @param array $normalizedOptions + * @return boolean + * @throws Exception + */ + protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + { + $baseOptions = $this->getOptions(); + $oldUmask = null; + + // create an associated array of files and contents to write + $contents = array(); + foreach ($normalizedKeyValuePairs as $key => & $value) { + $filespec = $this->getFileSpec($key, $normalizedOptions); + + // init directory level + if ($baseOptions->getDirLevel() > 0) { + $path = dirname($filespec); + if (!file_exists($path)) { + $oldUmask = ($oldUmask === null) ? umask($baseOptions->getDirUmask()) : $oldUmask; + ErrorHandler::start(); + $mkdir = mkdir($path, 0777, true); + $error = ErrorHandler::stop(); + if (!$mkdir) { + umask($oldUmask); + throw new Exception\RuntimeException( + "Error creating directory '{$path}'", 0, $error + ); + } + } + } + + // *.dat file + $contents[$filespec . '.dat'] = & $value; + + // *.ifo file + $info = null; + if ($baseOptions->getReadControl()) { + $info['hash'] = Utils::generateHash($baseOptions->getReadControlAlgo(), $value, true); + $info['algo'] = $baseOptions->getReadControlAlgo(); + } + if (isset($normalizedOptions['tags'])) { + $info['tags'] = & $normalizedOptions['tags']; + } + if ($info) { + $contents[$filespec . '.ifo'] = serialize($info); + } else { + $this->unlink($filespec . '.ifo'); + } + } + + // write to disk + try { + // set umask for files + if ($oldUmask !== null) { // $oldUmask could be defined on create directory + umask($baseOptions->getFileUmask()); + } else { + $oldUmask = umask($baseOptions->getFileUmask()); + } + + while ($contents) { + $nonBlocking = count($contents) > 1; + $wouldblock = null; + + foreach ($contents as $file => & $content) { + $this->putFileContent($file, $content, $nonBlocking, $wouldblock); + if (!$nonBlocking || !$wouldblock) { + unset($contents[$file]); + } + } + } + + // reset umask + umask($oldUmask); + + return true; + + } catch (Exception $e) { + // reset umask on exception + umask($oldUmask); + throw $e; + } + } + /** * Set an item only if token matches * From 46afe3b5e09fc27647e8b85b16f4343e917f39ff Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 6 Apr 2012 21:15:08 +0200 Subject: [PATCH 235/311] re-implemented a buffer of the last used filespec --- src/Storage/Adapter/Filesystem.php | 36 ++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 294139c63..fe8448c59 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -54,6 +54,21 @@ class Filesystem extends AbstractAdapter */ protected $stmtMatch = null; + /** + * An identity for the last filespec + * (cache directory + namespace prefix + key + directory level) + * + * @var string + */ + protected $lastFileSpecId = ''; + + /** + * The last used filespec + * + * @var string + */ + protected $lastFileSpec = ''; + /** * Set options. * @@ -1600,17 +1615,24 @@ protected function getFileSpec($normalizedKey, array & $normalizedOptions) $baseOptions = $this->getOptions(); $prefix = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator(); - $path = $baseOptions->getCacheDir(); + $path = $baseOptions->getCacheDir() . \DIRECTORY_SEPARATOR; $level = $baseOptions->getDirLevel(); - if ( $level > 0 ) { - // create up to 256 directories per directory level - $hash = md5($normalizedKey); - for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { - $path .= \DIRECTORY_SEPARATOR . $prefix . $hash[$i] . $hash[$i+1]; + + $fileSpecId = $path . $prefix . $normalizedKey . '/' . $level; + if ($this->lastFileSpecId !== $fileSpecId) { + if ($level > 0) { + // create up to 256 directories per directory level + $hash = md5($normalizedKey); + for ($i = 0, $max = ($level * 2); $i < $max; $i+= 2) { + $path .= $prefix . $hash[$i] . $hash[$i+1] . \DIRECTORY_SEPARATOR; + } } + + $this->lastFileSpecId = $fileSpecId; + $this->lastFileSpec = $path . $prefix . $normalizedKey; } - return $path . \DIRECTORY_SEPARATOR . $prefix . $normalizedKey; + return $this->lastFileSpec; } /** From 4dad11ee4cdbf3a6ea890494aab506bc79fd2981 Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Wed, 4 Apr 2012 00:27:17 +0200 Subject: [PATCH 236/311] Adding shell script to run tests It iterates over tested components and runs phpunit for each of them --- .travis/run-tests.sh | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .travis/run-tests.sh diff --git a/.travis/run-tests.sh b/.travis/run-tests.sh new file mode 100644 index 000000000..47d0c4a07 --- /dev/null +++ b/.travis/run-tests.sh @@ -0,0 +1,8 @@ +#!/bin/bash +travisdir=$(dirname $(readlink /proc/$$/fd/255)) +testdir="$travisdir/../tests" +testedcomponents=(`cat "$travisdir/tested-components"`) + +for tested in "${testedcomponents[@]}" + do phpunit -c $testdir/phpunit.xml $testdir/$tested +done From 775902341fd11e313983f4c630a3be796c19bbf9 Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Wed, 4 Apr 2012 00:29:10 +0200 Subject: [PATCH 237/311] Adding script used to configure the test suite --- .travis/TestConfiguration.php | 825 ++++++++++++++++++++++++++++++++++ 1 file changed, 825 insertions(+) create mode 100644 .travis/TestConfiguration.php diff --git a/.travis/TestConfiguration.php b/.travis/TestConfiguration.php new file mode 100644 index 000000000..fd8947049 --- /dev/null +++ b/.travis/TestConfiguration.php @@ -0,0 +1,825 @@ + test disabling output buffering in + * dispatcher + */ +defined('TESTS_ZEND_CONTROLLER_DISPATCHER_OB') || define('TESTS_ZEND_CONTROLLER_DISPATCHER_OB', false); + +/** + * Zend_Crypt related constantes + * + * TESTS_ZEND_CRYPT_OPENSSL_CONF => location of an openssl.cnf file for use + * with RSA encryption + */ +defined('TESTS_ZEND_CRYPT_OPENSSL_CONF') || define('TESTS_ZEND_CRYPT_OPENSSL_CONF', false); + +/** + * Zend_Db_Adapter_Pdo_Mysql and Zend_Db_Adapter_Mysqli + * + * There are separate properties to enable tests for the PDO_MYSQL adapter and + * the native Mysqli adapters, but the other properties are shared between the + * two MySQL-related Zend_Db adapters. + */ +defined('TESTS_ZEND_DB_ADAPTER_PDO_MYSQL_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_MYSQL_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_MYSQLI_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_MYSQLI_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_MYSQL_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_HOSTNAME', '127.0.0.1'); +defined('TESTS_ZEND_DB_ADAPTER_MYSQL_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_USERNAME', null); +defined('TESTS_ZEND_DB_ADAPTER_MYSQL_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_PASSWORD', null); +defined('TESTS_ZEND_DB_ADAPTER_MYSQL_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_DATABASE', 'test'); +defined('TESTS_ZEND_DB_ADAPTER_MYSQL_PORT') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_PORT', 3306); + +/** + * Zend_Db_Adapter_Pdo_Sqlite + * + * Username and password are irrelevant for SQLite. + */ +defined('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_DATABASE', ':memory:'); + +/** + * Zend_Db_Adapter_Pdo_Mssql + * + * Note that you need to patch your ntwdblib.dll, the one that + * comes with PHP does not work. See user comments at + * http://us2.php.net/manual/en/ref.mssql.php + */ +defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_HOSTNAME', '127.0.0.1'); +defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_USERNAME', null); +defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_PASSWORD', null); +defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_DATABASE', 'test'); + +/** + * Zend_Db_Adapter_Pdo_Pgsql + */ +defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_HOSTNAME', '127.0.0.1'); +defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_USERNAME', null); +defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_PASSWORD', null); +defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_DATABASE', 'postgres'); + +/** + * Zend_Db_Adapter_Oracle and Zend_Db_Adapter_Pdo_Oci + * + * There are separate properties to enable tests for the PDO_OCI adapter and + * the native Oracle adapter, but the other properties are shared between the + * two Oracle-related Zend_Db adapters. + */ +defined('TESTS_ZEND_DB_ADAPTER_PDO_OCI_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_OCI_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_ORACLE_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_ORACLE_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_HOSTNAME', '127.0.0.1'); +defined('TESTS_ZEND_DB_ADAPTER_ORACLE_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_USERNAME', null); +defined('TESTS_ZEND_DB_ADAPTER_ORACLE_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_PASSWORD', null); +defined('TESTS_ZEND_DB_ADAPTER_ORACLE_SID') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_SID', 'xe'); + +/** + * Zend_Db_Adapter_Db2 and Zend_Db_Adapter_Pdo_Ibm + * There are separate properties to enable tests for the PDO_IBM adapter and + * the native DB2 adapter, but the other properties are shared between the + * two related Zend_Db adapters. + */ +defined('TESTS_ZEND_DB_ADAPTER_PDO_IBM_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_IBM_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_DB2_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_DB2_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_DB2_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_DB2_HOSTNAME', '127.0.0.1'); +defined('TESTS_ZEND_DB_ADAPTER_DB2_PORT') || define('TESTS_ZEND_DB_ADAPTER_DB2_PORT', 50000); +defined('TESTS_ZEND_DB_ADAPTER_DB2_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_DB2_USERNAME', null); +defined('TESTS_ZEND_DB_ADAPTER_DB2_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_DB2_PASSWORD', null); +defined('TESTS_ZEND_DB_ADAPTER_DB2_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_DB2_DATABASE', 'sample'); + +/** + * Zend_Db_Adapter_Sqlsrv + * Note: Make sure that you create the "test" database and set a + * username and password + * + */ +defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_ENABLED', false); +defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_HOSTNAME', 'localhost\SQLEXPRESS'); +defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_USERNAME', null); +defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_PASSWORD', null); +defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_DATABASE', 'test'); + +/** + * Zend_Feed_Reader tests + * + * If the ONLINE_ENABLED property is false, only tests that can be executed + * without network connectivity are run; when enabled, all tests will run. + */ +defined('TESTS_ZEND_FEED_READER_ONLINE_ENABLED') || define('TESTS_ZEND_FEED_READER_ONLINE_ENABLED', false); + +/** + * Zend_Gdata tests + * + * If the ONLINE_ENABLED property is false, only tests that can be executed with + * a mock HTTP client are run. No request is sent to the Google Gdata servers. + * If ONLINE_ENABLED is true, some tests may make requests to the remote + * servers. This does not work if you are running tests on a disconnected + * client host. Also, the tests may show as failures if the Google servers + * cannot be reached or if they do not respond for another reason. + * + * If the CLIENTLOGIN_ENABLED property below is false, the authenticated + * tests are reported Skipped in the test run. Set this property to true + * to enable tests that require ClientLogin authentication. Enter your + * Google login credentials in the EMAIL and PASSWORD properties below. + * + * Edit TestConfiguration.php, not TestConfiguration.php.dist. + * Never commit plaintext passwords to the source code repository. + * + * Note: the GData tests currently require that the TZID env variable + * be set or the timezone otherwise configured. You'll see errors from the + * tests if this is not the case. + */ +defined('TESTS_ZEND_GDATA_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_ONLINE_ENABLED', false); +defined('TESTS_ZEND_GDATA_CLIENTLOGIN_ENABLED') || define('TESTS_ZEND_GDATA_CLIENTLOGIN_ENABLED', false); + +/* + * The credentials provided here should be only for a TEST account. + * Data for various services in this account may be added to, updated, + * or deleted based upon the actions of these test accounts. + */ +defined('TESTS_ZEND_GDATA_CLIENTLOGIN_EMAIL') || define('TESTS_ZEND_GDATA_CLIENTLOGIN_EMAIL', 'example@example.com'); +defined('TESTS_ZEND_GDATA_CLIENTLOGIN_PASSWORD') || define('TESTS_ZEND_GDATA_CLIENTLOGIN_PASSWORD', 'password'); + +/* + * This is the ID of a blank blog. There is no need to have + * any content in this blog. Also, blogs can only be used + * several times for the purpose of these test cases before + * they must be deleted and recreated. Otherwise, the tests + * will start failing, as posts to Blogger will return a 201 Created + * response even though the entry was not posted to the blog. + * This problem is being investigated. + */ +defined('TESTS_ZEND_GDATA_BLOGGER_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_BLOGGER_ONLINE_ENABLED', false); +defined('TESTS_ZEND_GDATA_BLOG_ID') || define('TESTS_ZEND_GDATA_BLOG_ID', '1111111111111111111'); + +/* + * This is the key for a spreadsheet with data only in the first row of + * the spreadsheet. The strings 'a1', 'b1', 'c1', 'd1' should be in the + * corresponding cell locations. + */ +defined('TESTS_ZEND_GDATA_SPREADSHEETS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_SPREADSHEETS_ONLINE_ENABLED', false); +defined('TESTS_ZEND_GDATA_SPREADSHEETS_SPREADSHEETKEY') || define('TESTS_ZEND_GDATA_SPREADSHEETS_SPREADSHEETKEY', 'o01111111111111111111.1111111111111111111'); +defined('TESTS_ZEND_GDATA_SPREADSHEETS_WORKSHEETID') || define('TESTS_ZEND_GDATA_SPREADSHEETS_WORKSHEETID', 'default'); + +/* + * This indicates that online tests for the Google Calendar API should + * be performed. The default calendar will be used. + */ +defined('TESTS_ZEND_GDATA_CALENDAR_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_CALENDAR_ONLINE_ENABLED', false); + +/* + * This is the fully-qualified domain name for a domiain hosted using + * Google Apps. This domain must be registered with Google Apps and + * have API access enabled. This should be a TEST domain only. + */ +defined('TESTS_ZEND_GDATA_GAPPS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_GAPPS_ONLINE_ENABLED', false); +defined('TESTS_ZEND_GDATA_GAPPS_DOMAIN') || define('TESTS_ZEND_GDATA_GAPPS_DOMAIN', 'example.com.invalid'); +defined('TESTS_ZEND_GDATA_GAPPS_EMAIL') || define('TESTS_ZEND_GDATA_GAPPS_EMAIL', 'example@example.com'); +defined('TESTS_ZEND_GDATA_GAPPS_PASSWORD') || define('TESTS_ZEND_GDATA_GAPPS_PASSWORD', 'password'); + +/* + * This is the ONLINE_ENABLED property for Google Base. + */ +defined('TESTS_ZEND_GDATA_GBASE_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_GBASE_ONLINE_ENABLED', false); + +/* + * This indicates that online tests for the Books Search data API + * should be performed. + */ +defined('TESTS_ZEND_GDATA_BOOKS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_BOOKS_ONLINE_ENABLED', false); + +/* + * This indicates that online tests for the YouTube data API should + * be performed. + */ +defined('TESTS_ZEND_GDATA_YOUTUBE_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_YOUTUBE_ONLINE_ENABLED', false); + +/* + * This is the username to use for retrieving subscriptions, etc + */ +defined('TESTS_ZEND_GDATA_YOUTUBE_ACCOUNT') || define('TESTS_ZEND_GDATA_YOUTUBE_ACCOUNT', 'zfgdata'); + +/* + * This is the developer key to access the YouTube API + */ +defined('TESTS_ZEND_GDATA_YOUTUBE_DEVELOPER_KEY') || define('TESTS_ZEND_GDATA_YOUTUBE_DEVELOPER_KEY', 'your_developer_key_here'); + +/* + * This is the client ID to access the YouTube API + */ +defined('TESTS_ZEND_GDATA_YOUTUBE_CLIENT_ID') || define('TESTS_ZEND_GDATA_YOUTUBE_CLIENT_ID', 'ZF_UnitTests_unknown'); + +/* + * This indicates that online tests for the Google Documents API should + * be performed. + */ +defined('TESTS_ZEND_GDATA_DOCS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_DOCS_ONLINE_ENABLED', false); + +/* + * This indicates that online tests for the GData Photos API should + * be performed. + */ +defined('TESTS_ZEND_GDATA_PHOTOS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_PHOTOS_ONLINE_ENABLED', false); + +/* + * This indicates that online tests for the Google Health API should + * be performed. + */ +defined('TESTS_ZEND_GDATA_HEALTH_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_HEALTH_ONLINE_ENABLED', false); + +/** + * Zend_Http_Client tests + * + * To enable the dynamic Zend_Http_Client tests, you will need to symbolically + * link or copy the files in tests/Zend/Http/Client/_files to a directory + * under your web server(s) document root and set this constant to point to the + * URL of this directory. + */ +defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') || define('TESTS_ZEND_HTTP_CLIENT_BASEURI', false); + +/** + * Zend_Http_Client_Proxy tests + * + * HTTP proxy to be used for testing the Proxy adapter. Set to a string of + * the form 'host:port'. Set to null to skip HTTP proxy tests. + */ +defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY') || define('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY', false); +defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_USER') || define('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_USER', ''); +defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_PASS') || define('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_PASS', ''); + +/** + * Zend_Loader_Autoloader multi-version support tests + * + * ENABLED: whether or not to run the multi-version tests + * PATH: path to a directory containing multiple ZF version installs + * LATEST: most recent ZF version in the PATH + * e.g., "1.9.2" + * LATEST_MAJOR: most recent ZF major version in the PATH to test against + * e.g., "1.9.2" + * LATEST_MINOR: most recent ZF minor version in the PATH to test against + * e.g., "1.8.4PL1" + * SPECIFIC: specific ZF version in the PATH to test against + * e.g., "1.7.6" + * As an example, consider the following tree: + * ZendFramework/ + * |-- 1.9.2 + * |-- ZendFramework-1.9.1-minimal + * |-- 1.8.4PL1 + * |-- 1.8.4 + * |-- ZendFramework-1.8.3 + * |-- 1.7.8 + * |-- 1.7.7 + * |-- 1.7.6 + * You would then set the value of "LATEST" and "LATEST_MAJOR" to "1.9.2", and + * could choose between "1.9.2", "1.8.4PL1", and "1.7.8" for "LATEST_MINOR", + * and any version number for "SPECIFIC". "PATH" would point to the parent + * "ZendFramework" directory. + */ +defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_ENABLED') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_ENABLED', false); +defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_PATH') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_PATH', false); +defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST', false); +defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MAJOR') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MAJOR', false); +defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MINOR') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MINOR', false); +defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_SPECIFIC') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_SPECIFIC', false); + +/** + * Zend_Ldap online tests + */ +defined('TESTS_ZEND_LDAP_ONLINE_ENABLED') || define('TESTS_ZEND_LDAP_ONLINE_ENABLED', false); + +/* These largely map to the options described in the Zend_Ldap and + * Zend_Auth_Adapter_Ldap documentation. + * + * Example Configuration for Active Directory: + * HOST: dc1.w.net + * USE_START_TLS: true + * USE_SSL: false + * USERNAME: CN=User 1,CN=Users,DC=w,DC=net + * PRINCIPAL_NAME: user1@w.net + * LDAP_PASSWORD: pass1 + * BASE_DN: CN=Users,DC=w,DC=net + * DOMAIN_NAME: w.net + * ACCOUNT_DOMAIN_NAME_SHORT: W + * ALT_USERNAME: user2 + * ALT_DN: CN=User 2,CN=Users,DC=w,DC=net + * ALT_PASSWORD: pass2 + * + * Example Configuration for OpenLDAP + * HOST: s0.foo.net + * USERNAME: CN=user1,DC=foo,DC=net + * PRINCIPAL_NAME: user1@foo.net + * LDAP_PASSWORD: pass1 + * BIND_REQUIRES_DN: true + * BASE_DN: OU=Sales,DC=w,DC=net + * DOMAIN_NAME: foo.net + * ACCOUNT_DOMAIN_NAME_SHORT: FOO + * ALT_USERNAME: abaker + * ALT_DN: CN=Alice Baker,OU=Sales,DC=foo,DC=net + * ALT_PASSWORD: apass + */ +defined('TESTS_ZEND_LDAP_HOST') || define('TESTS_ZEND_LDAP_HOST', 'localhost'); +//defined('TESTS_ZEND_LDAP_PORT') || define('TESTS_ZEND_LDAP_PORT', 389); +defined('TESTS_ZEND_LDAP_USE_START_TLS') || define('TESTS_ZEND_LDAP_USE_START_TLS', true); +//defined('TESTS_ZEND_LDAP_USE_SSL') || define('TESTS_ZEND_LDAP_USE_SSL', false); +defined('TESTS_ZEND_LDAP_USERNAME') || define('TESTS_ZEND_LDAP_USERNAME', 'CN=someUser,DC=example,DC=com'); +defined('TESTS_ZEND_LDAP_PRINCIPAL_NAME') || define('TESTS_ZEND_LDAP_PRINCIPAL_NAME', 'someUser@example.com'); +defined('TESTS_ZEND_LDAP_PASSWORD') || define('TESTS_ZEND_LDAP_PASSWORD', null); +defined('TESTS_ZEND_LDAP_BIND_REQUIRES_DN') || define('TESTS_ZEND_LDAP_BIND_REQUIRES_DN', true); +defined('TESTS_ZEND_LDAP_BASE_DN') || define('TESTS_ZEND_LDAP_BASE_DN', 'OU=Sales,DC=example,DC=com'); +//defined('TESTS_ZEND_LDAP_ACCOUNT_FILTER_FORMAT') || define('TESTS_ZEND_LDAP_ACCOUNT_FILTER_FORMAT', '(&(objectClass=posixAccount)(uid=%s))'); +defined('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME') || define('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME', 'example.com'); +defined('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME_SHORT') || define('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME_SHORT', 'EXAMPLE'); +defined('TESTS_ZEND_LDAP_ALT_USERNAME') || define('TESTS_ZEND_LDAP_ALT_USERNAME', 'anotherUser'); +defined('TESTS_ZEND_LDAP_ALT_DN') || define('TESTS_ZEND_LDAP_ALT_DN', 'CN=Another User,OU=Sales,DC=example,DC=com'); +defined('TESTS_ZEND_LDAP_ALT_PASSWORD') || define('TESTS_ZEND_LDAP_ALT_PASSWORD', null); // Used in Zend_Auth_Adapter_Ldap tests +//(defined('TESTS_ZEND_LDAP_WRITEABLE_SUBTREE') || define('TESTS_ZEND_LDAP_WRITEABLE_SUBTREE', 'OU=Test,OU=Sales,DC=example,DC=com'); + +/** + * Zend_Locale tests + * + * If the TESTS_ZEND_LOCALE_FORMAT_SETLOCALE property below is a valid, + * locally recognized locale (try "locale -a"), then all tests in + * tests/Zend/Locale/ test suites will execute *after* + * setlocale(LC_ALL, TESTS_ZEND_LOCALE_FORMAT_SETLOCALE); + * Primarily, this switches certain PHP functions to emit "localized" output, + * including the built-in "to string" for integer and float conversions. + * Thus, a locale of 'fr_FR' yields number-to-string conversions in a + * localized form with the decimal place separator chosen via: + * setlocale(LC_ALL, 'fr_FR@euro'); + */ +//define('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE', 'fr'); +//define('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE', 'fr_FR@euro'); +defined('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE') || define('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE', false); + +/** + * Zend_Date tests + * + * If the BCMATH_ENABLED property below is false, all arithmetic + * operations will use ordinary PHP math operators and functions. + * Otherwise, the bcmath functions will be used for unlimited precision. + * + * If the EXTENDED_COVERAGE property below is false, most of the I18N + * unit tests will not be computed... this speeds tests up to 80 minutes + * when doing reports. * + * Edit TestConfiguration.php, not TestConfiguration.php.dist. + */ +defined('TESTS_ZEND_LOCALE_BCMATH_ENABLED') || define('TESTS_ZEND_LOCALE_BCMATH_ENABLED', true); +defined('TESTS_ZEND_I18N_EXTENDED_COVERAGE') || define('TESTS_ZEND_I18N_EXTENDED_COVERAGE', true); + +/** + * Zend_Mail_Storage tests + * + * TESTS_ZEND_MAIL_SERVER_TESTDIR and TESTS_ZEND_MAIL_SERVER_FORMAT are used for POP3 and IMAP tests. + * TESTS_ZEND_MAIL_SERVER_FORMAT is the format your test mail server uses: 'mbox' or 'maildir'. The mail + * storage for the user specified in your POP3 or IMAP tests should be TESTS_ZEND_MAIL_SERVER_TESTDIR. Be + * careful: it's cleared before copying the files. If you want to copy the files manually set the dir + * to null (or anything == null). + * + * TESTS_ZEND_MAIL_TEMPDIR is used for testing write operations in local storages. If not set (== null) + * tempnam() is used. + */ +defined('TESTS_ZEND_MAIL_SERVER_TESTDIR') || define('TESTS_ZEND_MAIL_SERVER_TESTDIR', null); +defined('TESTS_ZEND_MAIL_SERVER_FORMAT') || define('TESTS_ZEND_MAIL_SERVER_FORMAT', 'mbox'); +defined('TESTS_ZEND_MAIL_TEMPDIR') || define('TESTS_ZEND_MAIL_TEMPDIR', null); + +/** + * Zend_Mail_Storage_Pop3 / Zend_Mail_Transport_Pop3 + * + * IMPORTANT: you need to copy tests/Zend/Mail/_files/test.mbox to your mail + * if you haven't set TESTS_ZEND_MAIL_SERVER_TESTDIR + */ +defined('TESTS_ZEND_MAIL_POP3_ENABLED') || define('TESTS_ZEND_MAIL_POP3_ENABLED', false); +defined('TESTS_ZEND_MAIL_POP3_HOST') || define('TESTS_ZEND_MAIL_POP3_HOST', 'localhost'); +defined('TESTS_ZEND_MAIL_POP3_USER') || define('TESTS_ZEND_MAIL_POP3_USER', 'test'); +defined('TESTS_ZEND_MAIL_POP3_PASSWORD') || define('TESTS_ZEND_MAIL_POP3_PASSWORD', ''); +// test SSL connections if enabled in your test server +defined('TESTS_ZEND_MAIL_POP3_SSL') || define('TESTS_ZEND_MAIL_POP3_SSL', true); +defined('TESTS_ZEND_MAIL_POP3_TLS') || define('TESTS_ZEND_MAIL_POP3_TLS', true); +// WRONG_PORT should be an existing server port, +// INVALID_PORT should be a non existing (each on defined host) +defined('TESTS_ZEND_MAIL_POP3_WRONG_PORT') || define('TESTS_ZEND_MAIL_POP3_WRONG_PORT', 80); +defined('TESTS_ZEND_MAIL_POP3_INVALID_PORT') || define('TESTS_ZEND_MAIL_POP3_INVALID_PORT', 3141); + +/** + * Zend_Mail_Storage_Imap / Zend_Mail_Transport_Imap + * + * IMPORTANT: you need to copy tests/Zend/Mail/_files/test.mbox to your mail + * if you haven't set TESTS_ZEND_MAIL_SERVER_TESTDIR + */ +defined('TESTS_ZEND_MAIL_IMAP_ENABLED') || define('TESTS_ZEND_MAIL_IMAP_ENABLED', false); +defined('TESTS_ZEND_MAIL_IMAP_HOST') || define('TESTS_ZEND_MAIL_IMAP_HOST', 'localhost'); +defined('TESTS_ZEND_MAIL_IMAP_USER') || define('TESTS_ZEND_MAIL_IMAP_USER', 'test'); +defined('TESTS_ZEND_MAIL_IMAP_PASSWORD') || define('TESTS_ZEND_MAIL_IMAP_PASSWORD', ''); +// test SSL connections if enabled in your test server +defined('TESTS_ZEND_MAIL_IMAP_SSL') || define('TESTS_ZEND_MAIL_IMAP_SSL', true); +defined('TESTS_ZEND_MAIL_IMAP_TLS') || define('TESTS_ZEND_MAIL_IMAP_TLS', true); +// WRONG_PORT should be an existing server port, +// INVALID_PORT should be a non-existing (each on defined host) +defined('TESTS_ZEND_MAIL_IMAP_WRONG_PORT') || define('TESTS_ZEND_MAIL_IMAP_WRONG_PORT', 80); +defined('TESTS_ZEND_MAIL_IMAP_INVALID_PORT') || define('TESTS_ZEND_MAIL_IMAP_INVALID_PORT', 3141); + + +/** + * Zend_Mail_Storage_Maildir test + * + * Before enabling this test you have to unpack messages.tar in + * Zend/Mail/_files/test.maildir/cur/ and remove the tar for this test to work. + * That's because the messages files have a colon in the filename and that's a + * forbidden character on Windows. + */ +defined('TESTS_ZEND_MAIL_MAILDIR_ENABLED') || define('TESTS_ZEND_MAIL_MAILDIR_ENABLED', false); + +/** + * Zend_Mail_Transport_Smtp + * + * @todo TO be implemented + */ +defined('TESTS_ZEND_MAIL_SMTP_ENABLED') || define('TESTS_ZEND_MAIL_SMTP_ENABLED', false); +defined('TESTS_ZEND_MAIL_SMTP_HOST') || define('TESTS_ZEND_MAIL_SMTP_HOST', 'localhost'); +defined('TESTS_ZEND_MAIL_SMTP_PORT') || define('TESTS_ZEND_MAIL_SMTP_PORT', 25); +defined('TESTS_ZEND_MAIL_SMTP_USER') || define('TESTS_ZEND_MAIL_SMTP_USER', 'testuser'); +defined('TESTS_ZEND_MAIL_SMTP_PASSWORD') || define('TESTS_ZEND_MAIL_SMTP_PASSWORD', 'testpassword'); +defined('TESTS_ZEND_MAIL_SMTP_AUTH') || define('TESTS_ZEND_MAIL_SMTP_AUTH', false); +// AUTH can be set to false or a string of AUTH method (e.g. LOGIN, PLAIN, CRAMMD5 or DIGESTMD5) + +/** + * Zend_Queue Test Configuration constants + * + * The Zend_Queue_Adapter_Db constant should be a JSON-encoded string + * representing a configuration object for Zend_Db::factory(). For example: + * { + * type: "pdo_mysql", + * host: "127.0.0.1", + * port: 3306, + * username: "queue", + * password: "queue", + * dbname: "queue" + * } + * + * The PlatformJobQueue adapter expects two parameters, the host and password. + * The HOST string should include both the host and port (typically 10003): + * 127.0.0.1:10003 + * When running tests against PlatformJobQueue, it's best to do so where + * Platform is installed on localhost and has maximum workers set to 20 + * (default is 5); do so with this zend.ini setting: + * zend_jq.max_num_of_request_workers=20 + * + * Selectively define the below in order to run tests for them. + */ +defined('TESTS_ZEND_QUEUE_ACTIVEMQ_ENABLED') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_ENABLED', false); +defined('TESTS_ZEND_QUEUE_ACTIVEMQ_SCHEME') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_SCHEME', false); +defined('TESTS_ZEND_QUEUE_ACTIVEMQ_HOST') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_HOST', false); +defined('TESTS_ZEND_QUEUE_ACTIVEMQ_PORT') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_PORT', false); +defined('TESTS_ZEND_QUEUE_DB_ENABLED') || define('TESTS_ZEND_QUEUE_DB_ENABLED', false); +defined('TESTS_ZEND_QUEUE_DB') || define('TESTS_ZEND_QUEUE_DB', false); +defined('TESTS_ZEND_QUEUE_MEMCACHEQ_ENABLED') || define('TESTS_ZEND_QUEUE_MEMCACHEQ_ENABLED', false); +defined('TESTS_ZEND_QUEUE_MEMCACHEQ_HOST') || define('TESTS_ZEND_QUEUE_MEMCACHEQ_HOST', false); +defined('TESTS_ZEND_QUEUE_MEMCACHEQ_PORT') || define('TESTS_ZEND_QUEUE_MEMCACHEQ_PORT', false); +defined('TESTS_ZEND_QUEUE_PLATFORMJQ_ENABLED') || define('TESTS_ZEND_QUEUE_PLATFORMJQ_ENABLED', false); +defined('TESTS_ZEND_QUEUE_PLATFORMJQ_HOST') || define('TESTS_ZEND_QUEUE_PLATFORMJQ_HOST', false); +defined('TESTS_ZEND_QUEUE_PLATFORMJQ_PASS') || define('TESTS_ZEND_QUEUE_PLATFORMJQ_PASS', false); + + +/** + * Zend\Service\AgileZen online tests + */ +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_ENABLED',false); +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_APIKEY','insert the API key'); +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_PROJECT_ID','insert the project id'); +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_STORY_ID','insert the story id'); +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_INVITE_EMAIL','insert email for invitation'); +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_INVITE_ROLE_ID','insert role id for invitation'); +define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_MEMBER_NAME','insert the member name to add to the project'); + + +/** + * Zend_Service_Amazon online tests + */ +defined('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ACCESSKEYID') || define('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ACCESSKEYID', 'Enter AWSAccessKeyId here'); +defined('TESTS_ZEND_SERVICE_AMAZON_ONLINE_SECRETKEY') || define('TESTS_ZEND_SERVICE_AMAZON_ONLINE_SECRETKEY', 'Enter AWSSecretKey here'); +defined('TESTS_ZEND_SERVICE_AMAZON_EC2_IMAGE_ID') || define('TESTS_ZEND_SERVICE_AMAZON_EC2_IMAGE_ID', 'zftestamazonimageid'); +defined('TESTS_ZEND_SERVICE_AMAZON_EC2_ZONE') || define('TESTS_ZEND_SERVICE_AMAZON_EC2_ZONE', 'us-east-1'); +defined('TESTS_ZEND_SERVICE_AMAZON_EC2_SECURITY_GROUP') || define('TESTS_ZEND_SERVICE_AMAZON_EC2_SECURITY_GROUP', 'default'); +defined('TESTS_ZEND_SERVICE_AMAZON_S3_BUCKET') || define('TESTS_ZEND_SERVICE_AMAZON_S3_BUCKET', 'zftestamazons3bucket'); +defined('TESTS_ZEND_SERVICE_AMAZON_SQS_QUEUE') || define('TESTS_ZEND_SERVICE_AMAZON_SQS_QUEUE', 'zftestamazonsqsqueuename'); + +/** + * Zend_Service_Delicious tests + */ +defined('TESTS_ZEND_SERVICE_DELICIOUS_ENABLED') || define('TESTS_ZEND_SERVICE_DELICIOUS_ENABLED', false); + +/** + * Zend_Service_DeveloperGarden tests + * Setup your Username and Password to test this Service + */ +defined('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_LOGIN') || define('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_LOGIN', 'ZF_Username'); +defined('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_PASSWORD') || define('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_PASSWORD', 'ZF_Password'); + +/** + * Zend_Service_Flickr online tests + */ +defined('TESTS_ZEND_SERVICE_FLICKR_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_FLICKR_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_FLICKR_ONLINE_APIKEY') || define('TESTS_ZEND_SERVICE_FLICKR_ONLINE_APIKEY', 'Enter API key here'); + +/** + * Zend_Service_GoGrid offline tests + */ + +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_KEY') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_KEY','insert key here'); +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SECRET') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SECRET','insert secret here'); +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_NAME') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_NAME','test-zf'); +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IMAGE') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IMAGE','insert image name here'); +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_RAM') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_RAM','insert ram name here'); +defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IP') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IP','insert ip here'); + +/** + * Zend\Service\LiveDocx configuration + * + * Define username and password in order to run unit tests for LiveDocx web services. + * + * phpunit/phpunit will typically work. + */ +defined('TESTS_ZEND_SERVICE_LIVEDOCX_USERNAME') || define('TESTS_ZEND_SERVICE_LIVEDOCX_USERNAME', false); +defined('TESTS_ZEND_SERVICE_LIVEDOCX_PASSWORD') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PASSWORD', false); + +/** + * Zend\Service\LiveDocx premium configuration + * + * Define username, password, WSDL in order to run unit tests for premium LiveDocx web services. + */ +defined('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_USERNAME') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_USERNAME', false); +defined('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_PASSWORD') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_PASSWORD', false); +defined('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_WSDL') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_WSDL', false); + +/** + * Zend_Service_Rackspace tests + */ +defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_USER') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_USER', 'Enter key here'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_KEY') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_KEY', 'Enter secret here'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_REGION') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_REGION', 'USA'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_CONTAINER_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_CONTAINER_NAME', 'zf-unit-test'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_OBJECT_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_OBJECT_NAME','zf-object-test'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NAME', 'zf-unit-test'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGEID') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGEID', '49'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NEW_IMAGEID') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NEW_IMAGEID', '49'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_FLAVORID') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_FLAVORID', '1'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGE_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGE_NAME', 'ZFunitTestImage'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_SHARED_IP_GROUP_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_SHARED_IP_GROUP_NAME', 'ZFgroupIP'); +defined('TESTS_ZEND_SERVICE_RACKSPACE_TIMEOUT') || define('TESTS_ZEND_SERVICE_RACKSPACE_TIMEOUT', 60); + +/** + * Zend_Service_ReCaptcha tests + */ +defined('TESTS_ZEND_SERVICE_RECAPTCHA_ENABLED') || define('TESTS_ZEND_SERVICE_RECAPTCHA_ENABLED', false); +defined('TESTS_ZEND_SERVICE_RECAPTCHA_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_RECAPTCHA_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_RECAPTCHA_PUBLIC_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_PUBLIC_KEY', 'public key'); +defined('TESTS_ZEND_SERVICE_RECAPTCHA_PRIVATE_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_PRIVATE_KEY', 'private key'); +defined('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PUBLIC_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PUBLIC_KEY', 'public mailhide key'); +defined('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PRIVATE_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PRIVATE_KEY', 'private mailhide key'); + +/** + * Zend_Service_Simpy tests + */ +defined('TESTS_ZEND_SERVICE_SIMPY_ENABLED') || define('TESTS_ZEND_SERVICE_SIMPY_ENABLED', false); +defined('TESTS_ZEND_SERVICE_SIMPY_USERNAME') || define('TESTS_ZEND_SERVICE_SIMPY_USERNAME', 'syapizend'); +defined('TESTS_ZEND_SERVICE_SIMPY_PASSWORD') || define('TESTS_ZEND_SERVICE_SIMPY_PASSWORD', 'mgt37ge'); + +/** + * Zend_Service_SlideShare tests + */ +defined('TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME') || define('TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME', ''); +defined('TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD') || define('TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD', ''); +defined('TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET') || define('TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET', ''); +defined('TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY') || define('TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY', ''); + +// The slide show ID to retrieve during tests +defined('TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID') || define('TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID', 0); + +// The tag to retrieve during tests +defined('TESTS_ZEND_SERVICE_SLIDESHARE_TAG') || define('TESTS_ZEND_SERVICE_SLIDESHARE_TAG', 'zend'); + +// The group to retrieve during tests +defined('TESTS_ZEND_SERVICE_SLIDESHARE_GROUP') || define('TESTS_ZEND_SERVICE_SLIDESHARE_GROUP', ''); + +/** + * Zend_Service_Twitter tests + * + * ONLINE_ENABLED indicates whether or not to run tests requiring a network + * connection. + * + * TWITTER_USER and TWITTER_PASS are valid Twitter credentials you wish to use + * when testing. + */ +defined('TESTS_ZEND_SERVICE_TWITTER_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_TWITTER_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_TWITTER_USER') || define('TESTS_ZEND_SERVICE_TWITTER_USER', 'zftestuser'); +defined('TESTS_ZEND_SERVICE_TWITTER_PASS') || define('TESTS_ZEND_SERVICE_TWITTER_PASS', 'zftestuser'); + +/** + * Zend_Service_WindowsAzure tests + */ + +/** + * Online + */ + +define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_ACCOUNTNAME',''); +define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_ACCOUNTKEY',''); +define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_TABLE_HOST',''); +define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_STORAGE_PROXY_HOST',''); +define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_STORAGE_PROXY_PORT',''); +define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_STORAGE_PROXY_CREDENTIALS',''); + +/** + * Proxy settings + */ +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_USEPROXY') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_USEPROXY', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY', ''); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_PORT') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_PORT', '8080'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_CREDENTIALS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_CREDENTIALS', ''); + +/** + * Azure hosts + */ +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_DEV', '127.0.0.1:10000'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_DEV', '127.0.0.1:10001'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_DEV', '127.0.0.1:10002'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_PROD', 'blob.core.windows.net'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_PROD', 'queue.core.windows.net'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_PROD', 'table.core.windows.net'); + +/** + * Credentials + */ +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_DEV', 'devstoreaccount1'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_DEV', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=='); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_PROD', 'phpazure'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_PROD', 'I+ebYPcIDB6BsmfAe6pJSpOw8oXA6jMBZv1BEZcSPRqTpldt44refCl65YpKJqcBOiD21Lxsj8d6Ah8Oc2/gKA=='); + +/** + * Blob storage tests + */ +// Enable this tests only when you have a working account +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNTESTS', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNONPROD', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNLARGEBLOB') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNLARGEBLOB', true); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_CONTAINER_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_CONTAINER_PREFIX', 'phpazuretestblob'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSTREAM_CONTAINER_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSTREAM_CONTAINER_PREFIX', 'phpazureteststream'); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSA_CONTAINER_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSA_CONTAINER_PREFIX', 'phpazuretestshared'); + +/** + * Table storage tests + */ +// Enable this tests only when you have a working account +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNTESTS', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNONPROD', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_TABLENAME_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_TABLENAME_PREFIX', 'phpazuretesttable'); + +/** + * Queue storage tests + */ +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNTESTS', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNONPROD', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_PREFIX', 'phpazuretestqueue'); + +/** + * SessionHandler tests + */ +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNTESTS', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNONPROD', false); +defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_TABLENAME_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_TABLENAME_PREFIX', 'phpazuretestsession'); + +/** + * Zend_Service_Yahoo online tests + */ +defined('TESTS_ZEND_SERVICE_YAHOO_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_YAHOO_ONLINE_ENABLED', false); +defined('TESTS_ZEND_SERVICE_YAHOO_ONLINE_APPID') || define('TESTS_ZEND_SERVICE_YAHOO_ONLINE_APPID', 'Enter APPID here'); + +/** + * Zend_Soap_AutoDiscover scenario tests for complex objects and wsdl generation + * + * Copy all the files of zf/tests/Zend/Soap/_files/fulltests into a directory + * that can be reached by webserver and enter the base uri to this directory + * into the variable. The test "Zend_Soap_AutoDiscover_OnlineTest" makes use + * of the servers and AutoDiscover feature. + * + * NOTE: Make sure the servers are using the correct Zend Framework copy, + * when having more than one version installed and include paths are changing. + */ +defined('TESTS_ZEND_SOAP_AUTODISCOVER_ONLINE_SERVER_BASEURI') || define('TESTS_ZEND_SOAP_AUTODISCOVER_ONLINE_SERVER_BASEURI', false); + +/** + * Zend_Uri tests + * + * Setting CRASH_TEST_ENABLED to true will enable some tests that may + * potentially crash PHP on some systems, due to very deep-nesting regular + * expressions. + * + * Only do this if you know what you are doing! + */ +defined('TESTS_ZEND_URI_CRASH_TEST_ENABLED') || define('TESTS_ZEND_URI_CRASH_TEST_ENABLED', false); + +/** + * Zend_Validate tests + * + * Set ONLINE_ENABLED if you wish to run validators that require network + * connectivity. + */ +defined('TESTS_ZEND_VALIDATE_ONLINE_ENABLED') || define('TESTS_ZEND_VALIDATE_ONLINE_ENABLED', false); + +/** + * PHPUnit Code Coverage / Test Report + */ +defined('TESTS_GENERATE_REPORT') || define('TESTS_GENERATE_REPORT', false); +defined('TESTS_GENERATE_REPORT_TARGET') || define('TESTS_GENERATE_REPORT_TARGET', '/path/to/target'); + From 2b52673c96ad568fc47e9d78fbae2c8cbf252bed Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Wed, 4 Apr 2012 00:32:21 +0200 Subject: [PATCH 238/311] Making the run-tests.sh script executable --- .travis/run-tests.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 .travis/run-tests.sh diff --git a/.travis/run-tests.sh b/.travis/run-tests.sh old mode 100644 new mode 100755 From e07e12e5060e6f92081034c0f95ed9b7381cecc9 Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Wed, 4 Apr 2012 20:56:26 +0200 Subject: [PATCH 239/311] Moving travis test configuration This way it is more obvious to the committer changing test configuration that also travis config should be changed --- .travis/TestConfiguration.php | 825 ---------------------------------- 1 file changed, 825 deletions(-) delete mode 100644 .travis/TestConfiguration.php diff --git a/.travis/TestConfiguration.php b/.travis/TestConfiguration.php deleted file mode 100644 index fd8947049..000000000 --- a/.travis/TestConfiguration.php +++ /dev/null @@ -1,825 +0,0 @@ - test disabling output buffering in - * dispatcher - */ -defined('TESTS_ZEND_CONTROLLER_DISPATCHER_OB') || define('TESTS_ZEND_CONTROLLER_DISPATCHER_OB', false); - -/** - * Zend_Crypt related constantes - * - * TESTS_ZEND_CRYPT_OPENSSL_CONF => location of an openssl.cnf file for use - * with RSA encryption - */ -defined('TESTS_ZEND_CRYPT_OPENSSL_CONF') || define('TESTS_ZEND_CRYPT_OPENSSL_CONF', false); - -/** - * Zend_Db_Adapter_Pdo_Mysql and Zend_Db_Adapter_Mysqli - * - * There are separate properties to enable tests for the PDO_MYSQL adapter and - * the native Mysqli adapters, but the other properties are shared between the - * two MySQL-related Zend_Db adapters. - */ -defined('TESTS_ZEND_DB_ADAPTER_PDO_MYSQL_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_MYSQL_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_MYSQLI_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_MYSQLI_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_MYSQL_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_HOSTNAME', '127.0.0.1'); -defined('TESTS_ZEND_DB_ADAPTER_MYSQL_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_USERNAME', null); -defined('TESTS_ZEND_DB_ADAPTER_MYSQL_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_PASSWORD', null); -defined('TESTS_ZEND_DB_ADAPTER_MYSQL_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_DATABASE', 'test'); -defined('TESTS_ZEND_DB_ADAPTER_MYSQL_PORT') || define('TESTS_ZEND_DB_ADAPTER_MYSQL_PORT', 3306); - -/** - * Zend_Db_Adapter_Pdo_Sqlite - * - * Username and password are irrelevant for SQLite. - */ -defined('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_PDO_SQLITE_DATABASE', ':memory:'); - -/** - * Zend_Db_Adapter_Pdo_Mssql - * - * Note that you need to patch your ntwdblib.dll, the one that - * comes with PHP does not work. See user comments at - * http://us2.php.net/manual/en/ref.mssql.php - */ -defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_HOSTNAME', '127.0.0.1'); -defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_USERNAME', null); -defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_PASSWORD', null); -defined('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_PDO_MSSQL_DATABASE', 'test'); - -/** - * Zend_Db_Adapter_Pdo_Pgsql - */ -defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_HOSTNAME', '127.0.0.1'); -defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_USERNAME', null); -defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_PASSWORD', null); -defined('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_PDO_PGSQL_DATABASE', 'postgres'); - -/** - * Zend_Db_Adapter_Oracle and Zend_Db_Adapter_Pdo_Oci - * - * There are separate properties to enable tests for the PDO_OCI adapter and - * the native Oracle adapter, but the other properties are shared between the - * two Oracle-related Zend_Db adapters. - */ -defined('TESTS_ZEND_DB_ADAPTER_PDO_OCI_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_OCI_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_ORACLE_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_ORACLE_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_HOSTNAME', '127.0.0.1'); -defined('TESTS_ZEND_DB_ADAPTER_ORACLE_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_USERNAME', null); -defined('TESTS_ZEND_DB_ADAPTER_ORACLE_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_PASSWORD', null); -defined('TESTS_ZEND_DB_ADAPTER_ORACLE_SID') || define('TESTS_ZEND_DB_ADAPTER_ORACLE_SID', 'xe'); - -/** - * Zend_Db_Adapter_Db2 and Zend_Db_Adapter_Pdo_Ibm - * There are separate properties to enable tests for the PDO_IBM adapter and - * the native DB2 adapter, but the other properties are shared between the - * two related Zend_Db adapters. - */ -defined('TESTS_ZEND_DB_ADAPTER_PDO_IBM_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_PDO_IBM_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_DB2_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_DB2_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_DB2_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_DB2_HOSTNAME', '127.0.0.1'); -defined('TESTS_ZEND_DB_ADAPTER_DB2_PORT') || define('TESTS_ZEND_DB_ADAPTER_DB2_PORT', 50000); -defined('TESTS_ZEND_DB_ADAPTER_DB2_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_DB2_USERNAME', null); -defined('TESTS_ZEND_DB_ADAPTER_DB2_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_DB2_PASSWORD', null); -defined('TESTS_ZEND_DB_ADAPTER_DB2_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_DB2_DATABASE', 'sample'); - -/** - * Zend_Db_Adapter_Sqlsrv - * Note: Make sure that you create the "test" database and set a - * username and password - * - */ -defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_ENABLED') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_ENABLED', false); -defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_HOSTNAME') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_HOSTNAME', 'localhost\SQLEXPRESS'); -defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_USERNAME') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_USERNAME', null); -defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_PASSWORD') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_PASSWORD', null); -defined('TESTS_ZEND_DB_ADAPTER_SQLSRV_DATABASE') || define('TESTS_ZEND_DB_ADAPTER_SQLSRV_DATABASE', 'test'); - -/** - * Zend_Feed_Reader tests - * - * If the ONLINE_ENABLED property is false, only tests that can be executed - * without network connectivity are run; when enabled, all tests will run. - */ -defined('TESTS_ZEND_FEED_READER_ONLINE_ENABLED') || define('TESTS_ZEND_FEED_READER_ONLINE_ENABLED', false); - -/** - * Zend_Gdata tests - * - * If the ONLINE_ENABLED property is false, only tests that can be executed with - * a mock HTTP client are run. No request is sent to the Google Gdata servers. - * If ONLINE_ENABLED is true, some tests may make requests to the remote - * servers. This does not work if you are running tests on a disconnected - * client host. Also, the tests may show as failures if the Google servers - * cannot be reached or if they do not respond for another reason. - * - * If the CLIENTLOGIN_ENABLED property below is false, the authenticated - * tests are reported Skipped in the test run. Set this property to true - * to enable tests that require ClientLogin authentication. Enter your - * Google login credentials in the EMAIL and PASSWORD properties below. - * - * Edit TestConfiguration.php, not TestConfiguration.php.dist. - * Never commit plaintext passwords to the source code repository. - * - * Note: the GData tests currently require that the TZID env variable - * be set or the timezone otherwise configured. You'll see errors from the - * tests if this is not the case. - */ -defined('TESTS_ZEND_GDATA_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_ONLINE_ENABLED', false); -defined('TESTS_ZEND_GDATA_CLIENTLOGIN_ENABLED') || define('TESTS_ZEND_GDATA_CLIENTLOGIN_ENABLED', false); - -/* - * The credentials provided here should be only for a TEST account. - * Data for various services in this account may be added to, updated, - * or deleted based upon the actions of these test accounts. - */ -defined('TESTS_ZEND_GDATA_CLIENTLOGIN_EMAIL') || define('TESTS_ZEND_GDATA_CLIENTLOGIN_EMAIL', 'example@example.com'); -defined('TESTS_ZEND_GDATA_CLIENTLOGIN_PASSWORD') || define('TESTS_ZEND_GDATA_CLIENTLOGIN_PASSWORD', 'password'); - -/* - * This is the ID of a blank blog. There is no need to have - * any content in this blog. Also, blogs can only be used - * several times for the purpose of these test cases before - * they must be deleted and recreated. Otherwise, the tests - * will start failing, as posts to Blogger will return a 201 Created - * response even though the entry was not posted to the blog. - * This problem is being investigated. - */ -defined('TESTS_ZEND_GDATA_BLOGGER_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_BLOGGER_ONLINE_ENABLED', false); -defined('TESTS_ZEND_GDATA_BLOG_ID') || define('TESTS_ZEND_GDATA_BLOG_ID', '1111111111111111111'); - -/* - * This is the key for a spreadsheet with data only in the first row of - * the spreadsheet. The strings 'a1', 'b1', 'c1', 'd1' should be in the - * corresponding cell locations. - */ -defined('TESTS_ZEND_GDATA_SPREADSHEETS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_SPREADSHEETS_ONLINE_ENABLED', false); -defined('TESTS_ZEND_GDATA_SPREADSHEETS_SPREADSHEETKEY') || define('TESTS_ZEND_GDATA_SPREADSHEETS_SPREADSHEETKEY', 'o01111111111111111111.1111111111111111111'); -defined('TESTS_ZEND_GDATA_SPREADSHEETS_WORKSHEETID') || define('TESTS_ZEND_GDATA_SPREADSHEETS_WORKSHEETID', 'default'); - -/* - * This indicates that online tests for the Google Calendar API should - * be performed. The default calendar will be used. - */ -defined('TESTS_ZEND_GDATA_CALENDAR_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_CALENDAR_ONLINE_ENABLED', false); - -/* - * This is the fully-qualified domain name for a domiain hosted using - * Google Apps. This domain must be registered with Google Apps and - * have API access enabled. This should be a TEST domain only. - */ -defined('TESTS_ZEND_GDATA_GAPPS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_GAPPS_ONLINE_ENABLED', false); -defined('TESTS_ZEND_GDATA_GAPPS_DOMAIN') || define('TESTS_ZEND_GDATA_GAPPS_DOMAIN', 'example.com.invalid'); -defined('TESTS_ZEND_GDATA_GAPPS_EMAIL') || define('TESTS_ZEND_GDATA_GAPPS_EMAIL', 'example@example.com'); -defined('TESTS_ZEND_GDATA_GAPPS_PASSWORD') || define('TESTS_ZEND_GDATA_GAPPS_PASSWORD', 'password'); - -/* - * This is the ONLINE_ENABLED property for Google Base. - */ -defined('TESTS_ZEND_GDATA_GBASE_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_GBASE_ONLINE_ENABLED', false); - -/* - * This indicates that online tests for the Books Search data API - * should be performed. - */ -defined('TESTS_ZEND_GDATA_BOOKS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_BOOKS_ONLINE_ENABLED', false); - -/* - * This indicates that online tests for the YouTube data API should - * be performed. - */ -defined('TESTS_ZEND_GDATA_YOUTUBE_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_YOUTUBE_ONLINE_ENABLED', false); - -/* - * This is the username to use for retrieving subscriptions, etc - */ -defined('TESTS_ZEND_GDATA_YOUTUBE_ACCOUNT') || define('TESTS_ZEND_GDATA_YOUTUBE_ACCOUNT', 'zfgdata'); - -/* - * This is the developer key to access the YouTube API - */ -defined('TESTS_ZEND_GDATA_YOUTUBE_DEVELOPER_KEY') || define('TESTS_ZEND_GDATA_YOUTUBE_DEVELOPER_KEY', 'your_developer_key_here'); - -/* - * This is the client ID to access the YouTube API - */ -defined('TESTS_ZEND_GDATA_YOUTUBE_CLIENT_ID') || define('TESTS_ZEND_GDATA_YOUTUBE_CLIENT_ID', 'ZF_UnitTests_unknown'); - -/* - * This indicates that online tests for the Google Documents API should - * be performed. - */ -defined('TESTS_ZEND_GDATA_DOCS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_DOCS_ONLINE_ENABLED', false); - -/* - * This indicates that online tests for the GData Photos API should - * be performed. - */ -defined('TESTS_ZEND_GDATA_PHOTOS_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_PHOTOS_ONLINE_ENABLED', false); - -/* - * This indicates that online tests for the Google Health API should - * be performed. - */ -defined('TESTS_ZEND_GDATA_HEALTH_ONLINE_ENABLED') || define('TESTS_ZEND_GDATA_HEALTH_ONLINE_ENABLED', false); - -/** - * Zend_Http_Client tests - * - * To enable the dynamic Zend_Http_Client tests, you will need to symbolically - * link or copy the files in tests/Zend/Http/Client/_files to a directory - * under your web server(s) document root and set this constant to point to the - * URL of this directory. - */ -defined('TESTS_ZEND_HTTP_CLIENT_BASEURI') || define('TESTS_ZEND_HTTP_CLIENT_BASEURI', false); - -/** - * Zend_Http_Client_Proxy tests - * - * HTTP proxy to be used for testing the Proxy adapter. Set to a string of - * the form 'host:port'. Set to null to skip HTTP proxy tests. - */ -defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY') || define('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY', false); -defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_USER') || define('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_USER', ''); -defined('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_PASS') || define('TESTS_ZEND_HTTP_CLIENT_HTTP_PROXY_PASS', ''); - -/** - * Zend_Loader_Autoloader multi-version support tests - * - * ENABLED: whether or not to run the multi-version tests - * PATH: path to a directory containing multiple ZF version installs - * LATEST: most recent ZF version in the PATH - * e.g., "1.9.2" - * LATEST_MAJOR: most recent ZF major version in the PATH to test against - * e.g., "1.9.2" - * LATEST_MINOR: most recent ZF minor version in the PATH to test against - * e.g., "1.8.4PL1" - * SPECIFIC: specific ZF version in the PATH to test against - * e.g., "1.7.6" - * As an example, consider the following tree: - * ZendFramework/ - * |-- 1.9.2 - * |-- ZendFramework-1.9.1-minimal - * |-- 1.8.4PL1 - * |-- 1.8.4 - * |-- ZendFramework-1.8.3 - * |-- 1.7.8 - * |-- 1.7.7 - * |-- 1.7.6 - * You would then set the value of "LATEST" and "LATEST_MAJOR" to "1.9.2", and - * could choose between "1.9.2", "1.8.4PL1", and "1.7.8" for "LATEST_MINOR", - * and any version number for "SPECIFIC". "PATH" would point to the parent - * "ZendFramework" directory. - */ -defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_ENABLED') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_ENABLED', false); -defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_PATH') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_PATH', false); -defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST', false); -defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MAJOR') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MAJOR', false); -defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MINOR') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_LATEST_MINOR', false); -defined('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_SPECIFIC') || define('TESTS_ZEND_LOADER_AUTOLOADER_MULTIVERSION_SPECIFIC', false); - -/** - * Zend_Ldap online tests - */ -defined('TESTS_ZEND_LDAP_ONLINE_ENABLED') || define('TESTS_ZEND_LDAP_ONLINE_ENABLED', false); - -/* These largely map to the options described in the Zend_Ldap and - * Zend_Auth_Adapter_Ldap documentation. - * - * Example Configuration for Active Directory: - * HOST: dc1.w.net - * USE_START_TLS: true - * USE_SSL: false - * USERNAME: CN=User 1,CN=Users,DC=w,DC=net - * PRINCIPAL_NAME: user1@w.net - * LDAP_PASSWORD: pass1 - * BASE_DN: CN=Users,DC=w,DC=net - * DOMAIN_NAME: w.net - * ACCOUNT_DOMAIN_NAME_SHORT: W - * ALT_USERNAME: user2 - * ALT_DN: CN=User 2,CN=Users,DC=w,DC=net - * ALT_PASSWORD: pass2 - * - * Example Configuration for OpenLDAP - * HOST: s0.foo.net - * USERNAME: CN=user1,DC=foo,DC=net - * PRINCIPAL_NAME: user1@foo.net - * LDAP_PASSWORD: pass1 - * BIND_REQUIRES_DN: true - * BASE_DN: OU=Sales,DC=w,DC=net - * DOMAIN_NAME: foo.net - * ACCOUNT_DOMAIN_NAME_SHORT: FOO - * ALT_USERNAME: abaker - * ALT_DN: CN=Alice Baker,OU=Sales,DC=foo,DC=net - * ALT_PASSWORD: apass - */ -defined('TESTS_ZEND_LDAP_HOST') || define('TESTS_ZEND_LDAP_HOST', 'localhost'); -//defined('TESTS_ZEND_LDAP_PORT') || define('TESTS_ZEND_LDAP_PORT', 389); -defined('TESTS_ZEND_LDAP_USE_START_TLS') || define('TESTS_ZEND_LDAP_USE_START_TLS', true); -//defined('TESTS_ZEND_LDAP_USE_SSL') || define('TESTS_ZEND_LDAP_USE_SSL', false); -defined('TESTS_ZEND_LDAP_USERNAME') || define('TESTS_ZEND_LDAP_USERNAME', 'CN=someUser,DC=example,DC=com'); -defined('TESTS_ZEND_LDAP_PRINCIPAL_NAME') || define('TESTS_ZEND_LDAP_PRINCIPAL_NAME', 'someUser@example.com'); -defined('TESTS_ZEND_LDAP_PASSWORD') || define('TESTS_ZEND_LDAP_PASSWORD', null); -defined('TESTS_ZEND_LDAP_BIND_REQUIRES_DN') || define('TESTS_ZEND_LDAP_BIND_REQUIRES_DN', true); -defined('TESTS_ZEND_LDAP_BASE_DN') || define('TESTS_ZEND_LDAP_BASE_DN', 'OU=Sales,DC=example,DC=com'); -//defined('TESTS_ZEND_LDAP_ACCOUNT_FILTER_FORMAT') || define('TESTS_ZEND_LDAP_ACCOUNT_FILTER_FORMAT', '(&(objectClass=posixAccount)(uid=%s))'); -defined('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME') || define('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME', 'example.com'); -defined('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME_SHORT') || define('TESTS_ZEND_LDAP_ACCOUNT_DOMAIN_NAME_SHORT', 'EXAMPLE'); -defined('TESTS_ZEND_LDAP_ALT_USERNAME') || define('TESTS_ZEND_LDAP_ALT_USERNAME', 'anotherUser'); -defined('TESTS_ZEND_LDAP_ALT_DN') || define('TESTS_ZEND_LDAP_ALT_DN', 'CN=Another User,OU=Sales,DC=example,DC=com'); -defined('TESTS_ZEND_LDAP_ALT_PASSWORD') || define('TESTS_ZEND_LDAP_ALT_PASSWORD', null); // Used in Zend_Auth_Adapter_Ldap tests -//(defined('TESTS_ZEND_LDAP_WRITEABLE_SUBTREE') || define('TESTS_ZEND_LDAP_WRITEABLE_SUBTREE', 'OU=Test,OU=Sales,DC=example,DC=com'); - -/** - * Zend_Locale tests - * - * If the TESTS_ZEND_LOCALE_FORMAT_SETLOCALE property below is a valid, - * locally recognized locale (try "locale -a"), then all tests in - * tests/Zend/Locale/ test suites will execute *after* - * setlocale(LC_ALL, TESTS_ZEND_LOCALE_FORMAT_SETLOCALE); - * Primarily, this switches certain PHP functions to emit "localized" output, - * including the built-in "to string" for integer and float conversions. - * Thus, a locale of 'fr_FR' yields number-to-string conversions in a - * localized form with the decimal place separator chosen via: - * setlocale(LC_ALL, 'fr_FR@euro'); - */ -//define('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE', 'fr'); -//define('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE', 'fr_FR@euro'); -defined('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE') || define('TESTS_ZEND_LOCALE_FORMAT_SETLOCALE', false); - -/** - * Zend_Date tests - * - * If the BCMATH_ENABLED property below is false, all arithmetic - * operations will use ordinary PHP math operators and functions. - * Otherwise, the bcmath functions will be used for unlimited precision. - * - * If the EXTENDED_COVERAGE property below is false, most of the I18N - * unit tests will not be computed... this speeds tests up to 80 minutes - * when doing reports. * - * Edit TestConfiguration.php, not TestConfiguration.php.dist. - */ -defined('TESTS_ZEND_LOCALE_BCMATH_ENABLED') || define('TESTS_ZEND_LOCALE_BCMATH_ENABLED', true); -defined('TESTS_ZEND_I18N_EXTENDED_COVERAGE') || define('TESTS_ZEND_I18N_EXTENDED_COVERAGE', true); - -/** - * Zend_Mail_Storage tests - * - * TESTS_ZEND_MAIL_SERVER_TESTDIR and TESTS_ZEND_MAIL_SERVER_FORMAT are used for POP3 and IMAP tests. - * TESTS_ZEND_MAIL_SERVER_FORMAT is the format your test mail server uses: 'mbox' or 'maildir'. The mail - * storage for the user specified in your POP3 or IMAP tests should be TESTS_ZEND_MAIL_SERVER_TESTDIR. Be - * careful: it's cleared before copying the files. If you want to copy the files manually set the dir - * to null (or anything == null). - * - * TESTS_ZEND_MAIL_TEMPDIR is used for testing write operations in local storages. If not set (== null) - * tempnam() is used. - */ -defined('TESTS_ZEND_MAIL_SERVER_TESTDIR') || define('TESTS_ZEND_MAIL_SERVER_TESTDIR', null); -defined('TESTS_ZEND_MAIL_SERVER_FORMAT') || define('TESTS_ZEND_MAIL_SERVER_FORMAT', 'mbox'); -defined('TESTS_ZEND_MAIL_TEMPDIR') || define('TESTS_ZEND_MAIL_TEMPDIR', null); - -/** - * Zend_Mail_Storage_Pop3 / Zend_Mail_Transport_Pop3 - * - * IMPORTANT: you need to copy tests/Zend/Mail/_files/test.mbox to your mail - * if you haven't set TESTS_ZEND_MAIL_SERVER_TESTDIR - */ -defined('TESTS_ZEND_MAIL_POP3_ENABLED') || define('TESTS_ZEND_MAIL_POP3_ENABLED', false); -defined('TESTS_ZEND_MAIL_POP3_HOST') || define('TESTS_ZEND_MAIL_POP3_HOST', 'localhost'); -defined('TESTS_ZEND_MAIL_POP3_USER') || define('TESTS_ZEND_MAIL_POP3_USER', 'test'); -defined('TESTS_ZEND_MAIL_POP3_PASSWORD') || define('TESTS_ZEND_MAIL_POP3_PASSWORD', ''); -// test SSL connections if enabled in your test server -defined('TESTS_ZEND_MAIL_POP3_SSL') || define('TESTS_ZEND_MAIL_POP3_SSL', true); -defined('TESTS_ZEND_MAIL_POP3_TLS') || define('TESTS_ZEND_MAIL_POP3_TLS', true); -// WRONG_PORT should be an existing server port, -// INVALID_PORT should be a non existing (each on defined host) -defined('TESTS_ZEND_MAIL_POP3_WRONG_PORT') || define('TESTS_ZEND_MAIL_POP3_WRONG_PORT', 80); -defined('TESTS_ZEND_MAIL_POP3_INVALID_PORT') || define('TESTS_ZEND_MAIL_POP3_INVALID_PORT', 3141); - -/** - * Zend_Mail_Storage_Imap / Zend_Mail_Transport_Imap - * - * IMPORTANT: you need to copy tests/Zend/Mail/_files/test.mbox to your mail - * if you haven't set TESTS_ZEND_MAIL_SERVER_TESTDIR - */ -defined('TESTS_ZEND_MAIL_IMAP_ENABLED') || define('TESTS_ZEND_MAIL_IMAP_ENABLED', false); -defined('TESTS_ZEND_MAIL_IMAP_HOST') || define('TESTS_ZEND_MAIL_IMAP_HOST', 'localhost'); -defined('TESTS_ZEND_MAIL_IMAP_USER') || define('TESTS_ZEND_MAIL_IMAP_USER', 'test'); -defined('TESTS_ZEND_MAIL_IMAP_PASSWORD') || define('TESTS_ZEND_MAIL_IMAP_PASSWORD', ''); -// test SSL connections if enabled in your test server -defined('TESTS_ZEND_MAIL_IMAP_SSL') || define('TESTS_ZEND_MAIL_IMAP_SSL', true); -defined('TESTS_ZEND_MAIL_IMAP_TLS') || define('TESTS_ZEND_MAIL_IMAP_TLS', true); -// WRONG_PORT should be an existing server port, -// INVALID_PORT should be a non-existing (each on defined host) -defined('TESTS_ZEND_MAIL_IMAP_WRONG_PORT') || define('TESTS_ZEND_MAIL_IMAP_WRONG_PORT', 80); -defined('TESTS_ZEND_MAIL_IMAP_INVALID_PORT') || define('TESTS_ZEND_MAIL_IMAP_INVALID_PORT', 3141); - - -/** - * Zend_Mail_Storage_Maildir test - * - * Before enabling this test you have to unpack messages.tar in - * Zend/Mail/_files/test.maildir/cur/ and remove the tar for this test to work. - * That's because the messages files have a colon in the filename and that's a - * forbidden character on Windows. - */ -defined('TESTS_ZEND_MAIL_MAILDIR_ENABLED') || define('TESTS_ZEND_MAIL_MAILDIR_ENABLED', false); - -/** - * Zend_Mail_Transport_Smtp - * - * @todo TO be implemented - */ -defined('TESTS_ZEND_MAIL_SMTP_ENABLED') || define('TESTS_ZEND_MAIL_SMTP_ENABLED', false); -defined('TESTS_ZEND_MAIL_SMTP_HOST') || define('TESTS_ZEND_MAIL_SMTP_HOST', 'localhost'); -defined('TESTS_ZEND_MAIL_SMTP_PORT') || define('TESTS_ZEND_MAIL_SMTP_PORT', 25); -defined('TESTS_ZEND_MAIL_SMTP_USER') || define('TESTS_ZEND_MAIL_SMTP_USER', 'testuser'); -defined('TESTS_ZEND_MAIL_SMTP_PASSWORD') || define('TESTS_ZEND_MAIL_SMTP_PASSWORD', 'testpassword'); -defined('TESTS_ZEND_MAIL_SMTP_AUTH') || define('TESTS_ZEND_MAIL_SMTP_AUTH', false); -// AUTH can be set to false or a string of AUTH method (e.g. LOGIN, PLAIN, CRAMMD5 or DIGESTMD5) - -/** - * Zend_Queue Test Configuration constants - * - * The Zend_Queue_Adapter_Db constant should be a JSON-encoded string - * representing a configuration object for Zend_Db::factory(). For example: - * { - * type: "pdo_mysql", - * host: "127.0.0.1", - * port: 3306, - * username: "queue", - * password: "queue", - * dbname: "queue" - * } - * - * The PlatformJobQueue adapter expects two parameters, the host and password. - * The HOST string should include both the host and port (typically 10003): - * 127.0.0.1:10003 - * When running tests against PlatformJobQueue, it's best to do so where - * Platform is installed on localhost and has maximum workers set to 20 - * (default is 5); do so with this zend.ini setting: - * zend_jq.max_num_of_request_workers=20 - * - * Selectively define the below in order to run tests for them. - */ -defined('TESTS_ZEND_QUEUE_ACTIVEMQ_ENABLED') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_ENABLED', false); -defined('TESTS_ZEND_QUEUE_ACTIVEMQ_SCHEME') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_SCHEME', false); -defined('TESTS_ZEND_QUEUE_ACTIVEMQ_HOST') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_HOST', false); -defined('TESTS_ZEND_QUEUE_ACTIVEMQ_PORT') || define('TESTS_ZEND_QUEUE_ACTIVEMQ_PORT', false); -defined('TESTS_ZEND_QUEUE_DB_ENABLED') || define('TESTS_ZEND_QUEUE_DB_ENABLED', false); -defined('TESTS_ZEND_QUEUE_DB') || define('TESTS_ZEND_QUEUE_DB', false); -defined('TESTS_ZEND_QUEUE_MEMCACHEQ_ENABLED') || define('TESTS_ZEND_QUEUE_MEMCACHEQ_ENABLED', false); -defined('TESTS_ZEND_QUEUE_MEMCACHEQ_HOST') || define('TESTS_ZEND_QUEUE_MEMCACHEQ_HOST', false); -defined('TESTS_ZEND_QUEUE_MEMCACHEQ_PORT') || define('TESTS_ZEND_QUEUE_MEMCACHEQ_PORT', false); -defined('TESTS_ZEND_QUEUE_PLATFORMJQ_ENABLED') || define('TESTS_ZEND_QUEUE_PLATFORMJQ_ENABLED', false); -defined('TESTS_ZEND_QUEUE_PLATFORMJQ_HOST') || define('TESTS_ZEND_QUEUE_PLATFORMJQ_HOST', false); -defined('TESTS_ZEND_QUEUE_PLATFORMJQ_PASS') || define('TESTS_ZEND_QUEUE_PLATFORMJQ_PASS', false); - - -/** - * Zend\Service\AgileZen online tests - */ -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_ENABLED',false); -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_APIKEY','insert the API key'); -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_PROJECT_ID','insert the project id'); -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_STORY_ID','insert the story id'); -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_INVITE_EMAIL','insert email for invitation'); -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_INVITE_ROLE_ID','insert role id for invitation'); -define('TESTS_ZEND_SERVICE_AGILEZEN_ONLINE_MEMBER_NAME','insert the member name to add to the project'); - - -/** - * Zend_Service_Amazon online tests - */ -defined('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ACCESSKEYID') || define('TESTS_ZEND_SERVICE_AMAZON_ONLINE_ACCESSKEYID', 'Enter AWSAccessKeyId here'); -defined('TESTS_ZEND_SERVICE_AMAZON_ONLINE_SECRETKEY') || define('TESTS_ZEND_SERVICE_AMAZON_ONLINE_SECRETKEY', 'Enter AWSSecretKey here'); -defined('TESTS_ZEND_SERVICE_AMAZON_EC2_IMAGE_ID') || define('TESTS_ZEND_SERVICE_AMAZON_EC2_IMAGE_ID', 'zftestamazonimageid'); -defined('TESTS_ZEND_SERVICE_AMAZON_EC2_ZONE') || define('TESTS_ZEND_SERVICE_AMAZON_EC2_ZONE', 'us-east-1'); -defined('TESTS_ZEND_SERVICE_AMAZON_EC2_SECURITY_GROUP') || define('TESTS_ZEND_SERVICE_AMAZON_EC2_SECURITY_GROUP', 'default'); -defined('TESTS_ZEND_SERVICE_AMAZON_S3_BUCKET') || define('TESTS_ZEND_SERVICE_AMAZON_S3_BUCKET', 'zftestamazons3bucket'); -defined('TESTS_ZEND_SERVICE_AMAZON_SQS_QUEUE') || define('TESTS_ZEND_SERVICE_AMAZON_SQS_QUEUE', 'zftestamazonsqsqueuename'); - -/** - * Zend_Service_Delicious tests - */ -defined('TESTS_ZEND_SERVICE_DELICIOUS_ENABLED') || define('TESTS_ZEND_SERVICE_DELICIOUS_ENABLED', false); - -/** - * Zend_Service_DeveloperGarden tests - * Setup your Username and Password to test this Service - */ -defined('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_LOGIN') || define('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_LOGIN', 'ZF_Username'); -defined('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_PASSWORD') || define('TESTS_ZEND_SERVICE_DEVELOPERGARDEN_ONLINE_PASSWORD', 'ZF_Password'); - -/** - * Zend_Service_Flickr online tests - */ -defined('TESTS_ZEND_SERVICE_FLICKR_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_FLICKR_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_FLICKR_ONLINE_APIKEY') || define('TESTS_ZEND_SERVICE_FLICKR_ONLINE_APIKEY', 'Enter API key here'); - -/** - * Zend_Service_GoGrid offline tests - */ - -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_KEY') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_KEY','insert key here'); -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SECRET') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SECRET','insert secret here'); -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_NAME') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_NAME','test-zf'); -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IMAGE') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IMAGE','insert image name here'); -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_RAM') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_RAM','insert ram name here'); -defined('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IP') || define('TESTS_ZEND_SERVICE_GOGRID_ONLINE_SERVER_IP','insert ip here'); - -/** - * Zend\Service\LiveDocx configuration - * - * Define username and password in order to run unit tests for LiveDocx web services. - * - * phpunit/phpunit will typically work. - */ -defined('TESTS_ZEND_SERVICE_LIVEDOCX_USERNAME') || define('TESTS_ZEND_SERVICE_LIVEDOCX_USERNAME', false); -defined('TESTS_ZEND_SERVICE_LIVEDOCX_PASSWORD') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PASSWORD', false); - -/** - * Zend\Service\LiveDocx premium configuration - * - * Define username, password, WSDL in order to run unit tests for premium LiveDocx web services. - */ -defined('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_USERNAME') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_USERNAME', false); -defined('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_PASSWORD') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_PASSWORD', false); -defined('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_WSDL') || define('TESTS_ZEND_SERVICE_LIVEDOCX_PREMIUM_WSDL', false); - -/** - * Zend_Service_Rackspace tests - */ -defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_USER') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_USER', 'Enter key here'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_KEY') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_KEY', 'Enter secret here'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_REGION') || define('TESTS_ZEND_SERVICE_RACKSPACE_ONLINE_REGION', 'USA'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_CONTAINER_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_CONTAINER_NAME', 'zf-unit-test'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_OBJECT_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_OBJECT_NAME','zf-object-test'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NAME', 'zf-unit-test'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGEID') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGEID', '49'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NEW_IMAGEID') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_NEW_IMAGEID', '49'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_FLAVORID') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_FLAVORID', '1'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGE_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_IMAGE_NAME', 'ZFunitTestImage'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_SHARED_IP_GROUP_NAME') || define('TESTS_ZEND_SERVICE_RACKSPACE_SERVER_SHARED_IP_GROUP_NAME', 'ZFgroupIP'); -defined('TESTS_ZEND_SERVICE_RACKSPACE_TIMEOUT') || define('TESTS_ZEND_SERVICE_RACKSPACE_TIMEOUT', 60); - -/** - * Zend_Service_ReCaptcha tests - */ -defined('TESTS_ZEND_SERVICE_RECAPTCHA_ENABLED') || define('TESTS_ZEND_SERVICE_RECAPTCHA_ENABLED', false); -defined('TESTS_ZEND_SERVICE_RECAPTCHA_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_RECAPTCHA_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_RECAPTCHA_PUBLIC_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_PUBLIC_KEY', 'public key'); -defined('TESTS_ZEND_SERVICE_RECAPTCHA_PRIVATE_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_PRIVATE_KEY', 'private key'); -defined('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PUBLIC_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PUBLIC_KEY', 'public mailhide key'); -defined('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PRIVATE_KEY') || define('TESTS_ZEND_SERVICE_RECAPTCHA_MAILHIDE_PRIVATE_KEY', 'private mailhide key'); - -/** - * Zend_Service_Simpy tests - */ -defined('TESTS_ZEND_SERVICE_SIMPY_ENABLED') || define('TESTS_ZEND_SERVICE_SIMPY_ENABLED', false); -defined('TESTS_ZEND_SERVICE_SIMPY_USERNAME') || define('TESTS_ZEND_SERVICE_SIMPY_USERNAME', 'syapizend'); -defined('TESTS_ZEND_SERVICE_SIMPY_PASSWORD') || define('TESTS_ZEND_SERVICE_SIMPY_PASSWORD', 'mgt37ge'); - -/** - * Zend_Service_SlideShare tests - */ -defined('TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME') || define('TESTS_ZEND_SERVICE_SLIDESHARE_USERNAME', ''); -defined('TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD') || define('TESTS_ZEND_SERVICE_SLIDESHARE_PASSWORD', ''); -defined('TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET') || define('TESTS_ZEND_SERVICE_SLIDESHARE_SHAREDSECRET', ''); -defined('TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY') || define('TESTS_ZEND_SERVICE_SLIDESHARE_APIKEY', ''); - -// The slide show ID to retrieve during tests -defined('TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID') || define('TESTS_ZEND_SERVICE_SLIDESHARE_SLIDESHOWID', 0); - -// The tag to retrieve during tests -defined('TESTS_ZEND_SERVICE_SLIDESHARE_TAG') || define('TESTS_ZEND_SERVICE_SLIDESHARE_TAG', 'zend'); - -// The group to retrieve during tests -defined('TESTS_ZEND_SERVICE_SLIDESHARE_GROUP') || define('TESTS_ZEND_SERVICE_SLIDESHARE_GROUP', ''); - -/** - * Zend_Service_Twitter tests - * - * ONLINE_ENABLED indicates whether or not to run tests requiring a network - * connection. - * - * TWITTER_USER and TWITTER_PASS are valid Twitter credentials you wish to use - * when testing. - */ -defined('TESTS_ZEND_SERVICE_TWITTER_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_TWITTER_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_TWITTER_USER') || define('TESTS_ZEND_SERVICE_TWITTER_USER', 'zftestuser'); -defined('TESTS_ZEND_SERVICE_TWITTER_PASS') || define('TESTS_ZEND_SERVICE_TWITTER_PASS', 'zftestuser'); - -/** - * Zend_Service_WindowsAzure tests - */ - -/** - * Online - */ - -define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_ACCOUNTNAME',''); -define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_ACCOUNTKEY',''); -define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_TABLE_HOST',''); -define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_STORAGE_PROXY_HOST',''); -define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_STORAGE_PROXY_PORT',''); -define('TESTS_ZEND_SERVICE_WINDOWSAZURE_ONLINE_STORAGE_PROXY_CREDENTIALS',''); - -/** - * Proxy settings - */ -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_USEPROXY') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_USEPROXY', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY', ''); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_PORT') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_PORT', '8080'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_CREDENTIALS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_PROXY_CREDENTIALS', ''); - -/** - * Azure hosts - */ -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_DEV', '127.0.0.1:10000'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_DEV', '127.0.0.1:10001'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_DEV', '127.0.0.1:10002'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_HOST_PROD', 'blob.core.windows.net'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_HOST_PROD', 'queue.core.windows.net'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_HOST_PROD', 'table.core.windows.net'); - -/** - * Credentials - */ -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_DEV', 'devstoreaccount1'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_DEV') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_DEV', 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=='); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_ACCOUNT_PROD', 'phpazure'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_PROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_STORAGE_KEY_PROD', 'I+ebYPcIDB6BsmfAe6pJSpOw8oXA6jMBZv1BEZcSPRqTpldt44refCl65YpKJqcBOiD21Lxsj8d6Ah8Oc2/gKA=='); - -/** - * Blob storage tests - */ -// Enable this tests only when you have a working account -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNTESTS', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNONPROD', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNLARGEBLOB') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_RUNLARGEBLOB', true); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_CONTAINER_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOB_CONTAINER_PREFIX', 'phpazuretestblob'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSTREAM_CONTAINER_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSTREAM_CONTAINER_PREFIX', 'phpazureteststream'); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSA_CONTAINER_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_BLOBSA_CONTAINER_PREFIX', 'phpazuretestshared'); - -/** - * Table storage tests - */ -// Enable this tests only when you have a working account -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNTESTS', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_RUNONPROD', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_TABLENAME_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_TABLE_TABLENAME_PREFIX', 'phpazuretesttable'); - -/** - * Queue storage tests - */ -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNTESTS', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_RUNONPROD', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_QUEUE_PREFIX', 'phpazuretestqueue'); - -/** - * SessionHandler tests - */ -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNTESTS') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNTESTS', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNONPROD') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_RUNONPROD', false); -defined('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_TABLENAME_PREFIX') || define('TESTS_ZEND_SERVICE_WINDOWSAZURE_SESSIONHANDLER_TABLENAME_PREFIX', 'phpazuretestsession'); - -/** - * Zend_Service_Yahoo online tests - */ -defined('TESTS_ZEND_SERVICE_YAHOO_ONLINE_ENABLED') || define('TESTS_ZEND_SERVICE_YAHOO_ONLINE_ENABLED', false); -defined('TESTS_ZEND_SERVICE_YAHOO_ONLINE_APPID') || define('TESTS_ZEND_SERVICE_YAHOO_ONLINE_APPID', 'Enter APPID here'); - -/** - * Zend_Soap_AutoDiscover scenario tests for complex objects and wsdl generation - * - * Copy all the files of zf/tests/Zend/Soap/_files/fulltests into a directory - * that can be reached by webserver and enter the base uri to this directory - * into the variable. The test "Zend_Soap_AutoDiscover_OnlineTest" makes use - * of the servers and AutoDiscover feature. - * - * NOTE: Make sure the servers are using the correct Zend Framework copy, - * when having more than one version installed and include paths are changing. - */ -defined('TESTS_ZEND_SOAP_AUTODISCOVER_ONLINE_SERVER_BASEURI') || define('TESTS_ZEND_SOAP_AUTODISCOVER_ONLINE_SERVER_BASEURI', false); - -/** - * Zend_Uri tests - * - * Setting CRASH_TEST_ENABLED to true will enable some tests that may - * potentially crash PHP on some systems, due to very deep-nesting regular - * expressions. - * - * Only do this if you know what you are doing! - */ -defined('TESTS_ZEND_URI_CRASH_TEST_ENABLED') || define('TESTS_ZEND_URI_CRASH_TEST_ENABLED', false); - -/** - * Zend_Validate tests - * - * Set ONLINE_ENABLED if you wish to run validators that require network - * connectivity. - */ -defined('TESTS_ZEND_VALIDATE_ONLINE_ENABLED') || define('TESTS_ZEND_VALIDATE_ONLINE_ENABLED', false); - -/** - * PHPUnit Code Coverage / Test Report - */ -defined('TESTS_GENERATE_REPORT') || define('TESTS_GENERATE_REPORT', false); -defined('TESTS_GENERATE_REPORT_TARGET') || define('TESTS_GENERATE_REPORT_TARGET', '/path/to/target'); - From 9d47a65a3432246796cc8f82bac70883f5847193 Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Wed, 4 Apr 2012 21:28:23 +0200 Subject: [PATCH 240/311] Re-enabling components as of @weierophinney suggestions --- .travis/skipped-components | 16 ---------------- .travis/tested-components | 18 ++++++++++++++++-- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/.travis/skipped-components b/.travis/skipped-components index 7d38e2de2..6ccd1be13 100644 --- a/.travis/skipped-components +++ b/.travis/skipped-components @@ -1,27 +1,11 @@ Zend/Amf Zend/Barcode -Zend/Cache -Zend/Code Zend/Date -Zend/Docbook Zend/Feed -Zend/File -Zend/Filter -Zend/GData -Zend/Json -Zend/Locale -Zend/Mail -Zend/Mime -Zend/Navigation -Zend/OpenId Zend/Paginator Zend/Queue -Zend/RegistryTest.php Zend/Service Zend/Session -Zend/Soap Zend/Test Zend/Translator -Zend/Validator Zend/Wildfire -Zend/XmlRpc diff --git a/.travis/tested-components b/.travis/tested-components index 34047abc0..da5b101b4 100644 --- a/.travis/tested-components +++ b/.travis/tested-components @@ -1,40 +1,54 @@ -Zend/Mvc -Zend/View Zend/Acl Zend/Authentication +Zend/Cache Zend/Captcha Zend/Cloud +Zend/Code Zend/Config Zend/Console Zend/Crypt Zend/Currency Zend/Db Zend/Di +Zend/Docbook Zend/Dojo Zend/Dom Zend/EventManager +Zend/File +Zend/Filter Zend/Form +Zend/GData Zend/Http Zend/InfoCard +Zend/Json Zend/Ldap Zend/Loader +Zend/Locale Zend/Log +Zend/Mail Zend/Markup Zend/Measure Zend/Memory +Zend/Mime Zend/Module Zend/Mvc +Zend/Navigation Zend/OAuth +Zend/OpenId Zend/Pdf Zend/ProgressBar +Zend/RegistryTest.php Zend/Rest Zend/Search Zend/Serializer Zend/Server +Zend/Soap Zend/Stdlib Zend/Tag Zend/Text Zend/TimeSync Zend/Uri +Zend/Validator Zend/VersionTest.php Zend/View +Zend/XmlRpc From 49c983cbb443e692e54b185edf02b673fde8b570 Mon Sep 17 00:00:00 2001 From: Marco Pivetta Date: Wed, 4 Apr 2012 22:16:58 +0200 Subject: [PATCH 241/311] Fixing exit code and output of test runner The test-runner will run all test suites and display their names anyway, then use an appropriate exit code in case of failures. Using the list of components to be tested (was using the skipped components list to be sure that the exit code of the test runner were correct). --- .travis/run-tests.sh | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis/run-tests.sh b/.travis/run-tests.sh index 47d0c4a07..11d98cd6a 100755 --- a/.travis/run-tests.sh +++ b/.travis/run-tests.sh @@ -2,7 +2,13 @@ travisdir=$(dirname $(readlink /proc/$$/fd/255)) testdir="$travisdir/../tests" testedcomponents=(`cat "$travisdir/tested-components"`) +result=0 for tested in "${testedcomponents[@]}" - do phpunit -c $testdir/phpunit.xml $testdir/$tested + do + echo "$tested:" + phpunit -c $testdir/phpunit.xml $testdir/$tested + let "result = $result || $?" done + +exit $result \ No newline at end of file From b27fc250cea6794ba744776e247c1585734882bc Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 9 Apr 2012 11:28:58 -0500 Subject: [PATCH 242/311] [zendframework/zf2#1008] Updated test lists - Moved Session, Paginator to tested-components - Added Zend/Feed/Reader, Writer to tested-components --- .travis/skipped-components | 2 -- .travis/tested-components | 4 ++++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis/skipped-components b/.travis/skipped-components index 6ccd1be13..6847359d1 100644 --- a/.travis/skipped-components +++ b/.travis/skipped-components @@ -2,10 +2,8 @@ Zend/Amf Zend/Barcode Zend/Date Zend/Feed -Zend/Paginator Zend/Queue Zend/Service -Zend/Session Zend/Test Zend/Translator Zend/Wildfire diff --git a/.travis/tested-components b/.travis/tested-components index da5b101b4..330e5f196 100644 --- a/.travis/tested-components +++ b/.travis/tested-components @@ -14,6 +14,8 @@ Zend/Docbook Zend/Dojo Zend/Dom Zend/EventManager +Zend/Feed/Reader +Zend/Feed/Writer Zend/File Zend/Filter Zend/Form @@ -35,6 +37,7 @@ Zend/Mvc Zend/Navigation Zend/OAuth Zend/OpenId +Zend/Paginator Zend/Pdf Zend/ProgressBar Zend/RegistryTest.php @@ -42,6 +45,7 @@ Zend/Rest Zend/Search Zend/Serializer Zend/Server +Zend/Session Zend/Soap Zend/Stdlib Zend/Tag From 5a92a779591519f3a6451e3d3b98411aff2defed Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Apr 2012 00:59:16 +0200 Subject: [PATCH 243/311] format --- src/Storage/Plugin.php | 1 - src/Storage/Plugin/AbstractPlugin.php | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Storage/Plugin.php b/src/Storage/Plugin.php index b4c4bf8f9..00ce3a46c 100644 --- a/src/Storage/Plugin.php +++ b/src/Storage/Plugin.php @@ -57,5 +57,4 @@ public function setOptions(Plugin\PluginOptions $options); * @return PluginOptions */ public function getOptions(); - } diff --git a/src/Storage/Plugin/AbstractPlugin.php b/src/Storage/Plugin/AbstractPlugin.php index 2850a4c59..b833144c0 100644 --- a/src/Storage/Plugin/AbstractPlugin.php +++ b/src/Storage/Plugin/AbstractPlugin.php @@ -61,5 +61,4 @@ public function getOptions() } return $this->options; } - } From e9ecc1a18a34eadf1494d4862d2d481e5b26846a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Apr 2012 01:14:33 +0200 Subject: [PATCH 244/311] added missing @param --- src/Storage/Adapter/AbstractAdapter.php | 1 + src/Storage/Plugin/ClearByFactor.php | 1 + src/Storage/Plugin/ExceptionHandler.php | 1 + src/Storage/Plugin/IgnoreUserAbort.php | 1 + src/Storage/Plugin/OptimizeByFactor.php | 1 + src/Storage/Plugin/Serializer.php | 1 + 6 files changed, 6 insertions(+) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index da9832668..e492fb0e6 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -324,6 +324,7 @@ public function hasPlugin(Plugin $plugin) * Register a plugin * * @param Plugin $plugin + * @param int $priority * @return AbstractAdapter Fluent interface * @throws Exception\LogicException */ diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 05b0f75c8..836cfa12f 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -47,6 +47,7 @@ class ClearByFactor extends AbstractPlugin * Attach * * @param EventCollection $eventCollection + * @param int $priority * @return ClearByFactor * @throws Exception\LogicException */ diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 44e3d7f41..5c5f31c21 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -45,6 +45,7 @@ class ExceptionHandler extends AbstractPlugin * Attach * * @param EventCollection $eventCollection + * @param int $priority * @return ExceptionHandler * @throws Exception\LogicException */ diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php index 9819513d5..2324296f3 100644 --- a/src/Storage/Plugin/IgnoreUserAbort.php +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -53,6 +53,7 @@ class IgnoreUserAbort extends AbstractPlugin * Attach * * @param EventCollection $eventCollection + * @param int $priority * @return Serializer * @throws Exception\LogicException */ diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index 772ec1754..851b7846f 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -46,6 +46,7 @@ class OptimizeByFactor extends AbstractPlugin * Attach * * @param EventCollection $eventCollection + * @param int $priority * @return OptimizeByFactor * @throws Exception\LogicException */ diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 9dffcd11c..4345abbaa 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -54,6 +54,7 @@ class Serializer extends AbstractPlugin * Attach * * @param EventCollection $eventCollection + * @param int $priority * @return Serializer * @throws Exception\LogicException */ From f08355791f96663082724ea14f1e210c21e577ae Mon Sep 17 00:00:00 2001 From: Rob Allen Date: Mon, 23 Apr 2012 20:30:10 +0100 Subject: [PATCH 245/311] Typo fix: messagae => message --- src/Utils.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Utils.php b/src/Utils.php index 8c3aca561..4ab240f40 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -93,7 +93,7 @@ public static function getSystemMemoryCapacity() // *nix if (false === ($meminfo = @file_get_contents('/proc/meminfo'))) { $lastErr = error_get_last(); - throw new Exception\RuntimeException("Can't read '/proc/meminfo': {$lastErr['messagae']}"); + throw new Exception\RuntimeException("Can't read '/proc/meminfo': {$lastErr['message']}"); } elseif (!preg_match_all('/(\w+):\s*(\d+\s*\w*)[\r|\n]/i', $meminfo, $matches, PREG_PATTERN_ORDER)) { throw new Exception\RuntimeException("Can't parse '/proc/meminfo'"); } From 53599fc508239cc11f4c3ca6a22a8dcfe407e68f Mon Sep 17 00:00:00 2001 From: Rob Allen Date: Mon, 23 Apr 2012 20:31:19 +0100 Subject: [PATCH 246/311] use realpath() to ensure that test passes on Max OS X where sys_get_temp_dir() and realpath(sys_get_temp_dir()) are two different things. --- test/Storage/Adapter/FilesystemTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index f1de88c6f..19f661b3f 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -89,7 +89,7 @@ protected function _removeRecursive($dir) public function testNormalizeCacheDir() { - $cacheDir = $cacheDirExpected = sys_get_temp_dir(); + $cacheDir = $cacheDirExpected = realpath(sys_get_temp_dir()); if (DIRECTORY_SEPARATOR != '/') { $cacheDir = str_replace(DIRECTORY_SEPARATOR, '/', $cacheDir); From 203f6bbb240db0ce876e3ba0ffa2c2bd0237273b Mon Sep 17 00:00:00 2001 From: Gabriel Baker Date: Sat, 21 Apr 2012 22:28:24 +0100 Subject: [PATCH 247/311] Fixed un-needed use statements --- src/Exception/BadMethodCallException.php | 2 -- src/Exception/ExtensionNotLoadedException.php | 2 -- src/Exception/InvalidArgumentException.php | 2 -- src/Exception/LogicException.php | 2 -- src/Exception/OutOfCapacityException.php | 2 -- src/Exception/RuntimeException.php | 2 -- src/Exception/UnexpectedValueException.php | 2 -- src/Exception/UnsupportedMethodCallException.php | 2 -- 8 files changed, 16 deletions(-) diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index f36d3a306..9eab64712 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/ExtensionNotLoadedException.php b/src/Exception/ExtensionNotLoadedException.php index 7d2b975ef..330f773a2 100644 --- a/src/Exception/ExtensionNotLoadedException.php +++ b/src/Exception/ExtensionNotLoadedException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index f61f4c9a0..b59446342 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/LogicException.php b/src/Exception/LogicException.php index b5da1a017..6d4f4b5f3 100644 --- a/src/Exception/LogicException.php +++ b/src/Exception/LogicException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/OutOfCapacityException.php b/src/Exception/OutOfCapacityException.php index 017f14092..2dfaef98a 100644 --- a/src/Exception/OutOfCapacityException.php +++ b/src/Exception/OutOfCapacityException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/RuntimeException.php b/src/Exception/RuntimeException.php index 6cb3c1fd0..432113373 100644 --- a/src/Exception/RuntimeException.php +++ b/src/Exception/RuntimeException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/UnexpectedValueException.php b/src/Exception/UnexpectedValueException.php index b89b01629..17d4c86dc 100644 --- a/src/Exception/UnexpectedValueException.php +++ b/src/Exception/UnexpectedValueException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache diff --git a/src/Exception/UnsupportedMethodCallException.php b/src/Exception/UnsupportedMethodCallException.php index 5337978f8..0cdf67848 100644 --- a/src/Exception/UnsupportedMethodCallException.php +++ b/src/Exception/UnsupportedMethodCallException.php @@ -20,8 +20,6 @@ namespace Zend\Cache\Exception; -use Zend\Cache\Exception\ExceptionInterface; - /** * @category Zend * @package Zend_Cache From e53dc2974894a55b8faa2f5241bddad1f06c3130 Mon Sep 17 00:00:00 2001 From: Gabriel Baker Date: Tue, 24 Apr 2012 21:42:34 +0100 Subject: [PATCH 248/311] Fixed CS issues --- src/Storage/Adapter/AdapterOptions.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 0e31756a7..629dc87de 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -23,7 +23,6 @@ use ArrayObject, Zend\Cache\Exception, - Zend\Cache\Storage\Adapter, Zend\Cache\Storage\Event, Zend\Stdlib\Options; @@ -117,10 +116,10 @@ public function toArray() /** * Adapter using this instance * - * @param Adapter\AdapterInterface|null $adapter + * @param AdapterInterface|null $adapter * @return AdapterOptions */ - public function setAdapter(Adapter\AdapterInterface $adapter = null) + public function setAdapter(AdapterInterface $adapter = null) { $this->adapter = $adapter; return $this; From 8e91278e8a76be4e677ec97cd2efd516b271f87c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 25 Apr 2012 23:09:32 +0200 Subject: [PATCH 249/311] added Zend\EventManager\EventsAware and use it instead of EventManagerAware, removed AbstractAdapter::setEventManager to not allow overwriting it --- src/Storage/Adapter/AbstractAdapter.php | 21 +++------------------ src/Storage/Adapter/AdapterOptions.php | 6 +++--- src/Storage/Capabilities.php | 4 ++-- 3 files changed, 8 insertions(+), 23 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index d0cc0f498..1c30af08c 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -34,7 +34,7 @@ Zend\Cache\Storage\Plugin, Zend\EventManager\EventCollection, Zend\EventManager\EventManager, - Zend\EventManager\EventManagerAware; + Zend\EventManager\EventsAware; /** * @category Zend @@ -43,7 +43,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -abstract class AbstractAdapter implements Adapter, EventManagerAware +abstract class AbstractAdapter implements Adapter, EventsAware { /** * The used EventManager if any @@ -222,18 +222,6 @@ public function getCaching() /* Event/Plugin handling */ - /** - * Set event manager instance - * - * @param EventCollection $events - * @return AbstractAdapter - */ - public function setEventManager(EventCollection $events) - { - $this->events = $events; - return $this; - } - /** * Get the event manager * @@ -242,10 +230,7 @@ public function setEventManager(EventCollection $events) public function events() { if ($this->events === null) { - $this->setEventManager(new EventManager(array( - __CLASS__, - get_called_class(), - ))); + $this->events = new EventManager(array(__CLASS__, get_called_class())); } return $this->events; } diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index a8655a6e4..dcaa0a790 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -25,7 +25,7 @@ Zend\Cache\Exception, Zend\Cache\Storage\Adapter, Zend\Cache\Storage\Event, - Zend\EventManager\EventManagerAware, + Zend\EventManager\EventsAware, Zend\Stdlib\Options; /** @@ -355,7 +355,7 @@ public function getWritable() /** * Triggers an option event if this options instance has a connection to - * an adapter implements EventManagerAware. + * an adapter implements EventsAware. * * @param string $optionName * @param mixed $optionValue @@ -363,7 +363,7 @@ public function getWritable() */ protected function triggerOptionEvent($optionName, $optionValue) { - if ($this->adapter instanceof EventManagerAware) { + if ($this->adapter instanceof EventsAware) { $event = new Event('option', $this->adapter, new ArrayObject(array($optionName => $optionValue))); $this->adapter->events()->trigger($event); } diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 95a4dd562..11a8c7c47 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -24,7 +24,7 @@ use ArrayObject, stdClass, Zend\Cache\Exception, - Zend\EventManager\EventManagerAware; + Zend\EventManager\EventsAware; /** * @category Zend @@ -572,7 +572,7 @@ protected function setCapability(stdClass $marker, $name, $value) $this->$property = $value; // trigger event - if ($this->adapter instanceof EventManagerAware) { + if ($this->adapter instanceof EventsAware) { $this->adapter->events()->trigger('capability', $this->adapter, new ArrayObject(array( $name => $value ))); From 96eae5662c7ddf01298b2a5bd18cf23d255cbebd Mon Sep 17 00:00:00 2001 From: Rob Allen Date: Tue, 1 May 2012 06:31:33 +0100 Subject: [PATCH 250/311] Ensure that we're checking for the correct path as realpath(sys_get_temp_dir()) is different on OS X to sys_get_temp_dir() --- test/Storage/Adapter/FilesystemTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index f1de88c6f..19f661b3f 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -89,7 +89,7 @@ protected function _removeRecursive($dir) public function testNormalizeCacheDir() { - $cacheDir = $cacheDirExpected = sys_get_temp_dir(); + $cacheDir = $cacheDirExpected = realpath(sys_get_temp_dir()); if (DIRECTORY_SEPARATOR != '/') { $cacheDir = str_replace(DIRECTORY_SEPARATOR, '/', $cacheDir); From 51800af3e4a7fcb76b3fbf681b54f29073b30eec Mon Sep 17 00:00:00 2001 From: Rob Allen Date: Tue, 1 May 2012 07:28:56 +0100 Subject: [PATCH 251/311] add getSystemMemoryCapacityOSX() --- src/Utils.php | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/src/Utils.php b/src/Utils.php index 8c3aca561..7f7eb5d1b 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -90,10 +90,15 @@ public static function getSystemMemoryCapacity() return self::getSystemMemoryCapacityWin(); } + // Darwin + if (substr(\PHP_OS, 0, 6) == 'Darwin') { + return self::getSystemMemoryCapacityOSX(); + } + // *nix if (false === ($meminfo = @file_get_contents('/proc/meminfo'))) { $lastErr = error_get_last(); - throw new Exception\RuntimeException("Can't read '/proc/meminfo': {$lastErr['messagae']}"); + throw new Exception\RuntimeException("Can't read '/proc/meminfo': {$lastErr['message']}"); } elseif (!preg_match_all('/(\w+):\s*(\d+\s*\w*)[\r|\n]/i', $meminfo, $matches, PREG_PATTERN_ORDER)) { throw new Exception\RuntimeException("Can't parse '/proc/meminfo'"); } @@ -174,6 +179,62 @@ static protected function getSystemMemoryCapacityWin() ); } + /** + * Get system memory capacity on windows systems + * + * @return array + * @throws Exception\RuntimeException + */ + static protected function getSystemMemoryCapacityOSX() + { + $total = 0; + $free = 0; + + if (!function_exists('exec')) { + throw new Exception\RuntimeException( + "Built-in function 'exec' is disabled" + ); + } else { + // sysctl will tell us the total amount of memory + $cmd = 'sysctl -n hw.memsize'; + $out = $ret = null; + $line = exec($cmd, $out, $ret); + + if ($ret) { + $out = implode("\n", $out); + throw new Exception\RuntimeException( + "Command '{$cmd}' failed" + . ", return: '{$ret}'" + . ", output: '{$out}'" + ); + } + $total = $line; + + // now work out amount used using vm_stat + $cmd = 'vm_stat | grep free'; + $out = $ret = null; + $line = exec($cmd, $out, $ret); + + if ($ret) { + $out = implode("\n", $out); + throw new Exception\RuntimeException( + "Command '{$cmd}' failed" + . ", return: '{$ret}'" + . ", output: '{$out}'" + ); + } + preg_match('/([\d]+)/', $line, $matches); + if (isset($matches[1])) { + $free = $matches[1] * 4096; + } + } + + return array( + 'total' => $total, + 'free' => $free, + ); + } + /** * Generate a hash value. * From 8a1e2d2a9ef321af69ded7e46decdb8969928d70 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 7 May 2012 12:20:17 -0500 Subject: [PATCH 252/311] [zen-27] Cache -- EM typehinting - Typehint on EventManagerInterface, not EventCollection --- src/Storage/Adapter/AbstractAdapter.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 386e86cbf..721f9fb2c 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -31,8 +31,8 @@ Zend\Cache\Storage\ExceptionEvent, Zend\Cache\Storage\PostEvent, Zend\Cache\Storage\Plugin, - Zend\EventManager\EventCollection, Zend\EventManager\EventManager, + Zend\EventManager\EventManagerInterface, Zend\EventManager\EventManagerAware; /** @@ -224,11 +224,15 @@ public function getCaching() /** * Set event manager instance * - * @param EventCollection $events + * @param EventManagerInterface $events * @return AbstractAdapter */ - public function setEventManager(EventCollection $events) + public function setEventManager(EventManagerInterface $events) { + $events->setIdentifiers(array( + __CLASS__, + get_called_class(), + )); $this->events = $events; return $this; } @@ -241,10 +245,7 @@ public function setEventManager(EventCollection $events) public function events() { if ($this->events === null) { - $this->setEventManager(new EventManager(array( - __CLASS__, - get_called_class(), - ))); + $this->setEventManager(new EventManager()); } return $this->events; } From 03facac393fa2ce280f13024a4f05fd7fc730689 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 7 May 2012 12:40:22 -0500 Subject: [PATCH 253/311] [zen-27] Update all classes that were EventManagerAware - to use EventManagerAwareInterface - also fixed some test cases that were still using setSharedCollections() to use setSharedManager() --- src/Storage/Adapter/AbstractAdapter.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 721f9fb2c..277c5ca51 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -32,8 +32,8 @@ Zend\Cache\Storage\PostEvent, Zend\Cache\Storage\Plugin, Zend\EventManager\EventManager, - Zend\EventManager\EventManagerInterface, - Zend\EventManager\EventManagerAware; + Zend\EventManager\EventManagerAwareInterface, + Zend\EventManager\EventManagerInterface; /** * @category Zend @@ -42,7 +42,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -abstract class AbstractAdapter implements AdapterInterface, EventManagerAware +abstract class AbstractAdapter implements AdapterInterface, EventManagerAwareInterface { /** * The used EventManager if any From 613e32b818848708b3efed4b31607a9811445210 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 7 May 2012 13:34:18 -0500 Subject: [PATCH 254/311] [zen-27] use correct typehint in constructor - s/Adapter/Adapter\AdapterInterface/ --- src/Storage/Capabilities.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index b477a2a0e..e7dbb17d1 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -142,7 +142,7 @@ class Capabilities * @param null|Capabilities $baseCapabilities */ public function __construct( - Adapter $adapter, + Adapter\AdapterInterface $adapter, stdClass $marker, array $capabilities = array(), Capabilities $baseCapabilities = null From 8648880b9b75837ca51fecc5c7c8bc1b82bde502 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 7 May 2012 21:15:12 +0200 Subject: [PATCH 255/311] renamed $eventCollection to $events --- src/Storage/Plugin/ClearByFactor.php | 22 ++++---- src/Storage/Plugin/ExceptionHandler.php | 72 ++++++++++++------------- src/Storage/Plugin/IgnoreUserAbort.php | 2 +- src/Storage/Plugin/OptimizeByFactor.php | 22 ++++---- src/Storage/Plugin/Serializer.php | 2 +- 5 files changed, 60 insertions(+), 60 deletions(-) diff --git a/src/Storage/Plugin/ClearByFactor.php b/src/Storage/Plugin/ClearByFactor.php index 78b726baa..51f3b7d0a 100644 --- a/src/Storage/Plugin/ClearByFactor.php +++ b/src/Storage/Plugin/ClearByFactor.php @@ -46,14 +46,14 @@ class ClearByFactor extends AbstractPlugin /** * Attach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @param int $priority * @return ClearByFactor * @throws Exception\LogicException */ - public function attach(EventManagerInterface $eventCollection, $priority = 1) + public function attach(EventManagerInterface $events, $priority = 1) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (isset($this->handles[$index])) { throw new Exception\LogicException('Plugin already attached'); } @@ -62,10 +62,10 @@ public function attach(EventManagerInterface $eventCollection, $priority = 1) $this->handles[$index] = & $handles; $callback = array($this, 'clearByFactor'); - $handles[] = $eventCollection->attach('setItem.post', $callback, $priority); - $handles[] = $eventCollection->attach('setItems.post', $callback, $priority); - $handles[] = $eventCollection->attach('addItem.post', $callback, $priority); - $handles[] = $eventCollection->attach('addItems.post', $callback, $priority); + $handles[] = $events->attach('setItem.post', $callback, $priority); + $handles[] = $events->attach('setItems.post', $callback, $priority); + $handles[] = $events->attach('addItem.post', $callback, $priority); + $handles[] = $events->attach('addItems.post', $callback, $priority); return $this; } @@ -73,20 +73,20 @@ public function attach(EventManagerInterface $eventCollection, $priority = 1) /** * Detach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @return ClearByFactor * @throws Exception\LogicException */ - public function detach(EventManagerInterface $eventCollection) + public function detach(EventManagerInterface $events) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (!isset($this->handles[$index])) { throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index foreach ($this->handles[$index] as $handle) { - $eventCollection->detach($handle); + $events->detach($handle); } // remove all detached handles diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index cc1b8af10..4e8bc202b 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -44,14 +44,14 @@ class ExceptionHandler extends AbstractPlugin /** * Attach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @param int $priority * @return ExceptionHandler * @throws Exception\LogicException */ - public function attach(EventManagerInterface $eventCollection, $priority = 1) + public function attach(EventManagerInterface $events, $priority = 1) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (isset($this->handles[$index])) { throw new Exception\LogicException('Plugin already attached'); } @@ -61,54 +61,54 @@ public function attach(EventManagerInterface $eventCollection, $priority = 1) $this->handles[$index] = & $handles; // read - $handles[] = $eventCollection->attach('getItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('getItems.exception', $callback, $priority); + $handles[] = $events->attach('getItem.exception', $callback, $priority); + $handles[] = $events->attach('getItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('hasItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('hasItems.exception', $callback, $priority); + $handles[] = $events->attach('hasItem.exception', $callback, $priority); + $handles[] = $events->attach('hasItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('getMetadata.exception', $callback, $priority); - $handles[] = $eventCollection->attach('getMetadatas.exception', $callback, $priority); + $handles[] = $events->attach('getMetadata.exception', $callback, $priority); + $handles[] = $events->attach('getMetadatas.exception', $callback, $priority); // non-blocking - $handles[] = $eventCollection->attach('getDelayed.exception', $callback, $priority); - $handles[] = $eventCollection->attach('find.exception', $callback, $priority); + $handles[] = $events->attach('getDelayed.exception', $callback, $priority); + $handles[] = $events->attach('find.exception', $callback, $priority); - $handles[] = $eventCollection->attach('fetch.exception', $callback, $priority); - $handles[] = $eventCollection->attach('fetchAll.exception', $callback, $priority); + $handles[] = $events->attach('fetch.exception', $callback, $priority); + $handles[] = $events->attach('fetchAll.exception', $callback, $priority); // write - $handles[] = $eventCollection->attach('setItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('setItems.exception', $callback, $priority); + $handles[] = $events->attach('setItem.exception', $callback, $priority); + $handles[] = $events->attach('setItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('addItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('addItems.exception', $callback, $priority); + $handles[] = $events->attach('addItem.exception', $callback, $priority); + $handles[] = $events->attach('addItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('replaceItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('replaceItems.exception', $callback, $priority); + $handles[] = $events->attach('replaceItem.exception', $callback, $priority); + $handles[] = $events->attach('replaceItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('touchItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('touchItems.exception', $callback, $priority); + $handles[] = $events->attach('touchItem.exception', $callback, $priority); + $handles[] = $events->attach('touchItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('removeItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('removeItems.exception', $callback, $priority); + $handles[] = $events->attach('removeItem.exception', $callback, $priority); + $handles[] = $events->attach('removeItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('checkAndSetItem.exception', $callback, $priority); + $handles[] = $events->attach('checkAndSetItem.exception', $callback, $priority); // increment / decrement item(s) - $handles[] = $eventCollection->attach('incrementItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('incrementItems.exception', $callback, $priority); + $handles[] = $events->attach('incrementItem.exception', $callback, $priority); + $handles[] = $events->attach('incrementItems.exception', $callback, $priority); - $handles[] = $eventCollection->attach('decrementItem.exception', $callback, $priority); - $handles[] = $eventCollection->attach('decrementItems.exception', $callback, $priority); + $handles[] = $events->attach('decrementItem.exception', $callback, $priority); + $handles[] = $events->attach('decrementItems.exception', $callback, $priority); // clear - $handles[] = $eventCollection->attach('clear.exception', $callback, $priority); - $handles[] = $eventCollection->attach('clearByNamespace.exception', $callback, $priority); + $handles[] = $events->attach('clear.exception', $callback, $priority); + $handles[] = $events->attach('clearByNamespace.exception', $callback, $priority); // additional - $handles[] = $eventCollection->attach('optimize.exception', $callback, $priority); - $handles[] = $eventCollection->attach('getCapacity.exception', $callback, $priority); + $handles[] = $events->attach('optimize.exception', $callback, $priority); + $handles[] = $events->attach('getCapacity.exception', $callback, $priority); return $this; } @@ -116,20 +116,20 @@ public function attach(EventManagerInterface $eventCollection, $priority = 1) /** * Detach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @return ExceptionHandler * @throws Exception\LogicException */ - public function detach(EventManagerInterface $eventCollection) + public function detach(EventManagerInterface $events) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (!isset($this->handles[$index])) { throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index foreach ($this->handles[$index] as $handle) { - $eventCollection->detach($handle); + $events->detach($handle); } // remove all detached handles diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php index f3c3f4ec2..4c8703b4d 100644 --- a/src/Storage/Plugin/IgnoreUserAbort.php +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -51,7 +51,7 @@ class IgnoreUserAbort extends AbstractPlugin /** * Attach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @param int $priority * @return Serializer * @throws Exception\LogicException diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index 57d967f3b..a72f24096 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -45,14 +45,14 @@ class OptimizeByFactor extends AbstractPlugin /** * Attach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @param int $priority * @return OptimizeByFactor * @throws Exception\LogicException */ - public function attach(EventManagerInterface $eventCollection, $priority = 1) + public function attach(EventManagerInterface $events, $priority = 1) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (isset($this->handles[$index])) { throw new Exception\LogicException('Plugin already attached'); } @@ -61,10 +61,10 @@ public function attach(EventManagerInterface $eventCollection, $priority = 1) $this->handles[$index] = & $handles; $callback = array($this, 'optimizeByFactor'); - $handles[] = $eventCollection->attach('removeItem.post', $callback, $priority); - $handles[] = $eventCollection->attach('removeItems.post', $callback, $priority); - $handles[] = $eventCollection->attach('clear.post', $callback, $priority); - $handles[] = $eventCollection->attach('clearByNamespace.post', $callback, $priority); + $handles[] = $events->attach('removeItem.post', $callback, $priority); + $handles[] = $events->attach('removeItems.post', $callback, $priority); + $handles[] = $events->attach('clear.post', $callback, $priority); + $handles[] = $events->attach('clearByNamespace.post', $callback, $priority); return $this; } @@ -72,20 +72,20 @@ public function attach(EventManagerInterface $eventCollection, $priority = 1) /** * Detach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @return OptimizeByFactor * @throws Exception\LogicException */ - public function detach(EventManagerInterface $eventCollection) + public function detach(EventManagerInterface $events) { - $index = spl_object_hash($eventCollection); + $index = spl_object_hash($events); if (!isset($this->handles[$index])) { throw new Exception\LogicException('Plugin not attached'); } // detach all handles of this index foreach ($this->handles[$index] as $handle) { - $eventCollection->detach($handle); + $events->detach($handle); } // remove all detached handles diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 982ff359c..3916e5eee 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -53,7 +53,7 @@ class Serializer extends AbstractPlugin /** * Attach * - * @param EventManagerInterface $eventCollection + * @param EventManagerInterface $events * @param int $priority * @return Serializer * @throws Exception\LogicException From 9515dc7ddc38d03180dec110a5a0212fdcb9747f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 7 May 2012 23:43:41 +0200 Subject: [PATCH 256/311] Cache: added umask test and small code format --- src/Storage/Adapter/AbstractAdapter.php | 6 +++--- test/Storage/Adapter/FilesystemTest.php | 10 +++++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 9b2434678..c5987136d 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -899,13 +899,13 @@ public function setItems(array $keyValuePairs, array $options = array()) */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $result = array(); + $failedKeys = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { if (!$this->internalSetItem($normalizedKey, $value, $normalizedOptions)) { - $result[] = $normalizedKey; + $failedKeys[] = $normalizedKey; } } - return $result; + return $failedKeys; } /** diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 19f661b3f..3f3d3f452 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -35,9 +35,12 @@ class FilesystemTest extends CommonAdapterTest { protected $_tmpCacheDir; + protected $_umask; public function setUp() { + $this->_umask = umask(); + $this->_tmpCacheDir = @tempnam(sys_get_temp_dir(), 'zend_cache_test_'); if (!$this->_tmpCacheDir) { $err = error_get_last(); @@ -47,7 +50,7 @@ public function setUp() $this->fail("Can't remove temporary cache directory-file: {$err['message']}"); } elseif (!@mkdir($this->_tmpCacheDir, 0777)) { $err = error_get_last(); - $this->fail("Can't create temporaty cache directory: {$err['message']}"); + $this->fail("Can't create temporary cache directory: {$err['message']}"); } $this->_options = new Cache\Storage\Adapter\FilesystemOptions(array( @@ -63,6 +66,11 @@ public function tearDown() { $this->_removeRecursive($this->_tmpCacheDir); + if ($this->_umask != umask()) { + umask($this->_umask); + $this->fail("Umask wasn't reset"); + } + parent::tearDown(); } From e6c72a9843bb2f8440da99b73228f7adac453476 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 8 May 2012 00:12:05 +0200 Subject: [PATCH 257/311] filesystem adapter: split logic to create the directory structure into an own method --- src/Storage/Adapter/Filesystem.php | 76 +++++++++++++----------------- 1 file changed, 32 insertions(+), 44 deletions(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 1bdb76942..11f094782 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -705,24 +705,8 @@ public function replaceItems(array $keyValuePairs, array $options = array()) protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) { $baseOptions = $this->getOptions(); - $oldUmask = null; $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - - if ($baseOptions->getDirLevel() > 0) { - $path = dirname($filespec); - if (!file_exists($path)) { - $oldUmask = umask($baseOptions->getDirUmask()); - ErrorHandler::start(); - $mkdir = mkdir($path, 0777, true); - $error = ErrorHandler::stop(); - if (!$mkdir) { - umask($oldUmask); - throw new Exception\RuntimeException( - "Error creating directory '{$path}'", 0, $error - ); - } - } - } + $this->prepareDirectoryStructure($filespec); $info = null; if ($baseOptions->getReadControl()) { @@ -736,11 +720,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz // write files try { // set umask for files - if ($oldUmask !== null) { // $oldUmask could be defined on create directory - umask($baseOptions->getFileUmask()); - } else { - $oldUmask = umask($baseOptions->getFileUmask()); - } + $oldUmask = umask($baseOptions->getFileUmask()); $contents = array($filespec . '.dat' => & $value); if ($info) { @@ -796,23 +776,7 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n $contents = array(); foreach ($normalizedKeyValuePairs as $key => & $value) { $filespec = $this->getFileSpec($key, $normalizedOptions); - - // init directory level - if ($baseOptions->getDirLevel() > 0) { - $path = dirname($filespec); - if (!file_exists($path)) { - $oldUmask = ($oldUmask === null) ? umask($baseOptions->getDirUmask()) : $oldUmask; - ErrorHandler::start(); - $mkdir = mkdir($path, 0777, true); - $error = ErrorHandler::stop(); - if (!$mkdir) { - umask($oldUmask); - throw new Exception\RuntimeException( - "Error creating directory '{$path}'", 0, $error - ); - } - } - } + $this->prepareDirectoryStructure($filespec); // *.dat file $contents[$filespec . '.dat'] = & $value; @@ -836,11 +800,7 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n // write to disk try { // set umask for files - if ($oldUmask !== null) { // $oldUmask could be defined on create directory - umask($baseOptions->getFileUmask()); - } else { - $oldUmask = umask($baseOptions->getFileUmask()); - } + $oldUmask = umask($baseOptions->getFileUmask()); while ($contents) { $nonBlocking = count($contents) > 1; @@ -1710,6 +1670,34 @@ protected function getFileContent($file, $nonBlocking = false, & $wouldblock = n return $res; } + /** + * Prepares a directory structure for the given file(spec) + * using the configured directory level. + * + * @param string $file + * @return void + * @throws Exception\RuntimeException + */ + protected function prepareDirectoryStructure($file) + { + $options = $this->getOptions(); + if ($options->getDirLevel() > 0) { + $path = dirname($file); + if (!file_exists($path)) { + $oldUmask = umask($options->getDirUmask()); + ErrorHandler::start(); + $mkdir = mkdir($path, 0777, true); + $error = ErrorHandler::stop(); + umask($oldUmask); + if (!$mkdir) { + throw new Exception\RuntimeException( + "Error creating directory '{$path}'", 0, $error + ); + } + } + } + } + /** * Write content to a file * From 65aacbac3a102f45a9eee97fdd52db4b5577285b Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Wed, 9 May 2012 11:28:05 -0500 Subject: [PATCH 258/311] Remove --stderr switch from Travis test runner - Appears that it may not be necessary --- .travis/run-tests.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis/run-tests.sh b/.travis/run-tests.sh index 1ba31be7e..9334e9597 100755 --- a/.travis/run-tests.sh +++ b/.travis/run-tests.sh @@ -7,7 +7,7 @@ result=0 for tested in "${testedcomponents[@]}" do echo "$tested:" - phpunit -c $testdir/phpunit.xml --stderr $testdir/$tested + phpunit -c $testdir/phpunit.xml $testdir/$tested result=$(($result || $?)) done From c8463a3aa146996f640edd03395452e71c8b3104 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 10 May 2012 23:48:58 +0200 Subject: [PATCH 259/311] Updated result values in cases of catched exceptions --- src/Storage/Adapter/AbstractAdapter.php | 103 ++++++++++++------- src/Storage/ExceptionEvent.php | 43 ++------ src/Storage/PostEvent.php | 10 +- test/Storage/Adapter/AbstractAdapterTest.php | 3 +- test/Storage/Plugin/ExceptionHandlerTest.php | 8 +- 5 files changed, 85 insertions(+), 82 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 3dc823414..74a48690d 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -248,12 +248,12 @@ protected function triggerPre($eventName, ArrayObject $args) /** * Triggers the PostEvent and return the result value. * - * @param string $eventName + * @param string $eventName * @param ArrayObject $args - * @param mixed $result + * @param mixed $result * @return mixed */ - protected function triggerPost($eventName, ArrayObject $args, &$result) + protected function triggerPost($eventName, ArrayObject $args, & $result) { $postEvent = new PostEvent($eventName . '.post', $this, $args, $result); $eventRs = $this->events()->trigger($postEvent); @@ -270,15 +270,16 @@ protected function triggerPost($eventName, ArrayObject $args, &$result) * If the ExceptionEvent has the flag "throwException" enabled throw the * exception after trigger else return the result. * - * @param string $eventName + * @param string $eventName * @param ArrayObject $args - * @param \Exception $exception + * @param mixed $result + * @param \Exception $exception * @throws Exception\ExceptionInterface * @return mixed */ - protected function triggerException($eventName, ArrayObject $args, \Exception $exception) + protected function triggerException($eventName, ArrayObject $args, & $result, \Exception $exception) { - $exceptionEvent = new ExceptionEvent($eventName . '.exception', $this, $args, $exception); + $exceptionEvent = new ExceptionEvent($eventName . '.exception', $this, $args, $result, $exception); $eventRs = $this->events()->trigger($exceptionEvent); if ($exceptionEvent->getThrowException()) { @@ -402,7 +403,8 @@ public function getItem($key, array $options = array(), & $success = null, & $ca $result = $this->internalGetItem($args['key'], $args['options'], $args['success'], $args['casToken']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -464,7 +466,8 @@ public function getItems(array $keys, array $options = array()) $result = $this->internalGetItems($args['keys'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array(); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -536,7 +539,8 @@ public function hasItem($key, array $options = array()) $result = $this->internalHasItem($args['key'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -601,7 +605,8 @@ public function hasItems(array $keys, array $options = array()) $result = $this->internalHasItems($args['keys'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array(); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -670,7 +675,8 @@ public function getMetadata($key, array $options = array()) $result = $this->internalGetMetadata($args['key'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -737,7 +743,8 @@ public function getMetadatas(array $keys, array $options = array()) $result = $this->internalGetMetadatas($args['keys'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array(); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -813,7 +820,8 @@ public function setItem($key, $value, array $options = array()) $result = $this->internalSetItem($args['key'], $args['value'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -878,7 +886,8 @@ public function setItems(array $keyValuePairs, array $options = array()) $result = $this->internalSetItems($args['keyValuePairs'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array_keys($keyValuePairs); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -953,7 +962,8 @@ public function addItem($key, $value, array $options = array()) $result = $this->internalAddItem($args['key'], $args['value'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1024,7 +1034,8 @@ public function addItems(array $keyValuePairs, array $options = array()) $result = $this->internalAddItems($args['keyValuePairs'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array_keys($keyValuePairs); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1099,7 +1110,8 @@ public function replaceItem($key, $value, array $options = array()) $result = $this->internalReplaceItem($args['key'], $args['value'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1171,7 +1183,8 @@ public function replaceItems(array $keyValuePairs, array $options = array()) $result = $this->internalReplaceItems($args['keyValuePairs'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array_keys($keyValuePairs); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1249,7 +1262,8 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) $result = $this->internalCheckAndSetItem($args['token'], $args['key'], $args['value'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1323,7 +1337,8 @@ public function touchItem($key, array $options = array()) $result = $this->internalTouchItem($args['key'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1400,7 +1415,7 @@ public function touchItems(array $keys, array $options = array()) $result = $this->internalTouchItems($args['keys'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + return $this->triggerException(__FUNCTION__, $args, $keys, $e); } } @@ -1467,7 +1482,8 @@ public function removeItem($key, array $options = array()) $result = $this->internalRemoveItem($args['key'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1523,7 +1539,7 @@ public function removeItems(array $keys, array $options = array()) $result = $this->internalRemoveItems($args['keys'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + return $this->triggerException(__FUNCTION__, $args, $keys, $e); } } @@ -1592,7 +1608,8 @@ public function incrementItem($key, $value, array $options = array()) $result = $this->internalIncrementItem($args['key'], $args['value'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1667,7 +1684,8 @@ public function incrementItems(array $keyValuePairs, array $options = array()) $result = $this->internalIncrementItems($args['keyValuePairs'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array(); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1739,7 +1757,8 @@ public function decrementItem($key, $value, array $options = array()) $result = $this->internalDecrementItem($args['key'], $args['value'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1814,7 +1833,8 @@ public function decrementItems(array $keyValuePairs, array $options = array()) $result = $this->internalDecrementItems($args['keyValuePairs'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array(); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1898,7 +1918,8 @@ public function getDelayed(array $keys, array $options = array()) $result = $this->internalGetDelayed($args['keys'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -1995,7 +2016,8 @@ public function find($mode = self::MATCH_ACTIVE, array $options = array()) $result = $this->internalFind($args['mode'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2047,7 +2069,8 @@ public function fetch() $result = $this->internalFetch(); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2138,7 +2161,8 @@ public function fetchAll() $result = $this->internalFetchAll(); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = array(); + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2201,7 +2225,8 @@ public function clear($mode = self::MATCH_EXPIRED, array $options = array()) $result = $this->internalClear($args['mode'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2270,7 +2295,8 @@ public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = a $result = $this->internalClearByNamespace($args['mode'], $args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2332,7 +2358,8 @@ public function optimize(array $options = array()) $result = $this->internalOptimize($args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2375,7 +2402,8 @@ public function getCapabilities() $result = $this->internalGetCapabilities(); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } @@ -2420,7 +2448,8 @@ public function getCapacity(array $options = array()) $result = $this->internalGetCapacity($args['options']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { - return $this->triggerException(__FUNCTION__, $args, $e); + $result = false; + return $this->triggerException(__FUNCTION__, $args, $result, $e); } } diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index 6865f9490..145c0c265 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -31,7 +31,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class ExceptionEvent extends Event +class ExceptionEvent extends PostEvent { /** * The exception to be thrown @@ -47,28 +47,21 @@ class ExceptionEvent extends Event */ protected $throwException = true; - /** - * The result/return value - * if the exception shouldn't throw - * - * @var mixed - */ - protected $result = false; - /** * Constructor * * Accept a target and its parameters. * - * @param string $name Event name - * @param Adapter $storage + * @param string $name + * @param Adapter $storage * @param ArrayObject $params - * @param Exception $exception + * @param mixed $result + * @param Exception $exception * @return void */ - public function __construct($name, Adapter\AdapterInterface $storage, ArrayObject $params, Exception $exception) + public function __construct($name, Adapter\AdapterInterface $storage, ArrayObject $params, & $result, Exception $exception) { - parent::__construct($name, $storage, $params); + parent::__construct($name, $storage, $params, $result); $this->setException($exception); } @@ -115,26 +108,4 @@ public function getThrowException() { return $this->throwException; } - - /** - * Set the result/return value - * - * @param mixed $value - * @return ExceptionEvent - */ - public function setResult(&$value) - { - $this->result = & $value; - return $this; - } - - /** - * Get the result/return value - * - * @return mixed - */ - public function & getResult() - { - return $this->result; - } } diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index 870f1f50a..497c20bbb 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -44,13 +44,13 @@ class PostEvent extends Event * * Accept a target and its parameters. * - * @param string $name Event name - * @param Adapter $storage + * @param string $name + * @param Adapter $storage * @param ArrayObject $params - * @param mixed $result + * @param mixed $result * @return void */ - public function __construct($name, Adapter\AdapterInterface $storage, ArrayObject $params, &$result) + public function __construct($name, Adapter\AdapterInterface $storage, ArrayObject $params, & $result) { parent::__construct($name, $storage, $params); $this->setResult($result); @@ -62,7 +62,7 @@ public function __construct($name, Adapter\AdapterInterface $storage, ArrayObjec * @param mixed $value * @return PostEvent */ - public function setResult(&$value) + public function setResult(& $value) { $this->result = & $value; return $this; diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 4cbad10cf..9d14cc996 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -250,6 +250,7 @@ public function testInternalTriggerExceptionThrowRuntimeException() $plugin = new \ZendTest\Cache\Storage\TestAsset\MockPlugin(); $this->_storage->addPlugin($plugin); + $result = null; $params = new \ArrayObject(array( 'key' => 'key1', 'value' => 'value1' @@ -260,7 +261,7 @@ public function testInternalTriggerExceptionThrowRuntimeException() $method->setAccessible(true); $this->setExpectedException('Zend\Cache\Exception\RuntimeException', 'test'); - $method->invokeArgs($this->_storage, array('setItem', $params, new Exception\RuntimeException('test'))); + $method->invokeArgs($this->_storage, array('setItem', $params, & $result, new Exception\RuntimeException('test'))); } public function testGetItemCallsInternalGetItem() diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php index 0bfb700d9..efac4fcff 100644 --- a/test/Storage/Plugin/ExceptionHandlerTest.php +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -110,10 +110,11 @@ public function testOnExceptionCallCallback() }); // run onException + $result = null; $event = new ExceptionEvent('getItem.exception', $this->_adapter, new ArrayObject(array( 'key' => 'key', 'options' => array() - )), $expectedException); + )), $result, $expectedException); $this->_plugin->onException($event); $this->assertTrue( @@ -127,14 +128,15 @@ public function testDontThrowException() $this->_options->setThrowExceptions(false); // run onException + $result = 'test'; $event = new ExceptionEvent('getItem.exception', $this->_adapter, new ArrayObject(array( 'key' => 'key', 'options' => array() - )), new \Exception()); + )), $result, new \Exception()); $this->_plugin->onException($event); $this->assertFalse($event->getThrowException()); - $this->assertFalse($event->getResult()); + $this->assertSame('test', $event->getResult()); } } From 7d3cc3c46efe4573d3739a3ad370a02cfa8cb04f Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 11 May 2012 00:46:10 +0200 Subject: [PATCH 260/311] updated docblocks --- src/Storage/Adapter/AbstractAdapter.php | 60 +++++++++++----------- src/Storage/Adapter/AbstractZendServer.php | 8 +-- src/Storage/Adapter/AdapterInterface.php | 36 ++++++------- src/Storage/Adapter/Apc.php | 22 ++++---- src/Storage/Adapter/Filesystem.php | 32 ++++++------ src/Storage/Adapter/Memcached.php | 18 +++---- src/Storage/Adapter/Memory.php | 20 ++++---- src/Storage/Adapter/WinCache.php | 26 +++------- src/Storage/Adapter/ZendServerDisk.php | 2 +- src/Storage/Adapter/ZendServerShm.php | 2 +- 10 files changed, 108 insertions(+), 118 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 74a48690d..21ecea584 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -371,7 +371,7 @@ public function getPlugins() * @param array $options * @param boolean $success * @param mixed $casToken - * @return mixed Data on success and null on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface * * @triggers getItem.pre(PreEvent) @@ -421,7 +421,7 @@ public function getItem($key, array $options = array(), & $success = null, & $ca * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken - * @return mixed Data on success or null on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ abstract protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null); @@ -437,7 +437,7 @@ abstract protected function internalGetItem(& $normalizedKey, array & $normalize * * @param array $keys * @param array $options - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface * * @triggers getItems.pre(PreEvent) @@ -482,7 +482,7 @@ public function getItems(array $keys, array $options = array()) * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -576,7 +576,7 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface * * @triggers hasItems.pre(PreEvent) @@ -621,7 +621,7 @@ public function hasItems(array $keys, array $options = array()) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface */ protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) @@ -646,7 +646,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * * @param string $key * @param array $options - * @return array|boolean Metadata or false on failure + * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * * @triggers getMetadata.pre(PreEvent) @@ -691,7 +691,7 @@ public function getMetadata($key, array $options = array()) * * @param string $normalizedKey * @param array $normalizedOptions - * @return array|boolean Metadata or false on failure + * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) @@ -714,7 +714,7 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti * * @param array $keys * @param array $options - * @return array Associative array of existing cache ids and its metadata + * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface * * @triggers getMetadatas.pre(PreEvent) @@ -759,7 +759,7 @@ public function getMetadatas(array $keys, array $options = array()) * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing cache ids and its metadata + * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface */ protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) @@ -857,7 +857,7 @@ abstract protected function internalSetItem(& $normalizedKey, & $value, array & * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface * * @triggers setItems.pre(PreEvent) @@ -904,7 +904,7 @@ public function setItems(array $keyValuePairs, array $options = array()) * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -1005,7 +1005,7 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface * * @triggers addItems.pre(PreEvent) @@ -1052,7 +1052,7 @@ public function addItems(array $keyValuePairs, array $options = array()) * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -1154,7 +1154,7 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface * * @triggers replaceItems.pre(PreEvent) @@ -1201,7 +1201,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalReplaceItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -1386,7 +1386,7 @@ protected function internalTouchItem(& $normalizedKey, array & $normalizedOption * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not updated keys * @throws Exception\ExceptionInterface * * @triggers touchItems.pre(PreEvent) @@ -1430,7 +1430,7 @@ public function touchItems(array $keys, array $options = array()) * * @param array $normalizedKeys * @param array $normalizedOptions - * @return boolean + * @return array Array of not updated keys * @throws Exception\ExceptionInterface */ protected function internalTouchItems(array & $normalizedKeys, array & $normalizedOptions) @@ -1510,7 +1510,7 @@ abstract protected function internalRemoveItem(& $normalizedKey, array & $normal * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not removed keys * @throws Exception\ExceptionInterface * * @triggers removeItems.pre(PreEvent) @@ -1552,7 +1552,7 @@ public function removeItems(array $keys, array $options = array()) * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) @@ -1578,7 +1578,7 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali * @param string $key * @param int $value * @param array $options - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface * * @triggers incrementItem.pre(PreEvent) @@ -1625,7 +1625,7 @@ public function incrementItem($key, $value, array $options = array()) * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -1655,7 +1655,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface * * @triggers incrementItems.pre(PreEvent) @@ -1700,7 +1700,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()) * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface */ protected function internalIncrementItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -1727,7 +1727,7 @@ protected function internalIncrementItems(array & $normalizedKeyValuePairs, arra * @param string $key * @param int $value * @param array $options - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface * * @triggers decrementItem.pre(PreEvent) @@ -1774,7 +1774,7 @@ public function decrementItem($key, $value, array $options = array()) * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -1804,7 +1804,7 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface * * @triggers incrementItems.pre(PreEvent) @@ -1849,7 +1849,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface */ protected function internalDecrementItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -2425,7 +2425,7 @@ protected function internalGetCapabilities() * Get storage capacity. * * @param array $options - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface * * @triggers getCapacity.pre(PreEvent) @@ -2457,7 +2457,7 @@ public function getCapacity(array $options = array()) * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ abstract protected function internalGetCapacity(array & $normalizedOptions); diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 879d506d8..349cdb1cf 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -55,7 +55,7 @@ abstract class AbstractZendServer extends AbstractAdapter * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken - * @return mixed Data on success or false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) @@ -82,7 +82,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -131,7 +131,7 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface */ protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) @@ -162,7 +162,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array|boolean + * @return array Associative array of keys and metadata * * @triggers getMetadatas.pre(PreEvent) * @triggers getMetadatas.post(PostEvent) diff --git a/src/Storage/Adapter/AdapterInterface.php b/src/Storage/Adapter/AdapterInterface.php index e8211068a..d89071c2e 100644 --- a/src/Storage/Adapter/AdapterInterface.php +++ b/src/Storage/Adapter/AdapterInterface.php @@ -110,9 +110,9 @@ public function getOptions(); * * @param string $key * @param array $options - * @param boolesn $success + * @param boolean $success * @param mixed $casToken - * @return mixed Data on success and false on failure + * @return mixed Data on success, null on failure * @throws \Zend\Cache\Exception\ExceptionInterface */ public function getItem($key, array $options = array(), & $success = null, & $casToken = null); @@ -122,7 +122,7 @@ public function getItem($key, array $options = array(), & $success = null, & $ca * * @param array $keys * @param array $options - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws \Zend\Cache\Exception\ExceptionInterface */ public function getItems(array $keys, array $options = array()); @@ -142,7 +142,7 @@ public function hasItem($key, array $options = array()); * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws \Zend\Cache\Exception\ExceptionInterface */ public function hasItems(array $keys, array $options = array()); @@ -152,7 +152,7 @@ public function hasItems(array $keys, array $options = array()); * * @param string $key * @param array $options - * @return array|boolean Metadata or false on failure + * @return array|boolean Metadata on success, false on failure * @throws \Zend\Cache\Exception\ExceptionInterface */ public function getMetadata($key, array $options = array()); @@ -162,7 +162,7 @@ public function getMetadata($key, array $options = array()); * * @param array $keys * @param array $options - * @return array Associative array of existing cache ids and its metadata + * @return array Associative array of keys and metadata * @throws \Zend\Cache\Exception\ExceptionInterface */ public function getMetadatas(array $keys, array $options = array()); @@ -173,8 +173,8 @@ public function getMetadatas(array $keys, array $options = array()); * Store an item. * * @param string $key - * @param mixed $value - * @param array $options + * @param mixed $value + * @param array $options * @return boolean * @throws \Zend\Cache\Exception\ExceptionInterface */ @@ -185,7 +185,7 @@ public function setItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws \Zend\Cache\Exception\ExceptionInterface */ public function setItems(array $keyValuePairs, array $options = array()); @@ -206,7 +206,7 @@ public function addItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws \Zend\Cache\Exception\ExceptionInterface */ public function addItems(array $keyValuePairs, array $options = array()); @@ -227,7 +227,7 @@ public function replaceItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws \Zend\Cache\Exception\ExceptionInterface */ public function replaceItems(array $keyValuePairs, array $options = array()); @@ -264,7 +264,7 @@ public function touchItem($key, array $options = array()); * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not updated keys * @throws \Zend\Cache\Exception\ExceptionInterface */ public function touchItems(array $keys, array $options = array()); @@ -284,7 +284,7 @@ public function removeItem($key, array $options = array()); * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not removed keys * @throws \Zend\Cache\Exception\ExceptionInterface */ public function removeItems(array $keys, array $options = array()); @@ -295,7 +295,7 @@ public function removeItems(array $keys, array $options = array()); * @param string $key * @param int $value * @param array $options - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws \Zend\Cache\Exception\ExceptionInterface */ public function incrementItem($key, $value, array $options = array()); @@ -305,7 +305,7 @@ public function incrementItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Associative array of keys and new values * @throws \Zend\Cache\Exception\ExceptionInterface */ public function incrementItems(array $keyValuePairs, array $options = array()); @@ -316,7 +316,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()); * @param string $key * @param int $value * @param array $options - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws \Zend\Cache\Exception\ExceptionInterface */ public function decrementItem($key, $value, array $options = array()); @@ -326,7 +326,7 @@ public function decrementItem($key, $value, array $options = array()); * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Associative array of keys and new values * @throws \Zend\Cache\Exception\ExceptionInterface */ public function decrementItems(array $keyValuePairs, array $options = array()); @@ -421,7 +421,7 @@ public function getCapabilities(); * Get storage capacity. * * @param array $options - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws \Zend\Cache\Exception\ExceptionInterface */ public function getCapacity(array $options = array()); diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 13441fd3e..3eb71e1c0 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -153,7 +153,7 @@ public function getOptions() * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken - * @return mixed Data on success or false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) @@ -179,7 +179,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -231,7 +231,7 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface */ protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) @@ -263,7 +263,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * * @param string $normalizedKey * @param array $normalizedOptions - * @return array|boolean Metadata or false on failure + * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * * @triggers getMetadata.pre(PreEvent) @@ -301,7 +301,7 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array + * @return array Associative array of keys and metadata * * @triggers getMetadatas.pre(PreEvent) * @triggers getMetadatas.post(PostEvent) @@ -374,7 +374,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -442,7 +442,7 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -525,7 +525,7 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) @@ -559,7 +559,7 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -593,7 +593,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -873,7 +873,7 @@ protected function internalGetCapabilities() * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 11f094782..b97d9856f 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -114,7 +114,7 @@ public function getOptions() * @param array $options * @param boolean $success * @param mixed $casToken - * @return mixed Data on success and false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface * * @triggers getItem.pre(PreEvent) @@ -142,7 +142,7 @@ public function getItem($key, array $options = array(), & $success = null, & $ca * * @param array $keys * @param array $options - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface * * @triggers getItems.pre(PreEvent) @@ -172,7 +172,7 @@ public function getItems(array $keys, array $options = array()) * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken - * @return mixed Data on success or false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) @@ -228,7 +228,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -321,7 +321,7 @@ public function hasItem($key, array $options = array()) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface * * @triggers hasItems.pre(PreEvent) @@ -382,9 +382,9 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) /** * Get metadata * - * @param $key - * @param array $options - * @return array|bool|mixed|null + * @param string $key + * @param array $options + * @return array|boolean Metadata on success, false on failure */ public function getMetadata($key, array $options = array()) { @@ -401,7 +401,7 @@ public function getMetadata($key, array $options = array()) * * @param array $keys * @param array $options - * @return array + * @return array Associative array of keys and metadata */ public function getMetadatas(array $keys, array $options = array()) { @@ -418,7 +418,7 @@ public function getMetadatas(array $keys, array $options = array()) * * @param string $normalizedKey * @param array $normalizedOptions - * @return array|bool + * @return array|boolean Metadata on success, false on failure */ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) { @@ -459,7 +459,7 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing cache ids and its metadata + * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface */ protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) @@ -556,7 +556,7 @@ public function setItem($key, $value, array $options = array()) * * @param array $keyValuePairs * @param array $options - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface * * @triggers setItems.pre(PreEvent) @@ -764,7 +764,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -929,7 +929,7 @@ public function touchItem($key, array $options = array()) * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not updated keys * @throws Exception\ExceptionInterface * * @triggers touchItems.pre(PreEvent) @@ -1015,7 +1015,7 @@ public function removeItem($key, array $options = array()) * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not removed keys * @throws Exception\ExceptionInterface * * @triggers removeItems.pre(PreEvent) @@ -1282,7 +1282,7 @@ protected function internalGetCapabilities() * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 4a4dcdb79..94076c336 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -161,7 +161,7 @@ public function getOptions() * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken - * @return mixed Data on success or false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) @@ -199,7 +199,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -254,7 +254,7 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface */ protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) @@ -278,7 +278,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array + * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface * * @triggers getMetadatas.pre(PreEvent) @@ -341,7 +341,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -492,7 +492,7 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio * * @param array $keys * @param array $options - * @return boolean + * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) @@ -530,7 +530,7 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -571,7 +571,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -796,7 +796,7 @@ protected function internalGetCapabilities() * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index d3dffe0a8..f3d718893 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -100,7 +100,7 @@ public function getOptions() * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken - * @return mixed Data on success or false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) @@ -134,7 +134,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -200,7 +200,7 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * * @param array $keys * @param array $options - * @return array Array of existing keys + * @return array Array of found keys * @throws Exception\ExceptionInterface */ protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) @@ -236,7 +236,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * * @param string $normalizedKey * @param array $normalizedOptions - * @return array|boolean Metadata or false on failure + * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * * @triggers getMetadata.pre(PreEvent) @@ -299,7 +299,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -368,7 +368,7 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -440,7 +440,7 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalReplaceItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -528,7 +528,7 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -560,7 +560,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -822,7 +822,7 @@ protected function internalGetCapabilities() * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 06b25095b..ab6e646de 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -112,12 +112,10 @@ public function getOptions() * - The time-to-life * - namespace * - The namespace to use - * - ignore_missing_items - * - Throw exception on missing item or return false * * @param string $normalizedKey * @param array $normalizedOptions - * @return mixed Data on success or false on failure + * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) @@ -148,7 +146,7 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) * * @param array $normalizedKeys * @param array $normalizedOptions - * @return array Associative array of existing keys and values + * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) @@ -201,12 +199,10 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * Options: * - namespace optional * - The namespace to use (Default: namespace of object) - * - ignore_missing_items optional - * - Throw exception on missing item or return false * * @param string $normalizedKey * @param array $normalizedOptions - * @return array|boolean Metadata or false on failure + * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * * @triggers getMetadata.pre(PreEvent) @@ -274,7 +270,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -342,7 +338,7 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions - * @return boolean + * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) @@ -405,8 +401,6 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm * Options: * - namespace * - The namespace to use - * - ignore_missing_items - * - Throw exception on missing item * * @param string $normalizedKey * @param array $normalizedOptions @@ -431,13 +425,11 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio * - The time-to-life * - namespace * - The namespace to use - * - ignore_missing_items - * - Throw exception on missing item * * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -469,13 +461,11 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no * - The time-to-life * - namespace * - The namespace to use - * - ignore_missing_items - * - Throw exception on missing item * * @param string $normalizedKey * @param int $value * @param array $normalizedOptions - * @return int|boolean The new value or false on failure + * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) @@ -583,7 +573,7 @@ protected function internalGetCapabilities() * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index d350cb96e..e16191ae1 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -57,7 +57,7 @@ public function __construct($options = array()) * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 7aa025ab0..95fd0aaa9 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -56,7 +56,7 @@ public function __construct($options = array()) * Internal method to get storage capacity. * * @param array $normalizedOptions - * @return array|boolean Capacity as array or false on failure + * @return array|boolean Associative array of capacity, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetCapacity(array & $normalizedOptions) From f904d3c4f81e8fbd75577d6928ffeb2a4b61e9e5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 11 May 2012 01:02:16 +0200 Subject: [PATCH 261/311] Now the WinCache adapter follows the new API --- src/Storage/Adapter/WinCache.php | 145 +++++++++++++------------------ 1 file changed, 62 insertions(+), 83 deletions(-) diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index ab6e646de..f3960dde7 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -113,25 +113,21 @@ public function getOptions() * - namespace * - The namespace to use * - * @param string $normalizedKey - * @param array $normalizedOptions + * @param string $normalizedKey + * @param array $normalizedOptions + * @param boolean $success + * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions) + protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) { $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); $internalKey = $prefix . $normalizedKey; - $success = false; $result = wincache_ucache_get($internalKey, $success); - if (!$success) { - if (!$normalizedOptions['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } - } else { - if (array_key_exists('token', $normalizedOptions)) { - $normalizedOptions['token'] = $result; - } + + if ($success) { + $casToken = $result; } return $result; @@ -158,12 +154,6 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized } $fetch = wincache_ucache_get($internalKeys); - if (!$normalizedOptions['ignore_missing_items']) { - if (count($normalizedKeys) != count($fetch)) { - $missing = implode("', '", array_diff($internalKeys, array_keys($fetch))); - throw new Exception\ItemNotFoundException('Keys not found: ' . $missing); - } - } // remove namespace prefix $prefixL = strlen($prefix); @@ -216,17 +206,11 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti $info = wincache_ucache_info(true, $internalKey); if (isset($info['ucache_entries'][1])) { $metadata = $info['ucache_entries'][1]; - } - - if (!$metadata) { - if (!$normalizedOptions['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); - } + $this->normalizeMetadata($metadata); + return $metadata; + } else { return false; } - - $this->normalizeMetadata($metadata); - return $metadata; } /* writing */ @@ -275,7 +259,8 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz */ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $prefixL = strlen($prefix); $internalKeyValuePairs = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { @@ -283,15 +268,14 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n $internalKeyValuePairs[$internalKey] = $value; } - $errKeys = wincache_ucache_set($internalKeyValuePairs, null, $normalizedOptions['ttl']); - if ($errKeys) { - throw new Exception\RuntimeException( - "wincache_ucache_set(, null, {$normalizedOptions['ttl']}) failed for keys: " - . "'" . implode("','", array_keys($errKeys)) . "'" - ); + $result = wincache_ucache_set($internalKeyValuePairs, null, $normalizedOptions['ttl']); + + // remove key prefic + foreach ($result as & $key) { + $key = substr($key, $prefixL); } - return true; + return $result; } /** @@ -313,11 +297,6 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz { $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; if (!wincache_ucache_add($internalKey, $value, $normalizedOptions['ttl'])) { - // TODO: check if this is really needed - if (wincache_ucache_exists($internalKey)) { - throw new Exception\RuntimeException("Key '{$internalKey}' already exists"); - } - $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( "wincache_ucache_add('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" @@ -350,15 +329,14 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n $internalKeyValuePairs[$internalKey] = $value; } - $errKeys = wincache_ucache_add($internalKeyValuePairs, null, $normalizedOptions['ttl']); - if ($errKeys !== array()) { - throw new Exception\RuntimeException( - "wincache_ucache_add(, null, {$normalizedOptions['ttl']}) failed for keys: " - . "'" . implode("','", array_keys($errKeys)) . "'" - ); + $result = wincache_ucache_add($internalKeyValuePairs, null, $normalizedOptions['ttl']); + + // remove key prefic + foreach ($result as & $key) { + $key = substr($key, $prefixL); } - return true; + return $result; } /** @@ -410,11 +388,42 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) { $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - if (!wincache_ucache_delete($internalKey) && !$normalizedOptions['ignore_missing_items']) { - throw new Exception\ItemNotFoundException("Key '{$internalKey}' not found"); + return wincache_ucache_delete($internalKey); + } + + /** + * Internal method to remove multiple items. + * + * Options: + * - namespace + * - The namespace to use + * + * @param array $keys + * @param array $options + * @return array Array of not removed keys + * @throws Exception\ExceptionInterface + */ + protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) + { + $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + + $internalKeys = array(); + foreach ($normalizedKeys as $normalizedKey) { + $internalKeys[] = $prefix . $normalizedKey; } - return true; + $result = wincache_ucache_delete($internalKeys); + if ($result === false) { + return $normalizedKeys; + } elseif ($result) { + // remove key prefix + $prefixL = strlen($prefix); + foreach ($result as & $key) { + $key = substr($key, $prefixL); + } + } + + return $result; } /** @@ -435,22 +444,7 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - $value = (int)$value; - $newValue = wincache_ucache_inc($internalKey, $value); - if ($newValue === false) { - if (wincache_ucache_exists($internalKey)) { - throw new Exception\RuntimeException("wincache_ucache_inc('{$internalKey}', {$value}) failed"); - } elseif (!$normalizedOptions['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); - } - - $newValue = $value; - $this->addItem($normalizedKey, $newValue, $normalizedOptions); - } - - return $newValue; + return wincache_ucache_inc($internalKey, (int)$value); } /** @@ -471,22 +465,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) { $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - $value = (int)$value; - $newValue = wincache_ucache_dec($internalKey, $value); - if ($newValue === false) { - if (wincache_ucache_exists($internalKey)) { - throw new Exception\RuntimeException("wincache_ucache_inc('{$internalKey}', {$value}) failed"); - } elseif (!$normalizedOptions['ignore_missing_items']) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' not found" - ); - } - - $newValue = -$value; - $this->addItem($normalizedKey, $newValue, $normalizedOptions); - } - - return $newValue; + return wincache_ucache_dec($internalKey, (int)$value); } /* cleaning */ @@ -593,7 +572,7 @@ protected function internalGetCapacity(array & $normalizedOptions) * @param array $metadata * @return void */ - protected function normalizeMetadata(array &$metadata) + protected function normalizeMetadata(array & $metadata) { if (isset($metadata['hitcount'])) { $metadata['num_hits'] = $metadata['hitcount']; From 93b2609f55998da0d76b951002479df979e7f9ad Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 11 May 2012 01:05:18 +0200 Subject: [PATCH 262/311] removed no longer needed ItemNotFoundException --- src/Storage/Adapter/WinCache.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index f3960dde7..dec09b410 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -358,9 +358,7 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm { $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; if (!wincache_ucache_exists($internalKey)) { - throw new Exception\ItemNotFoundException( - "Key '{$internalKey}' doesn't exist" - ); + return false; } if (!wincache_ucache_set($internalKey, $value, $normalizedOptions['ttl'])) { From cff9ea342789b9a25a083913a36de51ce298f842 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 11 May 2012 01:07:58 +0200 Subject: [PATCH 263/311] removed no longer needed option 'ignore_missing_items' --- src/Exception/ItemNotFoundException.php | 31 ------------- src/Storage/Adapter/AdapterOptions.php | 44 ------------------- .../Adapter/AbstractZendServerTest.php | 1 - 3 files changed, 76 deletions(-) delete mode 100644 src/Exception/ItemNotFoundException.php diff --git a/src/Exception/ItemNotFoundException.php b/src/Exception/ItemNotFoundException.php deleted file mode 100644 index 0ba6d2e75..000000000 --- a/src/Exception/ItemNotFoundException.php +++ /dev/null @@ -1,31 +0,0 @@ -ignoreMissingItems !== $flag) { - $this->triggerOptionEvent('ignore_missing_items', $flag); - $this->ignoreMissingItems = $flag; - } - return $this; - } - - /** - * Ignore missing items - * - * @return boolean - * @see setIgnoreMissingItems() - */ - public function getIgnoreMissingItems() - { - return $this->ignoreMissingItems; - } - /** * Set key pattern * diff --git a/test/Storage/Adapter/AbstractZendServerTest.php b/test/Storage/Adapter/AbstractZendServerTest.php index 4640e76b7..dc552d9b5 100644 --- a/test/Storage/Adapter/AbstractZendServerTest.php +++ b/test/Storage/Adapter/AbstractZendServerTest.php @@ -56,7 +56,6 @@ public function testGetOptions() $this->assertInternalType('string', $options->getNamespace()); $this->assertInternalType('string', $options->getNamespacePattern()); $this->assertInternalType('string', $options->getKeyPattern()); - $this->assertInternalType('boolean', $options->getIgnoreMissingItems()); } public function testGetWithDefaultNamespace() From 58466b3c48b87bdb673f4f9d8a4b057514281945 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 11 May 2012 01:09:18 +0200 Subject: [PATCH 264/311] removed no longer needed LockedException --- src/Exception/LockedException.php | 31 ------------------------------- 1 file changed, 31 deletions(-) delete mode 100644 src/Exception/LockedException.php diff --git a/src/Exception/LockedException.php b/src/Exception/LockedException.php deleted file mode 100644 index 5c2101286..000000000 --- a/src/Exception/LockedException.php +++ /dev/null @@ -1,31 +0,0 @@ - Date: Fri, 11 May 2012 11:57:50 -0500 Subject: [PATCH 265/311] [zendframework/zf2#1199] Allow testing barcode - also changed tested-components to merely list "Zend\Feed", so all of feed is executed --- .travis/skipped-components | 1 - .travis/tested-components | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.travis/skipped-components b/.travis/skipped-components index 0790ed22c..c4cd70659 100644 --- a/.travis/skipped-components +++ b/.travis/skipped-components @@ -1,5 +1,4 @@ Zend/Amf -Zend/Barcode Zend/Date Zend/Queue Zend/Service diff --git a/.travis/tested-components b/.travis/tested-components index c0fe64778..d1d71333e 100644 --- a/.travis/tested-components +++ b/.travis/tested-components @@ -1,5 +1,6 @@ Zend/Acl Zend/Authentication +Zend/Barcode Zend/Cache Zend/Captcha Zend/Cloud @@ -14,8 +15,7 @@ Zend/DocBook Zend/Dojo Zend/Dom Zend/EventManager -Zend/Feed/Reader -Zend/Feed/Writer +Zend/Feed Zend/File Zend/Filter Zend/Form From 679c783dd5fe905177cfa4e7005f4fd515bd70e2 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 11 May 2012 12:18:48 -0500 Subject: [PATCH 266/311] [zen-27][zendframework/zf2#1199] Fix Translator tests - Fixes log setup and usage in tests and code for Translator - Re-enabled Translator tests, as they now appear to work --- .travis/skipped-components | 1 - .travis/tested-components | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis/skipped-components b/.travis/skipped-components index c4cd70659..31bcaa87f 100644 --- a/.travis/skipped-components +++ b/.travis/skipped-components @@ -3,5 +3,4 @@ Zend/Date Zend/Queue Zend/Service Zend/Test -Zend/Translator Zend/Wildfire diff --git a/.travis/tested-components b/.travis/tested-components index d1d71333e..b1f4a794d 100644 --- a/.travis/tested-components +++ b/.travis/tested-components @@ -51,6 +51,7 @@ Zend/Stdlib Zend/Tag Zend/Text Zend/TimeSync +Zend/Translator Zend/Uri Zend/Validator Zend/VersionTest.php From 97a43920fb5d21a804c164feeb8c38330d6f3463 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 11 May 2012 08:17:31 -0500 Subject: [PATCH 267/311] [zen-12] Removed Dojo from test suite - Dojo integration largely relied on integration with Zend\Form; removing from testing for now, as it has not been refactored to work with the new Zend\Form code. --- .travis/skipped-components | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis/skipped-components b/.travis/skipped-components index 31bcaa87f..171dfe9d7 100644 --- a/.travis/skipped-components +++ b/.travis/skipped-components @@ -1,5 +1,6 @@ Zend/Amf Zend/Date +Zend/Dojo Zend/Queue Zend/Service Zend/Test From ae9228a8d08e442243bd1c8e16e86d722d83d20d Mon Sep 17 00:00:00 2001 From: Maks3w Date: Fri, 18 May 2012 00:22:37 +0200 Subject: [PATCH 268/311] [Travis] Enable Zend\Math tests --- .travis/tested-components | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis/tested-components b/.travis/tested-components index b1f4a794d..9b338206b 100644 --- a/.travis/tested-components +++ b/.travis/tested-components @@ -29,6 +29,7 @@ Zend/Locale Zend/Log Zend/Mail Zend/Markup +Zend/Math Zend/Measure Zend/Memory Zend/Mime From c7f2938d551f25fd07b99c392a2e0cdff150a1ad Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Mon, 28 May 2012 21:06:33 +0200 Subject: [PATCH 269/311] Simplyfied cache API and added modified interfaces: - renamed Zend\Cache\Storage\AdapterInterface -> Zend\Cache\Storage\StorageInterface -> because it's the interface of the storage and the adapters are an implementation detail - renamed Zend\Cache\Exception\OutOfCapacityException -> Zend\Cache\Exception\OutOfSpaceException - removed options argument array -> this simplifies things a lot and speed-op internal operations -> please only use the option instance instead - moved some spezial methods into own interfaces and implement it only if the adapters supports it - AvailableSpaceCapableInterface::getAvailableSpace() - TotalSpaceCapableInterface::getTotalSpace() - ClearByNamespaceInterface::clearByNamespace($namespace) - ClearByPrefixInterface::clearByPrefix($prefix) - ClearExpiredInterface::clearExpired() - FlushableInterface::flush() - IterableInterface::getIterator() (extends IteratorAggregate) - OptimizableInterface::optimize() - TagableInterface::setTags($key, array $tags) - TagableInterface::getTags($key) - TagableInterface::clearByTags(array $tags, $disjunction = false) - removed capability properties now handled by interfaces - iterable - clearByNamespace - clearAllNamespaces --- ...yException.php => OutOfSpaceException.php} | 2 +- src/Pattern/CallbackCache.php | 141 +- src/Pattern/CaptureCache.php | 3 +- src/Pattern/ClassCache.php | 61 +- src/Pattern/ObjectCache.php | 115 +- src/Pattern/OutputCache.php | 7 +- src/Pattern/PatternOptions.php | 29 +- src/Storage/Adapter/AbstractAdapter.php | 1353 ++--------------- src/Storage/Adapter/AbstractZendServer.php | 160 +- src/Storage/Adapter/AdapterInterface.php | 428 ------ src/Storage/Adapter/AdapterOptions.php | 63 +- src/Storage/Adapter/Apc.php | 650 +++----- src/Storage/Adapter/ApcIterator.php | 179 +++ src/Storage/Adapter/Filesystem.php | 1245 +++++++-------- src/Storage/Adapter/FilesystemIterator.php | 194 +++ src/Storage/Adapter/FilesystemOptions.php | 9 - src/Storage/Adapter/KeyListIterator.php | 191 +++ src/Storage/Adapter/Memcached.php | 424 ++---- src/Storage/Adapter/Memory.php | 737 ++++----- src/Storage/Adapter/MemoryOptions.php | 14 +- src/Storage/Adapter/WinCache.php | 314 ++-- src/Storage/Adapter/ZendServerDisk.php | 121 +- src/Storage/Adapter/ZendServerShm.php | 84 +- src/Storage/AdapterBroker.php | 4 +- .../AvailableSpaceCapableInterface.php | 39 + src/Storage/Capabilities.php | 125 +- src/Storage/ClearByNamespaceInterface.php | 40 + src/Storage/ClearByPrefixInterface.php | 40 + src/Storage/ClearExpiredInterface.php | 39 + src/Storage/Event.php | 22 +- src/Storage/ExceptionEvent.php | 2 +- src/Storage/FlushableInterface.php | 39 + src/Storage/IterableInterface.php | 39 + src/Storage/IteratorInterface.php | 60 + src/Storage/OptimizableInterface.php | 39 + ...rByFactor.php => ClearExpiredByFactor.php} | 28 +- src/Storage/Plugin/ExceptionHandler.php | 15 - src/Storage/Plugin/IgnoreUserAbort.php | 4 +- src/Storage/Plugin/OptimizeByFactor.php | 17 +- src/Storage/Plugin/PluginOptions.php | 39 +- src/Storage/Plugin/Serializer.php | 145 +- src/Storage/PluginBroker.php | 5 +- src/Storage/PluginLoader.php | 17 +- src/Storage/PostEvent.php | 10 +- src/Storage/StorageInterface.php | 263 ++++ src/Storage/TagableInterface.php | 62 + src/Storage/TotalSpaceCapableInterface.php | 39 + src/StorageFactory.php | 20 +- src/Utils.php | 31 +- test/Pattern/CallbackCacheTest.php | 40 +- test/Pattern/CaptureCacheTest.php | 1 - test/Pattern/ClassCacheTest.php | 9 +- test/Pattern/ObjectCacheTest.php | 81 +- test/Pattern/OutputCacheTest.php | 3 +- test/PatternFactoryTest.php | 1 - test/Storage/Adapter/AbstractAdapterTest.php | 230 +-- .../Adapter/AbstractZendServerTest.php | 140 +- test/Storage/Adapter/ApcTest.php | 1 - test/Storage/Adapter/CommonAdapterTest.php | 611 ++------ test/Storage/Adapter/MemcachedTest.php | 4 +- test/Storage/Adapter/MemoryTest.php | 5 +- test/Storage/Adapter/WinCacheTest.php | 1 - test/Storage/Adapter/ZendServerDiskTest.php | 1 - test/Storage/Adapter/ZendServerShmTest.php | 1 - ...rTest.php => ClearExpiredByFactorTest.php} | 54 +- test/Storage/Plugin/ExceptionHandlerTest.php | 13 - test/Storage/Plugin/IgnoreUserAbortTest.php | 1 - test/Storage/Plugin/OptimizeByFactorTest.php | 11 +- test/Storage/Plugin/SerializerTest.php | 4 - .../TestAsset/ClearExpiredMockAdapter.php | 12 + test/Storage/TestAsset/MockAdapter.php | 11 +- test/Storage/TestAsset/MockPlugin.php | 1 - .../TestAsset/OptimizableMockAdapter.php | 12 + test/StorageFactoryTest.php | 13 +- test/TestAsset/DummyPattern.php | 1 - test/TestAsset/DummyStoragePlugin.php | 1 - test/UtilsTest.php | 6 - 77 files changed, 3366 insertions(+), 5610 deletions(-) rename src/Exception/{OutOfCapacityException.php => OutOfSpaceException.php} (91%) delete mode 100644 src/Storage/Adapter/AdapterInterface.php create mode 100644 src/Storage/Adapter/ApcIterator.php create mode 100644 src/Storage/Adapter/FilesystemIterator.php create mode 100644 src/Storage/Adapter/KeyListIterator.php create mode 100644 src/Storage/AvailableSpaceCapableInterface.php create mode 100644 src/Storage/ClearByNamespaceInterface.php create mode 100644 src/Storage/ClearByPrefixInterface.php create mode 100644 src/Storage/ClearExpiredInterface.php create mode 100644 src/Storage/FlushableInterface.php create mode 100644 src/Storage/IterableInterface.php create mode 100644 src/Storage/IteratorInterface.php create mode 100644 src/Storage/OptimizableInterface.php rename src/Storage/Plugin/{ClearByFactor.php => ClearExpiredByFactor.php} (79%) create mode 100644 src/Storage/StorageInterface.php create mode 100644 src/Storage/TagableInterface.php create mode 100644 src/Storage/TotalSpaceCapableInterface.php rename test/Storage/Plugin/{ClearByFactorTest.php => ClearExpiredByFactorTest.php} (57%) create mode 100644 test/Storage/TestAsset/ClearExpiredMockAdapter.php create mode 100644 test/Storage/TestAsset/OptimizableMockAdapter.php diff --git a/src/Exception/OutOfCapacityException.php b/src/Exception/OutOfSpaceException.php similarity index 91% rename from src/Exception/OutOfCapacityException.php rename to src/Exception/OutOfSpaceException.php index 2dfaef98a..290592c8d 100644 --- a/src/Exception/OutOfCapacityException.php +++ b/src/Exception/OutOfSpaceException.php @@ -26,6 +26,6 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class OutOfCapacityException extends \OverflowException implements ExceptionInterface +class OutOfSpaceException extends \OverflowException implements ExceptionInterface { } diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index 736be227c..566039c93 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -22,8 +22,7 @@ namespace Zend\Cache\Pattern; use Zend\Cache\Exception, - Zend\Cache\StorageFactory, - Zend\Cache\Storage\Adapter\AdapterInterface as StorageAdapter; + Zend\Cache\StorageFactory; /** * @category Zend @@ -56,17 +55,16 @@ public function setOptions(PatternOptions $options) * * @param callback $callback A valid callback * @param array $args Callback arguments - * @param array $options Options * @return mixed Result * @throws Exception */ - public function call($callback, array $args = array(), array $options = array()) + public function call($callback, array $args = array()) { - $classOptions = $this->getOptions(); - + $options = $this->getOptions(); + $storage = $options->getStorage(); $success = null; - $key = $this->_generateKey($callback, $args, $options); - $result = $classOptions->getStorage()->getItem($key, $options, $success); + $key = $this->generateCallbackKey($callback, $args); + $result = $storage->getItem($key, $success); if ($success) { if (!isset($result[0])) { throw new Exception\RuntimeException("Invalid cached data for key '{$key}'"); @@ -76,7 +74,7 @@ public function call($callback, array $args = array(), array $options = array()) return $result[0]; } - $cacheOutput = $classOptions->getCacheOutput(); + $cacheOutput = $options->getCacheOutput(); if ($cacheOutput) { ob_start(); ob_implicit_flush(false); @@ -103,7 +101,7 @@ public function call($callback, array $args = array(), array $options = array()) $data = array($ret); } - $classOptions->getStorage()->setItem($key, $data, $options); + $storage->setItem($key, $data); return $ret; } @@ -123,106 +121,91 @@ public function __call($function, array $args) /** * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part merged using md5($callbackKey.$argumentsKey). - * - * Options: - * callback_key A string representing the callback part of the key - * or NULL to autogenerate the callback key part - * argument_key A string representing the arguments part of the key - * or NULL to autogenerate the arguments key part + * and a key representing the arguments part. * * @param callback $callback A valid callback * @param array $args Callback arguments - * @param array $options Options * @return string * @throws Exception */ - public function generateKey($callback, array $args = array(), array $options = array()) + public function generateKey($callback, array $args = array()) { - return $this->_generateKey($callback, $args, $options); + return $this->generateCallbackKey($callback, $args); } /** * Generate a unique key in base of a key representing the callback part - * and a key representing the arguments part merged using md5($callbackKey.$argumentsKey). + * and a key representing the arguments part. * * @param callback $callback A valid callback * @param array $args Callback arguments - * @param array $options Options * @return string - * @throws Exception\InvalidArgumentException - * @throws Exception\RuntimeException + * @throws Exception */ - protected function _generateKey($callback, array $args, array $options) + protected function generateCallbackKey($callback, array $args) { - $callbackKey = ''; - $argumentKey = ''; - - // generate callback key part - if (isset($options['callback_key'])) { - $callbackKey = (string) $options['callback_key']; - - if (!is_callable($callback, false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - } else { - if (!is_callable($callback, false, $callbackKey)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } + if (!is_callable($callback, false, $callbackKey)) { + throw new Exception\InvalidArgumentException('Invalid callback'); + } - // functions, methods and classnames are case-insensitive - $callbackKey = strtolower($callbackKey); + // functions, methods and classnames are case-insensitive + $callbackKey = strtolower($callbackKey); - // generate a unique key of object callbacks - if (is_object($callback)) { // Closures & __invoke - $object = $callback; - } elseif (isset($callback[0])) { // array($object, 'method') - $object = $callback[0]; - } - if (isset($object)) { - try { - $serializedObject = @serialize($object); - } catch (\Exception $e) { - throw new Exception\RuntimeException( - "Can't serialize callback: see previous exception" - , 0, $e); - } - - if (!$serializedObject) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException( - "Can't serialize callback: " - . $lastErr['message'] - ); - } - $callbackKey.= $serializedObject; - } + // generate a unique key of object callbacks + if (is_object($callback)) { // Closures & __invoke + $object = $callback; + } elseif (isset($callback[0])) { // array($object, 'method') + $object = $callback[0]; } - - // generate argument key part - if (isset($options['argument_key'])) { - $argumentKey = (string)$options['argument_key']; - } elseif ($args) { + if (isset($object)) { try { - $serializedArgs = @serialize(array_values($args)); + $serializedObject = @serialize($object); } catch (\Exception $e) { throw new Exception\RuntimeException( - "Can't serialize arguments: see previous exception" - , 0, $e); + "Can't serialize callback: see previous exception", 0, $e + ); } - if (!$serializedArgs) { + if (!$serializedObject) { $lastErr = error_get_last(); throw new Exception\RuntimeException( - "Can't serialize arguments: " - . $lastErr['message'] + "Can't serialize callback: " . $lastErr['message'] ); } + $callbackKey.= $serializedObject; + } + + return md5($callbackKey) . $this->generateArgumentsKey($args); + } + + /** + * Generate a unique key of the argument part. + * + * @param array $args + * @return string + * @throws Exception + */ + protected function generateArgumentsKey(array $args) + { + if (!$args) { + return ''; + } + + try { + $serializedArgs = @serialize(array_values($args)); + } catch (\Exception $e) { + throw new Exception\RuntimeException( + "Can't serialize arguments: see previous exception" + , 0, $e); + } - $argumentKey = $serializedArgs; + if (!$serializedArgs) { + $lastErr = error_get_last(); + throw new Exception\RuntimeException( + "Can't serialize arguments: " . $lastErr['message'] + ); } - // merge and return the key parts - return md5($callbackKey.$argumentKey); + return md5($serializedArgs); } } diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 834662c47..d90d5e19a 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -21,8 +21,7 @@ namespace Zend\Cache\Pattern; -use Zend\Cache\Exception, - Zend\Cache\Storage\Adapter\AdapterInterface as StorageAdapter; +use Zend\Cache\Exception; /** * @category Zend diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index 34f0e7a6d..5b14fb54e 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -55,22 +55,21 @@ public function setOptions(PatternOptions $options) * * @param string $method Method name to call * @param array $args Method arguments - * @param array $options Cache options * @return mixed * @throws Exception */ - public function call($method, array $args = array(), array $options = array()) + public function call($method, array $args = array()) { - $classOptions = $this->getOptions(); - $classname = $classOptions->getClass(); - $method = strtolower($method); - $callback = $classname . '::' . $method; + $options = $this->getOptions(); + $classname = $options->getClass(); + $method = strtolower($method); + $callback = $classname . '::' . $method; - $cache = $classOptions->getCacheByDefault(); + $cache = $options->getCacheByDefault(); if ($cache) { - $cache = !in_array($method, $classOptions->getClassNonCacheMethods()); + $cache = !in_array($method, $options->getClassNonCacheMethods()); } else { - $cache = in_array($method, $classOptions->getClassCacheMethods()); + $cache = in_array($method, $options->getClassCacheMethods()); } if (!$cache) { @@ -81,34 +80,40 @@ public function call($method, array $args = array(), array $options = array()) } } - // speed up key generation - if (!isset($options['callback_key'])) { - $options['callback_key'] = $callback; - } - - return parent::call($callback, $args, $options); + return parent::call($callback, $args); } /** - * Generate a key from the method name and arguments + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. * - * @param string $method The method name - * @param array $args Method arguments + * @param string $method The method + * @param array $args Callback arguments * @return string * @throws Exception */ - public function generateKey($method, array $args = array(), array $options = array()) + public function generateKey($method, array $args = array()) { - // speed up key generation - $classOptions = $this->getOptions(); - if (!isset($options['callback_key'])) { - $callback = $classOptions->getClass() . '::' . strtolower($method); - $options['callback_key'] = $callback; - } else { - $callback = $classOptions->getClass() . '::' . $method; - } + return $this->generateCallbackKey( + $this->getOptions()->getClass() . '::' . $method, + $args + ); + } - return parent::generateKey($callback, $args, $options); + /** + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. + * + * @param callback $callback A valid callback + * @param array $args Callback arguments + * @return string + * @throws Exception + */ + protected function generateCallbackKey($callback, array $args) + { + $callbackKey = md5(strtolower($callback)); + $argumentKey = $this->generateArgumentsKey($args); + return $callbackKey . $argumentKey; } /** diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index b692a74da..67fac77aa 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -54,15 +54,14 @@ public function setOptions(PatternOptions $options) * * @param string $method Method name to call * @param array $args Method arguments - * @param array $options Cache options * @return mixed * @throws Exception */ - public function call($method, array $args = array(), array $options = array()) + public function call($method, array $args = array()) { - $classOptions = $this->getOptions(); - $object = $classOptions->getObject(); - $method = strtolower($method); + $options = $this->getOptions(); + $object = $options->getObject(); + $method = strtolower($method); // handle magic methods switch ($method) { @@ -72,8 +71,8 @@ public function call($method, array $args = array(), array $options = array()) $object->{$property} = $value; - if (!$classOptions->getObjectCacheMagicProperties() - || property_exists($object, $property) + if (!$options->getObjectCacheMagicProperties() + || property_exists($object, $property) ) { // no caching if property isn't magic // or caching magic properties is disabled @@ -83,20 +82,20 @@ public function call($method, array $args = array(), array $options = array()) // remove cached __get and __isset $removeKeys = null; if (method_exists($object, '__get')) { - $removeKeys[] = $this->generateKey('__get', array($property), $options); + $removeKeys[] = $this->generateKey('__get', array($property)); } if (method_exists($object, '__isset')) { - $removeKeys[] = $this->generateKey('__isset', array($property), $options); + $removeKeys[] = $this->generateKey('__isset', array($property)); } if ($removeKeys) { - $classOptions->getStorage()->removeMulti($removeKeys); + $options->getStorage()->removeItems($removeKeys); } return; case '__get': $property = array_shift($args); - if (!$classOptions->getObjectCacheMagicProperties() + if (!$options->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -105,23 +104,12 @@ public function call($method, array $args = array(), array $options = array()) } array_unshift($args, $property); - - if (!isset($options['callback_key'])) { - if ((isset($options['entity_key']) - && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $classOptions->getObjectKey() !== null) - ) { - $options['callback_key'] = $entityKey . '::' . strtolower($method); - unset($options['entity_key']); - } - } - - return parent::call(array($object, '__get'), $args, $options); + return parent::call(array($object, '__get'), $args); case '__isset': $property = array_shift($args); - if (!$classOptions->getObjectCacheMagicProperties() + if (!$options->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -129,24 +117,14 @@ public function call($method, array $args = array(), array $options = array()) return isset($object->{$property}); } - if (!isset($options['callback_key'])) { - if ((isset($options['entity_key']) - && ($entityKey = $options['entity_key']) !== null) - || ($entityKey = $classOptions->getObjectKey() !== null) - ) { - $options['callback_key'] = $entityKey . '::' . strtolower($method); - unset($options['entity_key']); - } - } - - return parent::call(array($object, '__isset'), array($property), $options); + return parent::call(array($object, '__isset'), array($property)); case '__unset': $property = array_shift($args); unset($object->{$property}); - if (!$classOptions->getObjectCacheMagicProperties() + if (!$options->getObjectCacheMagicProperties() || property_exists($object, $property) ) { // no caching if property isn't magic @@ -157,64 +135,65 @@ public function call($method, array $args = array(), array $options = array()) // remove previous cached __get and __isset calls $removeKeys = null; if (method_exists($object, '__get')) { - $removeKeys[] = $this->generateKey('__get', array($property), $options); + $removeKeys[] = $this->generateKey('__get', array($property)); } if (method_exists($object, '__isset')) { - $removeKeys[] = $this->generateKey('__isset', array($property), $options); + $removeKeys[] = $this->generateKey('__isset', array($property)); } if ($removeKeys) { - $classOptions->getStorage()->removeMulti($removeKeys); + $options->getStorage()->removeItems($removeKeys); } return; } - $cache = $classOptions->getCacheByDefault(); + $cache = $options->getCacheByDefault(); if ($cache) { - $cache = !in_array($method, $classOptions->getObjectNonCacheMethods()); + $cache = !in_array($method, $options->getObjectNonCacheMethods()); } else { - $cache = in_array($method, $classOptions->getObjectCacheMethods()); + $cache = in_array($method, $options->getObjectCacheMethods()); } if (!$cache) { if ($args) { return call_user_func_array(array($object, $method), $args); - } - return $object->{$method}(); - } - - if (!isset($options['callback_key'])) { - if ((isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || (($entityKey = $classOptions->getObjectKey()) !== null) - ) { - $options['callback_key'] = $entityKey . '::' . strtolower($method); - unset($options['entity_key']); } + return $object->{$method}(); } - return parent::call(array($object, $method), $args, $options); + return parent::call(array($object, $method), $args); } /** - * Generate a unique key from the method name and arguments + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. * - * @param string $method The method name - * @param array $args Method arguments - * @param array $options Options + * @param string $method The method + * @param array $args Callback arguments * @return string * @throws Exception */ - public function generateKey($method, array $args = array(), array $options = array()) + public function generateKey($method, array $args = array()) { - $classOptions = $this->getOptions(); - if (!isset($options['callback_key'])) { - if ( (isset($options['entity_key']) && ($entityKey = $options['entity_key']) !== null) - || (($entityKey = $classOptions->getObjectKey()) !== null)) { - $options['callback_key'] = $entityKey . '::' . strtolower($method); - unset($options['entity_key']); - } - } + return $this->generateCallbackKey( + array($this->getOptions()->getObject(), $method), + $args + ); + } - return parent::generateKey(array($classOptions->getObject(), $method), $args, $options); + /** + * Generate a unique key in base of a key representing the callback part + * and a key representing the arguments part. + * + * @param callback $callback A valid callback + * @param array $args Callback arguments + * @return string + * @throws Exception + */ + protected function generateCallbackKey($callback, array $args = array()) + { + $callbackKey = md5($this->getOptions()->getObjectKey() . '::' . strtolower($callback[1])); + $argumentKey = $this->generateArgumentsKey($args); + return $callbackKey . $argumentKey; } /** @@ -314,7 +293,7 @@ public function __toString() * @return mixed * @see http://php.net/manual/language.oop5.magic.php#language.oop5.magic.invoke */ - public function __invoke() + public function __invoke() { return $this->call('__invoke', func_get_args()); } diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index 88a1ea48e..4f3251e74 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -22,8 +22,7 @@ namespace Zend\Cache\Pattern; use Zend\Cache\Exception, - Zend\Cache\StorageFactory, - Zend\Cache\Storage\Adapter\AdapterInterface as StorageAdapter; + Zend\Cache\StorageFactory; /** * @category Zend @@ -62,7 +61,7 @@ public function setOptions(PatternOptions $options) * else start buffering output until end() is called or the script ends. * * @param string $key Key - * @param array $storageOptions Options passing to Zend\Cache\Storage\Adapter\AdapterInterface::getItem + * @param array $storageOptions Options passing to Zend\Cache\Storage\StorageInterface::getItem * @return boolean * @throws Exception */ @@ -89,7 +88,7 @@ public function start($key, array $storageOptions = array()) * Stops bufferung output, write buffered data to cache using the given key on start() * and displays the buffer. * - * @param array $storageOptions Options passed to Zend\Cache\Storage\Adapter\AdapterInterface::setItem + * @param array $storageOptions Options passed to Zend\Cache\Storage\StorageInterface::setItem * @return boolean TRUE on success, FALSE on failure writing to cache * @throws Exception */ diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 8f0cd12aa..945105c46 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -23,7 +23,7 @@ use Zend\Cache\Exception, Zend\Cache\StorageFactory, - Zend\Cache\Storage\Adapter\AdapterInterface as StorageAdapter, + Zend\Cache\Storage\StorageInterface as Storage, Zend\Stdlib\Options; /** @@ -149,7 +149,7 @@ class PatternOptions extends Options * - ClassCache * - ObjectCache * - OutputCache - * @var null|StorageAdapter + * @var null|Storage */ protected $storage; @@ -170,7 +170,7 @@ class PatternOptions extends Options /** * Used by: * - CaptureCache - * @var null|StorageAdapter + * @var null|Storage */ protected $tagStorage; @@ -623,6 +623,9 @@ public function setObjectKey($objectKey) */ public function getObjectKey() { + if (!$this->objectKey) { + return get_class($this->getObject()); + } return $this->objectKey; } @@ -686,13 +689,12 @@ public function getPublicDir() * - ObjectCache * - OutputCache * - * @param string|array|StorageAdapter $storage + * @param string|array|Storage $storage * @return PatternOptions */ public function setStorage($storage) { - $storage = $this->storageFactory($storage); - $this->storage = $storage; + $this->storage = $this->storageFactory($storage); return $this; } @@ -705,7 +707,7 @@ public function setStorage($storage) * - ObjectCache * - OutputCache * - * @return null|StorageAdapter + * @return null|Storage */ public function getStorage() { @@ -772,13 +774,12 @@ public function getTags() * Used by: * - CaptureCache * - * @param string|array|StorageAdapter $tagStorage + * @param string|array|Storage $tagStorage * @return PatternOptions */ public function setTagStorage($tagStorage) { - $tagStorage = $this->storageFactory($tagStorage); - $this->tagStorage = $tagStorage; + $this->tagStorage = $this->storageFactory($tagStorage); return $this; } @@ -788,7 +789,7 @@ public function setTagStorage($tagStorage) * Used by: * - CaptureCache * - * @return null|StorageAdapter + * @return null|Storage */ public function getTagStorage() { @@ -858,7 +859,7 @@ protected function normalizeUmask($umask, $comparison) /** * Create a storage object from a given specification * - * @param array|string|StorageAdapter $storage + * @param array|string|Storage $storage * @return StorageAdapter */ protected function storageFactory($storage) @@ -867,9 +868,9 @@ protected function storageFactory($storage) $storage = StorageFactory::factory($storage); } elseif (is_string($storage)) { $storage = StorageFactory::adapterFactory($storage); - } elseif ( !($storage instanceof StorageAdapter) ) { + } elseif ( !($storage instanceof Storage) ) { throw new Exception\InvalidArgumentException( - 'The storage must be an instanceof Zend\Cache\Storage\Adapter\AdapterInterface ' + 'The storage must be an instanceof Zend\Cache\Storage\StorageInterface ' . 'or an array passed to Zend\Cache\Storage::factory ' . 'or simply the name of the storage adapter' ); diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 21ecea584..7534b53e0 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -31,6 +31,7 @@ Zend\Cache\Storage\ExceptionEvent, Zend\Cache\Storage\PostEvent, Zend\Cache\Storage\Plugin, + Zend\Cache\Storage\StorageInterface, Zend\EventManager\EventManager, Zend\EventManager\EventsCapableInterface; @@ -41,7 +42,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -abstract class AbstractAdapter implements AdapterInterface, EventsCapableInterface +abstract class AbstractAdapter implements StorageInterface, EventsCapableInterface { /** * The used EventManager if any @@ -84,27 +85,6 @@ abstract class AbstractAdapter implements AdapterInterface, EventsCapableInterfa */ protected $options; - /** - * Is a statement active - * - * @var bool - */ - protected $stmtActive = false; - - /** - * List of keys used for the active statement - * - * @var null|array - */ - protected $stmtKeys = null; - - /** - * Options used on starting the active statement - * - * @var null|array - */ - protected $stmtOptions = null; - /** * Constructor * @@ -130,7 +110,7 @@ public function __construct($options = null) */ public function __destruct() { - foreach ($this->getPlugins() as $plugin) { + foreach ($this->getPluginRegistry() as $plugin) { $this->removePlugin($plugin); } @@ -347,13 +327,16 @@ public function removePlugin(Plugin\PluginInterface $plugin) } /** - * Get all registered plugins + * Return registry of plugins * * @return SplObjectStorage */ - public function getPlugins() + public function getPluginRegistry() { - return $this->getPluginRegistry(); + if (!$this->pluginRegistry instanceof SplObjectStorage) { + $this->pluginRegistry = new SplObjectStorage(); + } + return $this->pluginRegistry; } /* reading */ @@ -361,14 +344,7 @@ public function getPlugins() /** * Get an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure @@ -378,7 +354,7 @@ public function getPlugins() * @triggers getItem.post(PostEvent) * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array(), & $success = null, & $casToken = null) + public function getItem($key, & $success = null, & $casToken = null) { if (!$this->getOptions()->getReadable()) { $success = false; @@ -386,13 +362,18 @@ public function getItem($key, array $options = array(), & $success = null, & $ca } $this->normalizeKey($key); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, - 'success' => & $success, - 'casToken' => & $casToken, - )); + + $argn = func_num_args(); + $args = array( + 'key' => & $key, + ); + if ($argn > 1) { + $args['success'] = & $success; + } + if ($argn > 2) { + $args['casToken'] = & $casToken; + } + $args = new ArrayObject($args); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); @@ -400,7 +381,13 @@ public function getItem($key, array $options = array(), & $success = null, & $ca return $eventRs->last(); } - $result = $this->internalGetItem($args['key'], $args['options'], $args['success'], $args['casToken']); + if (isset($args['success'], $args['casToken'])) { + $result = $this->internalGetItem($args['key'], $args['success'], $args['casToken']); + } elseif (isset($args['success'])) { + $result = $this->internalGetItem($args['key'], $args['success']); + } else { + $result = $this->internalGetItem($args['key']); + } return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -411,32 +398,18 @@ public function getItem($key, array $options = array(), & $success = null, & $ca /** * Internal method to get an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - abstract protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null); + abstract protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null); /** * Get multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Associative array of keys and values * @throws Exception\ExceptionInterface * @@ -444,17 +417,15 @@ abstract protected function internalGetItem(& $normalizedKey, array & $normalize * @triggers getItems.post(PostEvent) * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + public function getItems(array $keys) { if (!$this->getOptions()->getReadable()) { return array(); } $this->normalizeKeys($keys); - $this->normalizeOptions($options); $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, + 'keys' => & $keys, )); try { @@ -463,7 +434,7 @@ public function getItems(array $keys, array $options = array()) return $eventRs->last(); } - $result = $this->internalGetItems($args['keys'], $args['options']); + $result = $this->internalGetItems($args['keys']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array(); @@ -474,23 +445,16 @@ public function getItems(array $keys, array $options = array()) /** * Internal method to get multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { $success = null; $result = array(); foreach ($normalizedKeys as $normalizedKey) { - $value = $this->internalGetItem($normalizedKey, $normalizedOptions, $success); + $value = $this->internalGetItem($normalizedKey, $success); if ($success) { $result[$normalizedKey] = $value; } @@ -502,14 +466,7 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Test if an item exists. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -517,17 +474,15 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized * @triggers hasItem.post(PostEvent) * @triggers hasItem.exception(ExceptionEvent) */ - public function hasItem($key, array $options = array()) + public function hasItem($key) { if (!$this->getOptions()->getReadable()) { return false; } $this->normalizeKey($key); - $this->normalizeOptions($options); $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, + 'key' => & $key, )); try { @@ -536,7 +491,7 @@ public function hasItem($key, array $options = array()) return $eventRs->last(); } - $result = $this->internalHasItem($args['key'], $args['options']); + $result = $this->internalHasItem($args['key']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -547,35 +502,21 @@ public function hasItem($key, array $options = array()) /** * Internal method to test if an item exists. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { $success = null; - $this->internalGetItem($normalizedKey, $normalizedOptions, $success); + $this->internalGetItem($normalizedKey, $success); return $success; } /** * Test multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Array of found keys * @throws Exception\ExceptionInterface * @@ -583,17 +524,15 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * @triggers hasItems.post(PostEvent) * @triggers hasItems.exception(ExceptionEvent) */ - public function hasItems(array $keys, array $options = array()) + public function hasItems(array $keys) { if (!$this->getOptions()->getReadable()) { return array(); } $this->normalizeKeys($keys); - $this->normalizeOptions($options); $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, + 'keys' => & $keys, )); try { @@ -602,7 +541,7 @@ public function hasItems(array $keys, array $options = array()) return $eventRs->last(); } - $result = $this->internalHasItems($args['keys'], $args['options']); + $result = $this->internalHasItems($args['keys']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array(); @@ -613,22 +552,15 @@ public function hasItems(array $keys, array $options = array()) /** * Internal method to test multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $keys - * @param array $options * @return array Array of found keys * @throws Exception\ExceptionInterface */ - protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalHasItems(array & $normalizedKeys) { $result = array(); foreach ($normalizedKeys as $normalizedKey) { - if ($this->internalHasItem($normalizedKey, $normalizedOptions)) { + if ($this->internalHasItem($normalizedKey)) { $result[] = $normalizedKey; } } @@ -638,14 +570,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized /** * Get metadata of an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * @@ -653,17 +578,15 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * @triggers getMetadata.post(PostEvent) * @triggers getMetadata.exception(ExceptionEvent) */ - public function getMetadata($key, array $options = array()) + public function getMetadata($key) { if (!$this->getOptions()->getReadable()) { return false; } $this->normalizeKey($key); - $this->normalizeOptions($options); $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, + 'key' => & $key, )); try { @@ -672,7 +595,7 @@ public function getMetadata($key, array $options = array()) return $eventRs->last(); } - $result = $this->internalGetMetadata($args['key'], $args['options']); + $result = $this->internalGetMetadata($args['key']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -683,20 +606,13 @@ public function getMetadata($key, array $options = array()) /** * Internal method to get metadata of an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) + protected function internalGetMetadata(& $normalizedKey) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalHasItem($normalizedKey)) { return false; } @@ -706,14 +622,7 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti /** * Get multiple metadata * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface * @@ -721,17 +630,15 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti * @triggers getMetadatas.post(PostEvent) * @triggers getMetadatas.exception(ExceptionEvent) */ - public function getMetadatas(array $keys, array $options = array()) + public function getMetadatas(array $keys) { if (!$this->getOptions()->getReadable()) { return array(); } $this->normalizeKeys($keys); - $this->normalizeOptions($options); $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, + 'keys' => & $keys, )); try { @@ -740,7 +647,7 @@ public function getMetadatas(array $keys, array $options = array()) return $eventRs->last(); } - $result = $this->internalGetMetadatas($args['keys'], $args['options']); + $result = $this->internalGetMetadatas($args['keys']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array(); @@ -751,22 +658,15 @@ public function getMetadatas(array $keys, array $options = array()) /** * Internal method to get multiple metadata * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface */ - protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetMetadatas(array & $normalizedKeys) { $result = array(); foreach ($normalizedKeys as $normalizedKey) { - $metadata = $this->internalGetMetadata($normalizedKey, $normalizedOptions); + $metadata = $this->internalGetMetadata($normalizedKey); if ($metadata !== false) { $result[$normalizedKey] = $metadata; } @@ -779,17 +679,8 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal /** * Store an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -797,18 +688,16 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal * @triggers setItem.post(PostEvent) * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + public function setItem($key, $value) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, + 'key' => & $key, + 'value' => & $value, )); try { @@ -817,7 +706,7 @@ public function setItem($key, $value, array $options = array()) return $eventRs->last(); } - $result = $this->internalSetItem($args['key'], $args['value'], $args['options']); + $result = $this->internalSetItem($args['key'], $args['value']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -828,35 +717,17 @@ public function setItem($key, $value, array $options = array()) /** * Internal method to store an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - abstract protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions); + abstract protected function internalSetItem(& $normalizedKey, & $value); /** * Store multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param array $keyValuePairs - * @param array $options * @return array Array of not stored keys * @throws Exception\ExceptionInterface * @@ -864,17 +735,15 @@ abstract protected function internalSetItem(& $normalizedKey, & $value, array & * @triggers setItems.post(PostEvent) * @triggers setItems.exception(ExceptionEvent) */ - public function setItems(array $keyValuePairs, array $options = array()) + public function setItems(array $keyValuePairs) { if (!$this->getOptions()->getWritable()) { return array_keys($keyValuePairs); } $this->normalizeKeyValuePairs($keyValuePairs); - $this->normalizeOptions($options); $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, )); try { @@ -883,7 +752,7 @@ public function setItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - $result = $this->internalSetItems($args['keyValuePairs'], $args['options']); + $result = $this->internalSetItems($args['keyValuePairs']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array_keys($keyValuePairs); @@ -894,24 +763,16 @@ public function setItems(array $keyValuePairs, array $options = array()) /** * Internal method to store multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalSetItems(array & $normalizedKeyValuePairs) { $failedKeys = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!$this->internalSetItem($normalizedKey, $value, $normalizedOptions)) { + if (!$this->internalSetItem($normalizedKey, $value)) { $failedKeys[] = $normalizedKey; } } @@ -921,17 +782,8 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n /** * Add an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -939,18 +791,16 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * @triggers addItem.post(PostEvent) * @triggers addItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + public function addItem($key, $value) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, + 'key' => & $key, + 'value' => & $value, )); try { @@ -959,7 +809,7 @@ public function addItem($key, $value, array $options = array()) return $eventRs->last(); } - $result = $this->internalAddItem($args['key'], $args['value'], $args['options']); + $result = $this->internalAddItem($args['key'], $args['value']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -970,41 +820,23 @@ public function addItem($key, $value, array $options = array()) /** * Internal method to add an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalAddItem(& $normalizedKey, & $value) { - if ($this->internalHasItem($normalizedKey, $normalizedOptions)) { + if ($this->internalHasItem($normalizedKey)) { return false; } - return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); + return $this->internalSetItem($normalizedKey, $value); } /** * Add multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param array $keyValuePairs - * @param array $options * @return array Array of not stored keys * @throws Exception\ExceptionInterface * @@ -1012,17 +844,15 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz * @triggers addItems.post(PostEvent) * @triggers addItems.exception(ExceptionEvent) */ - public function addItems(array $keyValuePairs, array $options = array()) + public function addItems(array $keyValuePairs) { if (!$this->getOptions()->getWritable()) { return array_keys($keyValuePairs); } $this->normalizeKeyValuePairs($keyValuePairs); - $this->normalizeOptions($options); $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, )); try { @@ -1031,7 +861,7 @@ public function addItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - $result = $this->internalAddItems($args['keyValuePairs'], $args['options']); + $result = $this->internalAddItems($args['keyValuePairs']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array_keys($keyValuePairs); @@ -1042,24 +872,15 @@ public function addItems(array $keyValuePairs, array $options = array()) /** * Internal method to add multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalAddItems(array & $normalizedKeyValuePairs) { $result = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!$this->internalAddItem($normalizedKey, $value, $normalizedOptions)) { + if (!$this->internalAddItem($normalizedKey, $value)) { $result[] = $normalizedKey; } } @@ -1069,17 +890,8 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n /** * Replace an existing item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -1087,18 +899,16 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n * @triggers replaceItem.post(PostEvent) * @triggers replaceItem.exception(ExceptionEvent) */ - public function replaceItem($key, $value, array $options = array()) + public function replaceItem($key, $value) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, + 'key' => & $key, + 'value' => & $value, )); try { @@ -1107,7 +917,7 @@ public function replaceItem($key, $value, array $options = array()) return $eventRs->last(); } - $result = $this->internalReplaceItem($args['key'], $args['value'], $args['options']); + $result = $this->internalReplaceItem($args['key'], $args['value']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -1118,42 +928,24 @@ public function replaceItem($key, $value, array $options = array()) /** * Internal method to replace an existing item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalReplaceItem(& $normalizedKey, & $value) { - if (!$this->internalhasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalhasItem($normalizedKey)) { return false; } - return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); + return $this->internalSetItem($normalizedKey, $value); } /** * Replace multiple existing items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param array $keyValuePairs - * @param array $options * @return array Array of not stored keys * @throws Exception\ExceptionInterface * @@ -1161,17 +953,15 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm * @triggers replaceItems.post(PostEvent) * @triggers replaceItems.exception(ExceptionEvent) */ - public function replaceItems(array $keyValuePairs, array $options = array()) + public function replaceItems(array $keyValuePairs) { if (!$this->getOptions()->getWritable()) { return array_keys($keyValuePairs); } $this->normalizeKeyValuePairs($keyValuePairs); - $this->normalizeOptions($options); $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, )); try { @@ -1180,7 +970,7 @@ public function replaceItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - $result = $this->internalReplaceItems($args['keyValuePairs'], $args['options']); + $result = $this->internalReplaceItems($args['keyValuePairs']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array_keys($keyValuePairs); @@ -1191,24 +981,15 @@ public function replaceItems(array $keyValuePairs, array $options = array()) /** * Internal method to replace multiple existing items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalReplaceItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalReplaceItems(array & $normalizedKeyValuePairs) { $result = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - if (!$this->internalReplaceItem($normalizedKey, $value, $normalizedOptions)) { + if (!$this->internalReplaceItem($normalizedKey, $value)) { $result[] = $normalizedKey; } } @@ -1221,36 +1002,25 @@ protected function internalReplaceItems(array & $normalizedKeyValuePairs, array * It uses the token received from getItem() to check if the item has * changed before overwriting it. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param mixed $token * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @see getItem() * @see setItem() */ - public function checkAndSetItem($token, $key, $value, array $options = array()) + public function checkAndSetItem($token, $key, $value) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'token' => & $token, - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, + 'token' => & $token, + 'key' => & $key, + 'value' => & $value, )); try { @@ -1259,7 +1029,7 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) return $eventRs->last(); } - $result = $this->internalCheckAndSetItem($args['token'], $args['key'], $args['value'], $args['options']); + $result = $this->internalCheckAndSetItem($args['token'], $args['key'], $args['value']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -1270,44 +1040,28 @@ public function checkAndSetItem($token, $key, $value, array $options = array()) /** * Internal method to set an item only if token matches * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param mixed $token * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface * @see getItem() * @see setItem() */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) + protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) { - $oldValue = $this->internalGetItem($normalizedKey, $normalizedOptions); + $oldValue = $this->internalGetItem($normalizedKey); if ($oldValue !== $token) { return false; } - return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); + return $this->internalSetItem($normalizedKey, $value); } /** * Reset lifetime of an item * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -1315,17 +1069,15 @@ protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, * @triggers touchItem.post(PostEvent) * @triggers touchItem.exception(ExceptionEvent) */ - public function touchItem($key, array $options = array()) + public function touchItem($key) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, + 'key' => & $key, )); try { @@ -1334,7 +1086,7 @@ public function touchItem($key, array $options = array()) return $eventRs->last(); } - $result = $this->internalTouchItem($args['key'], $args['options']); + $result = $this->internalTouchItem($args['key']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -1345,47 +1097,25 @@ public function touchItem($key, array $options = array()) /** * Internal method to reset lifetime of an item * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) + protected function internalTouchItem(& $normalizedKey) { $success = null; - $value = $this->internalGetItem($normalizedKey, $normalizedOptions, $success); + $value = $this->internalGetItem($normalizedKey, $success); if (!$success) { return false; } - // rewrite item to update mtime/ttl - if (!isset($normalizedOptions['tags'])) { - $info = $this->internalGetMetadata($normalizedKey, $normalizedOptions); - if (isset($info['tags'])) { - $normalizedOptions['tags'] = & $info['tags']; - } - } - - return $this->internalReplaceItem($normalizedKey, $value, $normalizedOptions); + return $this->internalReplaceItem($normalizedKey, $value); } /** * Reset lifetime of multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Array of not updated keys * @throws Exception\ExceptionInterface * @@ -1393,17 +1123,15 @@ protected function internalTouchItem(& $normalizedKey, array & $normalizedOption * @triggers touchItems.post(PostEvent) * @triggers touchItems.exception(ExceptionEvent) */ - public function touchItems(array $keys, array $options = array()) + public function touchItems(array $keys) { if (!$this->getOptions()->getWritable()) { return $keys; } $this->normalizeKeys($keys); - $this->normalizeOptions($options); $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, + 'keys' => & $keys, )); try { @@ -1412,7 +1140,7 @@ public function touchItems(array $keys, array $options = array()) return $eventRs->last(); } - $result = $this->internalTouchItems($args['keys'], $args['options']); + $result = $this->internalTouchItems($args['keys']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $keys, $e); @@ -1422,22 +1150,15 @@ public function touchItems(array $keys, array $options = array()) /** * Internal method to reset lifetime of multiple items. * - * Options: - * - ttl - * - The namespace to us - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Array of not updated keys * @throws Exception\ExceptionInterface */ - protected function internalTouchItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalTouchItems(array & $normalizedKeys) { $result = array(); foreach ($normalizedKeys as $normalizedKey) { - if (!$this->internalTouchItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalTouchItem($normalizedKey)) { $result[] = $normalizedKey; } } @@ -1447,12 +1168,7 @@ protected function internalTouchItems(array & $normalizedKeys, array & $normaliz /** * Remove an item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -1460,17 +1176,15 @@ protected function internalTouchItems(array & $normalizedKeys, array & $normaliz * @triggers removeItem.post(PostEvent) * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + public function removeItem($key) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'options' => & $options, + 'key' => & $key, )); try { @@ -1479,7 +1193,7 @@ public function removeItem($key, array $options = array()) return $eventRs->last(); } - $result = $this->internalRemoveItem($args['key'], $args['options']); + $result = $this->internalRemoveItem($args['key']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -1490,26 +1204,16 @@ public function removeItem($key, array $options = array()) /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - abstract protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions); + abstract protected function internalRemoveItem(& $normalizedKey); /** * Remove multiple items. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Array of not removed keys * @throws Exception\ExceptionInterface * @@ -1517,17 +1221,15 @@ abstract protected function internalRemoveItem(& $normalizedKey, array & $normal * @triggers removeItems.post(PostEvent) * @triggers removeItems.exception(ExceptionEvent) */ - public function removeItems(array $keys, array $options = array()) + public function removeItems(array $keys) { if (!$this->getOptions()->getWritable()) { return $keys; } - $this->normalizeOptions($options); $this->normalizeKeys($keys); $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, + 'keys' => & $keys, )); try { @@ -1536,7 +1238,7 @@ public function removeItems(array $keys, array $options = array()) return $eventRs->last(); } - $result = $this->internalRemoveItems($args['keys'], $args['options']); + $result = $this->internalRemoveItems($args['keys']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $keys, $e); @@ -1546,20 +1248,15 @@ public function removeItems(array $keys, array $options = array()) /** * Internal method to remove multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $keys - * @param array $options * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ - protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalRemoveItems(array & $normalizedKeys) { $result = array(); foreach ($normalizedKeys as $normalizedKey) { - if (!$this->internalRemoveItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalRemoveItem($normalizedKey)) { $result[] = $normalizedKey; } } @@ -1569,15 +1266,8 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali /** * Increment an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key * @param int $value - * @param array $options * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface * @@ -1585,18 +1275,16 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali * @triggers incrementItem.post(PostEvent) * @triggers incrementItem.exception(ExceptionEvent) */ - public function incrementItem($key, $value, array $options = array()) + public function incrementItem($key, $value) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, + 'key' => & $key, + 'value' => & $value, )); try { @@ -1605,7 +1293,7 @@ public function incrementItem($key, $value, array $options = array()) return $eventRs->last(); } - $result = $this->internalIncrementItem($args['key'], $args['value'], $args['options']); + $result = $this->internalIncrementItem($args['key'], $args['value']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -1616,29 +1304,22 @@ public function incrementItem($key, $value, array $options = array()) /** * Internal method to increment an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalIncrementItem(& $normalizedKey, & $value) { $success = null; $value = (int) $value; - $get = (int) $this->internalGetItem($normalizedKey, $normalizedOptions, $success); + $get = (int) $this->internalGetItem($normalizedKey, $success); $newValue = $get + $value; if ($success) { - $this->internalReplaceItem($normalizedKey, $newValue, $normalizedOptions); + $this->internalReplaceItem($normalizedKey, $newValue); } else { - $this->internalAddItem($normalizedKey, $newValue, $normalizedOptions); + $this->internalAddItem($normalizedKey, $newValue); } return $newValue; @@ -1647,14 +1328,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no /** * Increment multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keyValuePairs - * @param array $options * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface * @@ -1662,17 +1336,15 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no * @triggers incrementItems.post(PostEvent) * @triggers incrementItems.exception(ExceptionEvent) */ - public function incrementItems(array $keyValuePairs, array $options = array()) + public function incrementItems(array $keyValuePairs) { if (!$this->getOptions()->getWritable()) { return array(); } - $this->normalizeOptions($options); $this->normalizeKeyValuePairs($keyValuePairs); $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, )); try { @@ -1681,7 +1353,7 @@ public function incrementItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - $result = $this->internalIncrementItems($args['keyValuePairs'], $args['options']); + $result = $this->internalIncrementItems($args['keyValuePairs']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array(); @@ -1692,22 +1364,15 @@ public function incrementItems(array $keyValuePairs, array $options = array()) /** * Internal method to increment multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface */ - protected function internalIncrementItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalIncrementItems(array & $normalizedKeyValuePairs) { $result = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $newValue = $this->internalIncrementItem($normalizedKey, $value, $normalizedOptions); + $newValue = $this->internalIncrementItem($normalizedKey, $value); if ($newValue !== false) { $result[$normalizedKey] = $newValue; } @@ -1718,15 +1383,8 @@ protected function internalIncrementItems(array & $normalizedKeyValuePairs, arra /** * Decrement an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key * @param int $value - * @param array $options * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface * @@ -1734,18 +1392,16 @@ protected function internalIncrementItems(array & $normalizedKeyValuePairs, arra * @triggers decrementItem.post(PostEvent) * @triggers decrementItem.exception(ExceptionEvent) */ - public function decrementItem($key, $value, array $options = array()) + public function decrementItem($key, $value) { if (!$this->getOptions()->getWritable()) { return false; } - $this->normalizeOptions($options); $this->normalizeKey($key); $args = new ArrayObject(array( - 'key' => & $key, - 'value' => & $value, - 'options' => & $options, + 'key' => & $key, + 'value' => & $value, )); try { @@ -1754,7 +1410,7 @@ public function decrementItem($key, $value, array $options = array()) return $eventRs->last(); } - $result = $this->internalDecrementItem($args['key'], $args['value'], $args['options']); + $result = $this->internalDecrementItem($args['key'], $args['value']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = false; @@ -1765,29 +1421,22 @@ public function decrementItem($key, $value, array $options = array()) /** * Internal method to decrement an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalDecrementItem(& $normalizedKey, & $value) { $success = null; $value = (int) $value; - $get = (int) $this->internalGetItem($normalizedKey, $normalizedOptions, $success); + $get = (int) $this->internalGetItem($normalizedKey, $success); $newValue = $get - $value; if ($success) { - $this->internalReplaceItem($normalizedKey, $newValue, $normalizedOptions); + $this->internalReplaceItem($normalizedKey, $newValue); } else { - $this->internalAddItem($normalizedKey, $newValue, $normalizedOptions); + $this->internalAddItem($normalizedKey, $newValue); } return $newValue; @@ -1796,14 +1445,7 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no /** * Decrement multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keyValuePairs - * @param array $options * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface * @@ -1811,17 +1453,15 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no * @triggers incrementItems.post(PostEvent) * @triggers incrementItems.exception(ExceptionEvent) */ - public function decrementItems(array $keyValuePairs, array $options = array()) + public function decrementItems(array $keyValuePairs) { if (!$this->getOptions()->getWritable()) { return array(); } - $this->normalizeOptions($options); $this->normalizeKeyValuePairs($keyValuePairs); $args = new ArrayObject(array( 'keyValuePairs' => & $keyValuePairs, - 'options' => & $options, )); try { @@ -1830,7 +1470,7 @@ public function decrementItems(array $keyValuePairs, array $options = array()) return $eventRs->last(); } - $result = $this->internalDecrementItems($args['keyValuePairs'], $args['options']); + $result = $this->internalDecrementItems($args['keyValuePairs']); return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { $result = array(); @@ -1841,22 +1481,15 @@ public function decrementItems(array $keyValuePairs, array $options = array()) /** * Internal method to decrement multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Associative array of keys and new values * @throws Exception\ExceptionInterface */ - protected function internalDecrementItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalDecrementItems(array & $normalizedKeyValuePairs) { $result = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $newValue = $this->decrementItem($normalizedKey, $value, $normalizedOptions); + $newValue = $this->decrementItem($normalizedKey, $value); if ($newValue !== false) { $result[$normalizedKey] = $newValue; } @@ -1864,521 +1497,6 @@ protected function internalDecrementItems(array & $normalizedKeyValuePairs, arra return $result; } - /* non-blocking */ - - /** - * Request multiple items. - * - * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - select optional - * - An array of the information the returned item contains - * (Default: array('key', 'value')) - * - callback optional - * - An result callback will be invoked for each item in the result set. - * - The first argument will be the item array. - * - The callback does not have to return anything. - * - * @param array $keys - * @param array $options - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - * - * @triggers getDelayed.pre(PreEvent) - * @triggers getDelayed.post(PostEvent) - * @triggers getDelayed.exception(ExceptionEvent) - */ - public function getDelayed(array $keys, array $options = array()) - { - if (!$this->getOptions()->getReadable()) { - return false; - } elseif (!$keys) { - // empty statement - return true; - } - - $this->normalizeKeys($keys); - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'keys' => & $keys, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalGetDelayed($args['keys'], $args['options']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to request multiple items. - * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * - select - * - An array of the information the returned item contains - * - callback optional - * - An result callback will be invoked for each item in the result set. - * - The first argument will be the item array. - * - The callback does not have to return anything. - * - * @param array $normalizedKeys - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - $this->stmtOptions = array_merge($this->getOptions()->toArray(), $normalizedOptions); - $this->stmtKeys = & $normalizedKeys; - $this->stmtActive = true; - - if (isset($normalizedOptions['callback'])) { - $callback = $normalizedOptions['callback']; - if (!is_callable($callback, false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - while ( ($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - return true; - } - - /* find */ - - /** - * Find items. - * - * Options: - * - ttl optional - * - The time-to-live (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - Tags to search for used with matching modes of - * Adapter::MATCH_TAGS_* - * - * @param int $mode Matching mode (Value of Adapter::MATCH_*) - * @param array $options - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - * - * @triggers find.pre(PreEvent) - * @triggers find.post(PostEvent) - * @triggers find.exception(ExceptionEvent) - */ - public function find($mode = self::MATCH_ACTIVE, array $options = array()) - { - if (!$this->getOptions()->getReadable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_ACTIVE, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalFind($args['mode'], $args['options']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * internal method to find items. - * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * - tags - * - Tags to search for used with matching modes of - * Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalFind(& $normalizedMode, array & $normalizedOptions) - { - throw new Exception\UnsupportedMethodCallException('find isn\'t supported by this adapter'); - } - - /** - * Fetches the next item from result set - * - * @return array|boolean The next item or false - * @throws Exception\ExceptionInterface - * @see fetchAll() - * - * @triggers fetch.pre(PreEvent) - * @triggers fetch.post(PostEvent) - * @triggers fetch.exception(ExceptionEvent) - */ - public function fetch() - { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalFetch(); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to fetch the next item from result set - * - * @return array|boolean The next item or false - * @throws Exception\ExceptionInterface - */ - protected function internalFetch() - { - if (!$this->stmtActive) { - return false; - } - - $options = $this->stmtOptions; - $success = null; - - do { - $key = array_shift($this->stmtKeys); - if ($key === null) { - break; - } - - $item = array(); - $value = $info = $exist = null; - foreach ($options['select'] as $select) { - if ($select == 'key') { - $item['key'] = $key; - } elseif ($select == 'value') { - $value = $this->internalGetItem($key, $options, $success); - if (!$success) { - $exist = false; - break; - } - $exist = true; - $item['value'] = $value; - } else { - if ($info === null) { - $info = $this->internalGetMetadata($key, $options); - if ($info === false) { - $exist = false; - break; - } - $exist = true; - } - $item[$select] = isset($info[$select]) ? $info[$select] : null; - } - } - - // goto next if not exists - if ($exist === false || ($exist === null && !$this->internalHasItem($key, $options))) { - continue; - } - - return $item; - } while (true); - - // clear statement - $this->stmtActive = false; - $this->stmtKeys = null; - $this->stmtOptions = null; - - return false; - } - - /** - * Returns all items of result set. - * - * @return array The result set as array containing all items - * @throws Exception\ExceptionInterface - * @see fetch() - * - * @triggers fetchAll.pre(PreEvent) - * @triggers fetchAll.post(PostEvent) - * @triggers fetchAll.exception(ExceptionEvent) - */ - public function fetchAll() - { - $args = new ArrayObject(); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalFetchAll(); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = array(); - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to return all items of result set. - * - * @return array The result set as array containing all items - * @throws Exception\ExceptionInterface - * @see fetch() - */ - protected function internalFetchAll() - { - $rs = array(); - while (($item = $this->internalFetch()) !== false) { - $rs[] = $item; - } - return $rs; - } - - /* cleaning */ - - /** - * Clear items off all namespaces. - * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - tags optional - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $mode Matching mode (Value of Adapter::MATCH_*) - * @param array $options - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - * - * @triggers clear.pre(PreEvent) - * @triggers clear.post(PostEvent) - * @triggers clear.exception(ExceptionEvent) - */ - public function clear($mode = self::MATCH_EXPIRED, array $options = array()) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalClear($args['mode'], $args['options']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to clear items off all namespaces. - * - * Options: - * - ttl - * - The time-to-life - * - tags - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - throw new Exception\RuntimeException( - "This adapter doesn't support to clear items off all namespaces" - ); - } - - /** - * Clear items by namespace. - * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $mode Matching mode (Value of Adapter::MATCH_*) - * @param array $options - * @return boolean - * @throws Exception\ExceptionInterface - * @see clear() - * - * @triggers clearByNamespace.pre(PreEvent) - * @triggers clearByNamespace.post(PostEvent) - * @triggers clearByNamespace.exception(ExceptionEvent) - */ - public function clearByNamespace($mode = self::MATCH_EXPIRED, array $options = array()) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $this->normalizeOptions($options); - $this->normalizeMatchingMode($mode, self::MATCH_EXPIRED, $options); - $args = new ArrayObject(array( - 'mode' => & $mode, - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalClearByNamespace($args['mode'], $args['options']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Clear items by namespace. - * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clear() - */ - protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) - { - throw new Exception\RuntimeException( - "This adapter doesn't support to clear items by namespace" - ); - } - - /** - * Optimize adapter storage. - * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - * @param array $options - * @return boolean - * @throws Exception\ExceptionInterface - * - * @triggers optimize.pre(PreEvent) - * @triggers optimize.post(PostEvent) - * @triggers optimize.exception(ExceptionEvent) - */ - public function optimize(array $options = array()) - { - if (!$this->getOptions()->getWritable()) { - return false; - } - - $args = new ArrayObject(array( - 'options' => & $options - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalOptimize($args['options']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to optimize adapter storage. - * - * Options: - * - namespace - * - The namespace to use - * - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - */ - protected function internalOptimize(array & $normalizedOptions) - { - return true; - } - /* status */ /** @@ -2421,185 +1539,8 @@ protected function internalGetCapabilities() return $this->capabilities; } - /** - * Get storage capacity. - * - * @param array $options - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - * - * @triggers getCapacity.pre(PreEvent) - * @triggers getCapacity.post(PostEvent) - * @triggers getCapacity.exception(ExceptionEvent) - */ - public function getCapacity(array $options = array()) - { - $this->normalizeOptions($options); - $args = new ArrayObject(array( - 'options' => & $options, - )); - - try { - $eventRs = $this->triggerPre(__FUNCTION__, $args); - if ($eventRs->stopped()) { - return $eventRs->last(); - } - - $result = $this->internalGetCapacity($args['options']); - return $this->triggerPost(__FUNCTION__, $args, $result); - } catch (\Exception $e) { - $result = false; - return $this->triggerException(__FUNCTION__, $args, $result, $e); - } - } - - /** - * Internal method to get storage capacity. - * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - */ - abstract protected function internalGetCapacity(array & $normalizedOptions); - /* internal */ - /** - * Validates and normalizes the $options argument - * - * @param array $options - * @return void - */ - protected function normalizeOptions(array &$options) - { - $baseOptions = $this->getOptions(); - - // ttl - if (isset($options['ttl'])) { - $this->normalizeTtl($options['ttl']); - } else { - $options['ttl'] = $baseOptions->getTtl(); - } - - // namespace - if (isset($options['namespace'])) { - $this->normalizeNamespace($options['namespace']); - } else { - $options['namespace'] = $baseOptions->getNamespace(); - } - - // tags - if (isset($options['tags'])) { - $this->normalizeTags($options['tags']); - } else { - $options['tags'] = null; - } - - // select - if (isset($options['select'])) { - $this->normalizeSelect($options['select']); - } else { - $options['select'] = array('key', 'value'); - } - } - - /** - * Validates and normalize a TTL. - * - * @param int|float $ttl - * @return void - * @throws Exception\InvalidArgumentException - */ - protected function normalizeTtl(&$ttl) - { - if (!is_int($ttl)) { - $ttl = (float) $ttl; - - // convert to int if possible - if ($ttl === (float) (int) $ttl) { - $ttl = (int) $ttl; - } - } - - if ($ttl < 0) { - throw new Exception\InvalidArgumentException("TTL can't be negative"); - } - } - - /** - * Validates and normalize a namespace. - * - * @param string $namespace - * @return void - * @throws Exception\InvalidArgumentException - */ - protected function normalizeNamespace(&$namespace) - { - $namespace = (string) $namespace; - $pattern = $this->getOptions()->getNamespacePattern(); - if ($pattern && !preg_match($pattern, $namespace)) { - throw new Exception\InvalidArgumentException( - "The namespace '{$namespace}' doesn't match against pattern '{$pattern}'" - ); - } - } - - /** - * Validates and normalize tags array - * - * @param array $tags - * @return void - * @throws Exception\InvalidArgumentException - */ - protected function normalizeTags(&$tags) - { - if (!is_array($tags)) { - throw new Exception\InvalidArgumentException('Tags have to be an array'); - } - - foreach ($tags as &$tag) { - $tag = (string) $tag; - if ($tag === '') { - throw new Exception\InvalidArgumentException('Empty tags are not allowed'); - } - } - - $tags = array_values(array_unique($tags)); - } - - /** - * Validates and normalize select array - * - * @param string[]|string - * @return void - */ - protected function normalizeSelect(&$select) - { - if (!is_array($select)) { - $select = array((string) $select); - } else { - $select = array_unique($select); - } - } - - /** - * Normalize the matching mode needed on (clear and find) - * - * @todo normalize matching mode with given tags - * @param int $mode Matching mode to normalize - * @param int $default Default matching mode - * @return void - */ - protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOptions) - { - $mode = (int) $mode; - if (($mode & self::MATCH_EXPIRED) != self::MATCH_EXPIRED - && ($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE - ) { - $mode = $mode | (int) $default; - } - } - /** * Validates and normalizes a key * @@ -2607,7 +1548,7 @@ protected function normalizeMatchingMode(&$mode, $default, array &$normalizedOpt * @return void * @throws Exception\InvalidArgumentException On an invalid key */ - protected function normalizeKey(&$key) + protected function normalizeKey(& $key) { $key = (string) $key; @@ -2629,7 +1570,7 @@ protected function normalizeKey(&$key) * @return void * @throws Exception\InvalidArgumentException On an invalid key */ - protected function normalizeKeys(array &$keys) + protected function normalizeKeys(array & $keys) { if (!$keys) { throw new Exception\InvalidArgumentException( @@ -2657,18 +1598,4 @@ protected function normalizeKeyValuePairs(array & $keyValuePairs) } $keyValuePairs = $normalizedKeyValuePairs; } - - /** - * Return registry of plugins - * - * @return SplObjectStorage - */ - protected function getPluginRegistry() - { - if (!$this->pluginRegistry instanceof SplObjectStorage) { - $this->pluginRegistry = new SplObjectStorage(); - } - return $this->pluginRegistry; - } - } diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 349cdb1cf..35e3114ce 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -47,21 +47,18 @@ abstract class AbstractZendServer extends AbstractAdapter /** * Internal method to get an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) { - $internalKey = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR . $normalizedKey; - $result = $this->zdcFetch($internalKey); + $prefix = $this->getOptions()->getNamespace() . self::NAMESPACE_SEPARATOR; + $internalKey = $prefix . $normalizedKey; + + $result = $this->zdcFetch($internalKey); if ($result === false) { $success = false; $result = null; @@ -76,27 +73,22 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, /** * Internal method to get multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { - $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; + $prefix = $this->getOptions()->getNamespace() . self::NAMESPACE_SEPARATOR; + $prefixL = strlen($prefix); $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { $internalKeys[] = $prefix . $normalizedKey; } - $fetch = $this->zdcFetchMulti($internalKeys); - $prefixL = strlen($prefix); - $result = array(); + $fetch = $this->zdcFetchMulti($internalKeys); + $result = array(); foreach ($fetch as $k => & $v) { $result[ substr($k, $prefixL) ] = $v; } @@ -107,45 +99,37 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Internal method to test if an item exists. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { - $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; + + $prefix = $this->getOptions()->getNamespace() . self::NAMESPACE_SEPARATOR; return ($this->zdcFetch($prefix . $normalizedKey) !== false); } /** * Internal method to test multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $keys - * @param array $options * @return array Array of found keys * @throws Exception\ExceptionInterface */ - protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalHasItems(array & $normalizedKeys) { - $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; + $prefix = $this->getOptions()->getNamespace() . self::NAMESPACE_SEPARATOR; + $prefixL = strlen($prefix); $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { $internalKeys[] = $prefix . $normalizedKey; } - $fetch = $this->zdcFetchMulti($internalKeys); - $prefixL = strlen($prefix); - $result = array(); + $fetch = $this->zdcFetchMulti($internalKeys); + $result = array(); foreach ($fetch as $internalKey => & $value) { $result[] = substr($internalKey, $prefixL); } @@ -156,29 +140,25 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized /** * Get metadata for multiple items * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and metadata * * @triggers getMetadatas.pre(PreEvent) * @triggers getMetadatas.post(PostEvent) * @triggers getMetadatas.exception(ExceptionEvent) */ - protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetMetadatas(array & $normalizedKeys) { - $prefix = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR; + $prefix = $this->getOptions()->getNamespace() . self::NAMESPACE_SEPARATOR; + $prefixL = strlen($prefix); + $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { $internalKeys[] = $prefix . $normalizedKey; } - $fetch = $this->zdcFetchMulti($internalKeys); - $prefixL = strlen($prefix); - $result = array(); + $fetch = $this->zdcFetchMulti($internalKeys); + $result = array(); foreach ($fetch as $internalKey => $value) { $result[ substr($internalKey, $prefixL) ] = array(); } @@ -191,91 +171,32 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal /** * Internal method to store an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalSetItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR . $normalizedKey; - $this->zdcStore($internalKey, $value, $normalizedOptions['ttl']); + $options = $this->getOptions(); + $internalKey = $options->getNamespace() . self::NAMESPACE_SEPARATOR . $normalizedKey; + $this->zdcStore($internalKey, $value, $options->getTtl()); return true; } /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) + protected function internalRemoveItem(& $normalizedKey) { - $internalKey = $normalizedOptions['namespace'] . self::NAMESPACE_SEPARATOR . $normalizedKey; + $internalKey = $this->getOptions()->getNamespace() . self::NAMESPACE_SEPARATOR . $normalizedKey; return $this->zdcDelete($internalKey); } - /* cleaning */ - - /** - * Internal method to clear items off all namespaces. - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - // clear all - if (($normalizedMode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $this->zdcClear(); - } - - // expired items will be deleted automatic - - return true; - } - - /** - * Clear items by namespace. - * - * Options: - * - namespace - * - The namespace to use - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clear() - */ - protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) - { - // clear all - if (($normalizedMode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $this->zdcClearByNamespace($normalizedOptions['namespace']); - } - - // expired items will be deleted automatic - - return true; - } - /* status */ /** @@ -304,16 +225,12 @@ protected function internalGetCapabilities() 'supportedMetadata' => array(), 'maxTtl' => 0, 'staticTtl' => true, - 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => false, 'expiredRead' => false, 'maxKeyLength' => 0, 'namespaceIsPrefix' => true, 'namespaceSeparator' => self::NAMESPACE_SEPARATOR, - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, ) ); } @@ -360,21 +277,4 @@ abstract protected function zdcFetchMulti(array $internalKeys); * @throws Exception\RuntimeException */ abstract protected function zdcDelete($internalKey); - - /** - * Clear items of all namespaces from Zend Data Cache (zdc) - * - * @return void - * @throws Exception\RuntimeException - */ - abstract protected function zdcClear(); - - /** - * Clear items of the given namespace from Zend Data Cache (zdc) - * - * @param string $namespace - * @return void - * @throws Exception\RuntimeException - */ - abstract protected function zdcClearByNamespace($namespace); } diff --git a/src/Storage/Adapter/AdapterInterface.php b/src/Storage/Adapter/AdapterInterface.php deleted file mode 100644 index d89071c2e..000000000 --- a/src/Storage/Adapter/AdapterInterface.php +++ /dev/null @@ -1,428 +0,0 @@ -adapter = $adapter; return $this; @@ -162,15 +156,8 @@ public function getKeyPattern() */ public function setNamespace($namespace) { - $namespace = (string)$namespace; + $namespace = (string) $namespace; if ($this->namespace !== $namespace) { - $pattern = $this->getNamespacePattern(); - if ($pattern && !preg_match($pattern, $namespace)) { - throw new Exception\InvalidArgumentException( - "The namespace '{$namespace}' doesn't match agains pattern '{$pattern}'" - ); - } - $this->triggerOptionEvent('namespace', $namespace); $this->namespace = $namespace; } @@ -188,48 +175,6 @@ public function getNamespace() return $this->namespace; } - /** - * Set namespace pattern - * - * @param null|string $pattern - * @return AdapterOptions - */ - public function setNamespacePattern($pattern) - { - $pattern = (string) $pattern; - if ($this->namespacePattern !== $pattern) { - if ($pattern !== '') { - // validate pattern - if (@preg_match($pattern, '') === false) { - $err = error_get_last(); - throw new Exception\InvalidArgumentException("Invalid pattern '{$pattern}': {$err['message']}"); - - // validate current namespace - } elseif (($ns = $this->getNamespace()) && !preg_match($pattern, $ns)) { - throw new Exception\RuntimeException( - "The current namespace '{$ns}' doesn't match agains pattern '{$pattern}'" - . " - please change the namespace first" - ); - } - } - - $this->triggerOptionEvent('namespace_pattern', $pattern); - $this->namespacePattern = $pattern; - } - - return $this; - } - - /** - * Get namespace pattern - * - * @return string - */ - public function getNamespacePattern() - { - return $this->namespacePattern; - } - /** * Enable/Disable reading data from cache. * diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 3eb71e1c0..af8d7f864 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -21,12 +21,18 @@ namespace Zend\Cache\Storage\Adapter; -use APCIterator, +use APCIterator as BaseApcIterator, ArrayObject, stdClass, Traversable, Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities; + Zend\Cache\Storage\Capabilities, + Zend\Cache\Storage\ClearByPrefixInterface, + Zend\Cache\Storage\ClearByNamespaceInterface, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\IterableInterface, + Zend\Cache\Storage\AvailableSpaceCapableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @package Zend_Cache @@ -35,31 +41,17 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Apc extends AbstractAdapter +class Apc + extends AbstractAdapter + implements ClearByPrefixInterface, ClearByNamespaceInterface, FlushableInterface, IterableInterface, + AvailableSpaceCapableInterface, TotalSpaceCapableInterface { /** - * Map selected properties on getDelayed & find - * to APCIterator selector + * Buffered total space in bytes * - * Init on constructor after ext/apc has been tested - * - * @var null|array + * @var null|int|float */ - protected static $selectMap = null; - - /** - * The used namespace separator - * - * @var string - */ - protected $namespaceSeparator = ':'; - - /** - * Statement - * - * @var null|APCIterator - */ - protected $stmtIterator = null; + protected $totalSpace; /** * Constructor @@ -85,25 +77,6 @@ public function __construct($options = null) ); } - // init select map - if (static::$selectMap === null) { - static::$selectMap = array( - // 'key' => \APC_ITER_KEY, - 'value' => \APC_ITER_VALUE, - 'mtime' => \APC_ITER_MTIME, - 'ctime' => \APC_ITER_CTIME, - 'atime' => \APC_ITER_ATIME, - 'rtime' => \APC_ITER_DTIME, - 'ttl' => \APC_ITER_TTL, - 'num_hits' => \APC_ITER_NUM_HITS, - 'ref_count' => \APC_ITER_REFCOUNT, - 'mem_size' => \APC_ITER_MEM_SIZE, - - // virtual keys - 'internal_key' => \APC_ITER_KEY, - ); - } - parent::__construct($options); } @@ -139,26 +112,113 @@ public function getOptions() return $this->options; } + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + if ($this->totalSpace !== null) { + $smaInfo = apc_sma_info(true); + $this->totalSpace = $smaInfo['num_seg'] * $smaInfo['seg_size']; + } + + return $this->totalSpace; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $smaInfo = apc_sma_info(true); + return $smaInfo['avail_mem']; + } + + /* IterableInterface */ + + /** + * Get the storage iterator + * + * @return ApcIterator + */ + public function getIterator() + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $pattern = '/^' . preg_quote($prefix, '/') . '/'; + $format = 0; + + $baseIt = new BaseApcIterator('user', $pattern, 0, 1, \APC_LIST_ACTIVE); + return new ApcIterator($this, $baseIt, $prefix); + } + + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + return apc_clear_cache('user'); + } + + /* ClearByNamespaceInterface */ + + /** + * Remove items by given namespace + * + * @param string $prefix + * @return boolean + */ + public function clearByNamespace($namespace) + { + $options = $this->getOptions(); + $prefix = $namespace . $options->getNamespaceSeparator(); + $pattern = '/^' . preg_quote($prefix, '/') . '+/'; + return apc_delete(new BaseApcIterator('user', $pattern, 0, 1, \APC_LIST_ACTIVE)); + } + + /* ClearByPrefixInterface */ + + /** + * Remove items matching given prefix + * + * @param string $prefix + * @return boolean + */ + public function clearByPrefix($prefix) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator() . $prefix; + $pattern = '/^' . preg_quote($prefix, '/') . '+/'; + return apc_delete(new BaseApcIterator('user', $pattern, 0, 1, \APC_LIST_ACTIVE)); + } /* reading */ /** * Internal method to get an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKey = $prefix . $normalizedKey; $result = apc_fetch($internalKey, $success); @@ -173,19 +233,14 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, /** * Internal method to get multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { - $namespaceSep = $this->getOptions()->getNamespaceSeparator(); - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { @@ -207,36 +262,29 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Internal method to test if an item exists. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); return apc_exists($prefix . $normalizedKey); } /** * Internal method to test multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $keys - * @param array $options * @return array Array of found keys * @throws Exception\ExceptionInterface */ - protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalHasItems(array & $normalizedKeys) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { $internalKeys[] = $prefix . $normalizedKey; @@ -257,12 +305,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized /** * Get metadata of an item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $normalizedKey - * @param array $normalizedOptions * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * @@ -270,17 +313,19 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * @triggers getMetadata.post(PostEvent) * @triggers getMetadata.exception(ExceptionEvent) */ - protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) + protected function internalGetMetadata(& $normalizedKey) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; // @see http://pecl.php.net/bugs/bug.php?id=22564 if (!apc_exists($internalKey)) { $metadata = false; } else { - $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE ^ \APC_ITER_REFCOUNT; $regexp = '/^' . preg_quote($internalKey, '/') . '$/'; - $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $it = new BaseApcIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); $metadata = $it->current(); } @@ -295,29 +340,26 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti /** * Get metadata of multiple items * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and metadata * * @triggers getMetadatas.pre(PreEvent) * @triggers getMetadatas.post(PostEvent) * @triggers getMetadatas.exception(ExceptionEvent) */ - protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetMetadatas(array & $normalizedKeys) { $keysRegExp = array(); foreach ($normalizedKeys as $normalizedKey) { $keysRegExp[] = preg_quote($normalizedKey, '/'); } - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $regexp = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $keysRegExp) . ')' . '$/'; - $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE; - $it = new APCIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $regexp = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $keysRegExp) . ')' . '$/'; + $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE ^ \APC_ITER_REFCOUNT; + + $it = new BaseApcIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); $result = array(); $prefixL = strlen($prefix); foreach ($it as $internalKey => $metadata) { @@ -338,48 +380,39 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal /** * Internal method to store an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalSetItem(& $normalizedKey, & $value) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKey = $prefix . $normalizedKey; - if (!apc_store($internalKey, $value, $normalizedOptions['ttl'])) { + $ttl = $options->getTtl(); + + if (!apc_store($internalKey, $value, $ttl)) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "apc_store('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + "apc_store('{$internalKey}', <{$type}>, {$ttl}) failed" ); } + return true; } /** * Internal method to store multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalSetItems(array & $normalizedKeyValuePairs) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKeyValuePairs = array(); foreach ($normalizedKeyValuePairs as $normalizedKey => &$value) { @@ -387,7 +420,7 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n $internalKeyValuePairs[$internalKey] = &$value; } - $failedKeys = apc_store($internalKeyValuePairs, null, $normalizedOptions['ttl']); + $failedKeys = apc_store($internalKeyValuePairs, null, $options->getTtl()); $failedKeys = array_keys($failedKeys); // remove prefix @@ -402,29 +435,26 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n /** * Add an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalAddItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - if (!apc_add($internalKey, $value, $normalizedOptions['ttl'])) { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $ttl = $options->getTtl(); + + if (!apc_add($internalKey, $value, $ttl)) { if (apc_exists($internalKey)) { return false; } $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "apc_add('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + "apc_add('{$internalKey}', <{$type}>, {$ttl}) failed" ); } @@ -434,27 +464,22 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to add multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalAddItems(array & $normalizedKeyValuePairs) { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKeyValuePairs = array(); - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { $internalKey = $prefix . $normalizedKey; $internalKeyValuePairs[$internalKey] = $value; } - $failedKeys = apc_add($internalKeyValuePairs, null, $normalizedOptions['ttl']); + $failedKeys = apc_add($internalKeyValuePairs, null, $options->getTtl()); $failedKeys = array_keys($failedKeys); // remove prefix @@ -469,29 +494,26 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n /** * Internal method to replace an existing item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalReplaceItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $ttl = $options->getTtl(); + if (!apc_exists($internalKey)) { return false; } - if (!apc_store($internalKey, $value, $normalizedOptions['ttl'])) { + if (!apc_store($internalKey, $value, $ttl)) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "apc_store('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + "apc_store('{$internalKey}', <{$type}>, {$ttl}) failed" ); } @@ -501,37 +523,31 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) + protected function internalRemoveItem(& $normalizedKey) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; return apc_delete($internalKey); } /** * Internal method to remove multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $keys - * @param array $options * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ - protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalRemoveItems(array & $normalizedKeys) { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKeys = array(); - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); foreach ($normalizedKeys as $normalizedKey) { $internalKeys[] = $prefix . $normalizedKey; } @@ -550,30 +566,27 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali /** * Internal method to increment an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalIncrementItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - $value = (int)$value; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $ttl = $options->getTtl(); + $value = (int) $value; $newValue = apc_inc($internalKey, $value); // initial value if ($newValue === false) { + $ttl = $options->getTtl(); $newValue = $value; - if (!apc_add($internalKey, $newValue, $normalizedOptions['ttl'])) { + if (!apc_add($internalKey, $newValue, $ttl)) { throw new Exception\RuntimeException( - "apc_add('{$internalKey}', {$newValue}, {$normalizedOptions['ttl']}) failed" + "apc_add('{$internalKey}', {$newValue}, {$ttl}) failed" ); } } @@ -584,31 +597,26 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no /** * Internal method to decrement an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalDecrementItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - $value = (int)$value; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $value = (int) $value; $newValue = apc_dec($internalKey, $value); // initial value if ($newValue === false) { - // initial value + $ttl = $options->getTtl(); $newValue = -$value; - if (!apc_add($internalKey, $newValue, $normalizedOptions['ttl'])) { + if (!apc_add($internalKey, $newValue, $ttl)) { throw new Exception\RuntimeException( - "apc_add('{$internalKey}', {$newValue}, {$normalizedOptions['ttl']}) failed" + "apc_add('{$internalKey}', {$newValue}, {$ttl}) failed" ); } } @@ -616,192 +624,6 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no return $newValue; } - /* non-blocking */ - - /** - * Internal method to request multiple items. - * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * - select - * - An array of the information the returned item contains - * - callback optional - * - An result callback will be invoked for each item in the result set. - * - The first argument will be the item array. - * - The callback does not have to return anything. - * - * @param array $normalizedKeys - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - if (isset($normalizedOptions['callback']) && !is_callable($normalizedOptions['callback'], false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - $format = 0; - foreach ($normalizedOptions['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; - } - } - - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $search = array(); - foreach ($normalizedKeys as $normalizedKey) { - $search[] = preg_quote($normalizedKey, '/'); - } - $search = '/^' . preg_quote($prefix, '/') . '(' . implode('|', $search) . ')$/'; - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = & $normalizedOptions; - - if (isset($normalizedOptions['callback'])) { - $callback = & $normalizedOptions['callback']; - while (($item = $this->fetch()) !== false) { - call_user_func($callback, $item); - } - } - - return true; - } - - /* find */ - - /** - * internal method to find items. - * - * Options: - * - namespace - * - The namespace to use - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalFind(& $normalizedMode, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - // This adapter doesn't support to read expired items - if (($normalizedMode & self::MATCH_ACTIVE) == self::MATCH_ACTIVE) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $search = '/^' . preg_quote($prefix, '/') . '+/'; - - $format = 0; - foreach ($normalizedOptions['select'] as $property) { - if (isset(self::$selectMap[$property])) { - $format = $format | self::$selectMap[$property]; - } - } - - $this->stmtIterator = new APCIterator('user', $search, $format, 1, \APC_LIST_ACTIVE); - $this->stmtActive = true; - $this->stmtOptions = & $normalizedOptions; - } - - return true; - } - - /** - * Internal method to fetch the next item from result set - * - * @return array|boolean The next item or false - * @throws Exception\ExceptionInterface - */ - protected function internalFetch() - { - if (!$this->stmtActive) { - return false; - } - - $prefix = $this->stmtOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $prefixL = strlen($prefix); - - do { - if (!$this->stmtIterator->valid()) { - // clear stmt - $this->stmtActive = false; - $this->stmtIterator = null; - $this->stmtOptions = null; - - return false; - } - - // @see http://pecl.php.net/bugs/bug.php?id=22564 - $exist = apc_exists($this->stmtIterator->key()); - if ($exist) { - $result = $this->stmtIterator->current(); - $this->normalizeMetadata($result); - - $select = $this->stmtOptions['select']; - if (in_array('key', $select)) { - $internalKey = $this->stmtIterator->key(); - $result['key'] = substr($internalKey, $prefixL); - } - } - - $this->stmtIterator->next(); - } while (!$exist); - - return $result; - } - - /* cleaning */ - - /** - * Internal method to clear items off all namespaces. - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - return $this->clearByRegEx('/.*/', $normalizedMode, $normalizedOptions); - } - - /** - * Clear items by namespace. - * - * Options: - * - namespace - * - The namespace to use - * - tags - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clear() - */ - protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) - { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $regex = '/^' . preg_quote($prefix, '/') . '+/'; - return $this->clearByRegEx($regex, $normalizedMode, $normalizedOptions); - } - /* status */ /** @@ -828,28 +650,18 @@ protected function internalGetCapabilities() 'resource' => false, ), 'supportedMetadata' => array( - 'atime', - 'ctime', 'internal_key', - 'mem_size', - 'mtime', - 'num_hits', - 'ref_count', - 'rtime', - 'ttl', + 'atime', 'ctime', 'mtime', 'rtime', + 'size', 'hits', 'ttl', ), 'maxTtl' => 0, 'staticTtl' => true, - 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => (bool) ini_get('apc.use_request_time'), 'expiredRead' => false, 'maxKeyLength' => 5182, 'namespaceIsPrefix' => true, 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - 'iterable' => true, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, ) ); @@ -869,76 +681,30 @@ protected function internalGetCapabilities() return $this->capabilities; } - /** - * Internal method to get storage capacity. - * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetCapacity(array & $normalizedOptions) - { - $mem = apc_sma_info(true); - return array( - 'free' => $mem['avail_mem'], - 'total' => $mem['num_seg'] * $mem['seg_size'], - ); - } - /* internal */ - /** - * Clear cached items based on key regex - * - * @param string $regex - * @param int $mode - * @param array $options - * @return bool - */ - protected function clearByRegEx($regex, $mode, array &$options) - { - if (($mode & self::MATCH_ACTIVE) != self::MATCH_ACTIVE) { - // no need to clear expired items - return true; - } - - return apc_delete(new APCIterator('user', $regex, 0, 1, \APC_LIST_ACTIVE)); - } - /** * Normalize metadata to work with APC * * @param array $metadata * @return void */ - protected function normalizeMetadata(array &$metadata) + protected function normalizeMetadata(array & $metadata) { - // rename - if (isset($metadata['creation_time'])) { - $metadata['ctime'] = $metadata['creation_time']; - unset($metadata['creation_time']); - } - - if (isset($metadata['access_time'])) { - $metadata['atime'] = $metadata['access_time']; - unset($metadata['access_time']); - } - - if (isset($metadata['deletion_time'])) { - $metadata['rtime'] = $metadata['deletion_time']; - unset($metadata['deletion_time']); - } - - // remove namespace prefix - if (isset($metadata['key'])) { - $pos = strpos($metadata['key'], $this->getOptions()->getNamespaceSeparator()); - if ($pos !== false) { - $metadata['internal_key'] = $metadata['key']; - } else { - $metadata['internal_key'] = $metadata['key']; - } - - unset($metadata['key']); - } + $metadata['internal_key'] = $metadata['key']; + $metadata['ctime'] = $metadata['creation_time']; + $metadata['atime'] = $metadata['access_time']; + $metadata['rtime'] = $metadata['deletion_time']; + $metadata['size'] = $metadata['mem_size']; + $metadata['hits'] = $metadata['num_hits']; + + unset( + $metadata['key'], + $metadata['creation_time'], + $metadata['access_time'], + $metadata['deletion_time'], + $metadata['mem_size'], + $metadata['num_hits'] + ); } } diff --git a/src/Storage/Adapter/ApcIterator.php b/src/Storage/Adapter/ApcIterator.php new file mode 100644 index 000000000..08f97a833 --- /dev/null +++ b/src/Storage/Adapter/ApcIterator.php @@ -0,0 +1,179 @@ +storage = $storage; + $this->baseIterator = $baseIterator; + $this->prefixLength = strlen($prefix); + } + + /** + * Get storage instance + * + * @return StorageInterface + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Get iterator mode + * + * @return int Value of IteratorInterface::CURRENT_AS_* + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set iterator mode + * + * @param int $mode + * @return ApcIterator Fluent interface + */ + public function setMode($mode) + { + $this->mode = (int) $mode; + return $this; + } + + /* Iterator */ + + /** + * Get current key, value or metadata. + * + * @return mixed + */ + public function current() + { + if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { + return $this; + } + + $key = $this->key(); + + if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { + return $this->storage->getItem($key); + } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { + return $this->storage->getMetadata($key); + } + + return $key; + } + + /** + * Get current key + * + * @return string + */ + public function key() + { + $key = $this->baseIterator->key(); + + // remove namespace prefix + return substr($key, $this->prefixLength); + } + + /** + * Move forward to next element + * + * @return void + */ + public function next() + { + $this->baseIterator->next(); + } + + /** + * Checks if current position is valid + * + * @return boolean + */ + public function valid() + { + return $this->baseIterator->valid(); + } + + /** + * Rewind the Iterator to the first element. + * + * @return void + */ + public function rewind() + { + return $this->baseIterator->rewind(); + } +} diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index b6b700e3e..97b6d90ec 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -27,7 +27,17 @@ Exception as BaseException, Zend\Cache\Exception, Zend\Cache\Storage, + Zend\Cache\Storage\StorageInterface, Zend\Cache\Storage\Capabilities, + Zend\Cache\Storage\ClearExpiredInterface, + Zend\Cache\Storage\ClearByNamespaceInterface, + Zend\Cache\Storage\ClearByPrefixInterface, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\IterableInterface, + Zend\Cache\Storage\AvailableSpaceCapableInterface, + Zend\Cache\Storage\OptimizableInterface, + Zend\Cache\Storage\TagableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface, Zend\Cache\Utils, Zend\Stdlib\ErrorHandler; @@ -38,21 +48,19 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Filesystem extends AbstractAdapter +class Filesystem + extends AbstractAdapter + implements FlushableInterface, ClearExpiredInterface, ClearByNamespaceInterface, ClearByPrefixInterface, + TagableInterface, IterableInterface, OptimizableInterface, + AvailableSpaceCapableInterface, TotalSpaceCapableInterface { - /** - * GlobIterator used as statement - * - * @var GlobIterator|null - */ - protected $stmtGlob = null; /** - * Matching mode of active statement + * Buffered total space in bytes * - * @var integer|null + * @var null|int|float */ - protected $stmtMatch = null; + protected $totalSpace; /** * An identity for the last filespec @@ -99,19 +107,358 @@ public function getOptions() return $this->options; } + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; + $dir = $this->getOptions()->getCacheDir(); + $clearFolder = null; + $clearFolder = function ($dir) use (& $clearFolder, $flags) { + $it = new GlobIterator($dir . \DIRECTORY_SEPARATOR . '*', $flags); + foreach ($it as $pathname) { + if ($it->isDir()) { + $clearFolder($pathname); + rmdir($pathname); + } else { + unlink($pathname); + } + } + }; + + ErrorHandler::start(); + $clearFolder($dir); + $error = ErrorHandler::stop(); + if ($error) { + throw new Exception\RuntimeException("Flushing directory '{$dir}' failed", 0, $error); + } + + return true; + } + + /* ClearExpiredInterface */ + + /** + * Remove expired items + * + * @return boolean + */ + public function clearExpired() + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + + $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_FILEINFO; + $path = $options->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + $glob = new GlobIterator($path, $flags); + $time = time(); + $ttl = $options->getTtl(); + + ErrorHandler::start(); + foreach ($glob as $entry) { + $mtime = $entry->getMTime(); + if ($time >= $mtime + $ttl) { + $pathname = $entry->getPathname(); + unlink($pathname); + + $tagPathname = substr($pathname, 0, -4) . '.tag'; + if (file_exists($tagPathname)) { + unlink($tagPathname); + } + + $ifoPathname = substr($pathname, 0, -4) . '.ifo'; + if (file_exists($ifoPathname)) { + unlink($ifoPathname); + } + } + } + $error = ErrorHandler::stop(); + if ($error) { + throw new Exception\RuntimeException("Failed to clear expired items", 0, $error); + } + + return true; + } + + /* ClearByNamespaceInterface */ + + /** + * Remove items by given namespace + * + * @param string $namespace + * @return boolean + */ + public function clearByNamespace($namespace) + { + $options = $this->getOptions(); + $nsPrefix = $namespace . $options->getNamespaceSeparator(); + + $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; + $path = $options->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $nsPrefix . '*', $options->getDirLevel()) + . \DIRECTORY_SEPARATOR . $nsPrefix . '*'; + $glob = new GlobIterator($path, $flags); + $time = time(); + $ttl = $options->getTtl(); + + ErrorHandler::start(); + foreach ($glob as $pathname) { + unlink($pathname); + } + $error = ErrorHandler::stop(); + if ($error) { + throw new Exception\RuntimeException("Failed to remove file '{$pathname}'", 0, $error); + } + + return true; + } + + /* ClearByPrefixInterface */ + + /** + * Remove items matching given prefix + * + * @param string $prefix + * @return boolean + */ + public function clearByPrefix($prefix) + { + $options = $this->getOptions(); + $nsPrefix = $options->getNamespace() . $options->getNamespaceSeparator(); + + $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; + $path = $options->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $nsPrefix . '*', $options->getDirLevel()) + . \DIRECTORY_SEPARATOR . $nsPrefix . $prefix . '*'; + $glob = new GlobIterator($path, $flags); + $time = time(); + $ttl = $options->getTtl(); + + ErrorHandler::start(); + foreach ($glob as $pathname) { + unlink($pathname); + } + $error = ErrorHandler::stop(); + if ($error) { + throw new Exception\RuntimeException("Failed to remove file '{$pathname}'", 0, $error); + } + + return true; + } + + /* TagableInterface */ + + /** + * Set tags to an item by given key. + * An empty array will remove all tags. + * + * @param string $key + * @param string[] $tags + * @return boolean + */ + public function setTags($key, array $tags) + { + $this->normalizeKey($key); + if (!$this->internalHasItem($key)) { + return false; + } + + $filespec = $this->getFileSpec($key); + + if (!$tags) { + $this->unlink($filespec . '.tag'); + return true; + } + + $this->putFileContent($filespec . '.tag', implode("\n", $tags)); + return true; + } + + /** + * Get tags of an item by given key + * + * @param string $key + * @return string[]|FALSE + */ + public function getTags($key) + { + $this->normalizeKey($key); + if (!$this->internalHasItem($key)) { + return false; + } + + $filespec = $this->getFileSpec($key); + $tags = array(); + if (file_exists($filespec . '.tag')) { + $tags = explode("\n", $this->getFileContent($filespec . '.tag')); + } + + return $tags; + } + + /** + * Remove items matching given tags. + * + * If $disjunction only one of the given tags must match + * else all given tags must match. + * + * @param string[] $tags + * @param boolean $disjunction + * @return boolean + */ + public function clearByTags(array $tags, $disjunction = false) + { + if (!$tags) { + return true; + } + + $tagCount = count($tags); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + + $flags = GlobIterator::SKIP_DOTS | GlobIterator::CURRENT_AS_PATHNAME; + $path = $options->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) + . \DIRECTORY_SEPARATOR . $prefix . '*.tag'; + $glob = new GlobIterator($path, $flags); + $time = time(); + $ttl = $options->getTtl(); + + foreach ($glob as $pathname) { + $diff = array_diff($tags, explode("\n", $this->getFileContent($pathname))); + + $rem = false; + if ($disjunction && count($diff) < $tagCount) { + $rem = true; + } elseif (!$disjunction && !$diff) { + $rem = true; + } + + if ($rem) { + unlink($pathname); + + $datPathname = substr($pathname, 0, -4) . '.dat'; + if (file_exists($datPathname)) { + unlink($datPathname); + } + + $ifoPathname = substr($pathname, 0, -4) . '.ifo'; + if (file_exists($ifoPathname)) { + unlink($ifoPathname); + } + } + } + + return true; + } + + /* IterableInterface */ + + /** + * Get the storage iterator + * + * @return FilesystemIterator + */ + public function getIterator() + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $path = $options->getCacheDir() + . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $options->getDirLevel()) + . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; + return new FilesystemIterator($this, $path, $prefix); + } + + /* OptimizableInterface */ + + /** + * Optimize the storage + * + * @return void + * @return Exception\RuntimeException + */ + public function optimize() + { + $baseOptions = $this->getOptions(); + if ($baseOptions->getDirLevel()) { + // removes only empty directories + $this->rmDir( + $baseOptions->getCacheDir(), + $baseOptions->getNamespace() . $baseOptions->getNamespaceSeparator() + ); + } + return true; + } + + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + if ($this->totalSpace !== null) { + $path = $this->getOptions()->getCacheDir(); + + ErrorHandler::start(); + $total = disk_total_space($path); + $error = ErrorHandler::stop(); + if ($total === false) { + throw new Exception\RuntimeException("Can't detect total space of '{$path}'", 0, $error); + } + + // clean total space buffer on change cache_dir + $events = $this->events(); + $handle = null; + $totalSpace = & $this->totalSpace; + $callback = function ($event) use (& $events, & $handle, & $totalSpace) { + $params = $event->getParams(); + if (isset($params['cache_dir'])) { + $totalSpace = null; + $events->detach($handle); + } + }; + $handle = $this->events()->attach($callback); + } + return $this->totalSpace; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $path = $this->getOptions()->getCacheDir(); + + ErrorHandler::start(); + $avail = disk_free_space($path); + $error = ErrorHandler::stop(); + if ($avail === false) { + throw new Exception\RuntimeException("Can't detect free space of '{$path}'", 0, $error); + } + + return $avail; + } + /* reading */ /** * Get an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure @@ -121,27 +468,27 @@ public function getOptions() * @triggers getItem.post(PostEvent) * @triggers getItem.exception(ExceptionEvent) */ - public function getItem($key, array $options = array(), & $success = null, & $casToken = null) + public function getItem($key, & $success = null, & $casToken = null) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::getItem($key, $options, $success, $casToken); + $argn = func_num_args(); + if ($argn > 2) { + return parent::getItem($key, $success, $casToken); + } elseif ($argn > 1) { + return parent::getItem($key, $success); + } else { + return parent::getItem($key); + } } /** * Get multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Associative array of keys and values * @throws Exception\ExceptionInterface * @@ -149,45 +496,37 @@ public function getItem($key, array $options = array(), & $success = null, & $ca * @triggers getItems.post(PostEvent) * @triggers getItems.exception(ExceptionEvent) */ - public function getItems(array $keys, array $options = array()) + public function getItems(array $keys) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::getItems($keys, $options); + return parent::getItems($keys); } /** * Internal method to get an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalHasItem($normalizedKey)) { $success = false; return null; } try { - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - $baseOptions = $this->getOptions(); - $data = $this->getFileContent($filespec . '.dat'); + $filespec = $this->getFileSpec($normalizedKey); + $data = $this->getFileContent($filespec . '.dat'); - if ($baseOptions->getReadControl()) { + if ($this->getOptions()->getReadControl()) { if ( ($info = $this->readInfoFile($filespec . '.ifo')) && isset($info['hash'], $info['algo']) && Utils::generateHash($info['algo'], $data, true) != $info['hash'] @@ -199,20 +538,14 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, } // use filemtime + filesize as CAS token - $casToken = filemtime($filespec . '.dat') . filesize($filespec . '.dat'); + if (func_num_args() > 2) { + $casToken = filemtime($filespec . '.dat') . filesize($filespec . '.dat'); + } $success = true; return $data; - } catch (Exception $e) { + } catch (BaseException $e) { $success = false; - - try { - // remove cache file on exception - $this->internalRemoveItem($normalizedKey, $normalizedOptions); - } catch (Exception $tmp) { - // do not throw remove exception on this point - } - throw $e; } } @@ -220,26 +553,15 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, /** * Internal method to get multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { - $baseOptions = $this->getOptions(); - - // Don't change arguments passed by reference - $keys = $normalizedKeys; - $options = $normalizedOptions; - - $result = array(); + $options = $this->getOptions(); + $keys = $normalizedKeys; // Don't change argument passed by reference + $result = array(); while ($keys) { // LOCK_NB if more than one items have to read @@ -248,12 +570,12 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized // read items foreach ($keys as $i => $key) { - if (!$this->internalHasItem($key, $options)) { + if (!$this->internalHasItem($key)) { unset($keys[$i]); continue; } - $filespec = $this->getFileSpec($key, $options); + $filespec = $this->getFileSpec($key); $data = $this->getFileContent($filespec . '.dat', $nonBlocking, $wouldblock); if ($nonBlocking && $wouldblock) { continue; @@ -261,7 +583,7 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized unset($keys[$i]); } - if ($baseOptions->getReadControl()) { + if ($options->getReadControl()) { $info = $this->readInfoFile($filespec . '.ifo'); if (isset($info['hash'], $info['algo']) && Utils::generateHash($info['algo'], $data, true) != $info['hash'] @@ -275,8 +597,8 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized $result[$key] = $data; } - // Don't check ttl after first iteration - $options['ttl'] = 0; + // TODO: Don't check ttl after first iteration + // $options['ttl'] = 0; } return $result; @@ -285,14 +607,7 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Test if an item exists. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -300,27 +615,20 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized * @triggers hasItem.post(PostEvent) * @triggers hasItem.exception(ExceptionEvent) */ - public function hasItem($key, array $options = array()) + public function hasItem($key) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::hasItem($key, $options); + return parent::hasItem($key); } /** * Test multiple items. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Array of found keys * @throws Exception\ExceptionInterface * @@ -328,46 +636,39 @@ public function hasItem($key, array $options = array()) * @triggers hasItems.post(PostEvent) * @triggers hasItems.exception(ExceptionEvent) */ - public function hasItems(array $keys, array $options = array()) + public function hasItems(array $keys) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::hasItems($keys, $options); + return parent::hasItems($keys); } /** * Internal method to test if an item exists. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { - $ttl = $normalizedOptions['ttl']; - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - - if (!file_exists($filespec . '.dat')) { + $file = $this->getFileSpec($normalizedKey) . '.dat'; + if (!file_exists($file)) { return false; } + $ttl = $this->getOptions()->getTtl(); if ($ttl) { ErrorHandler::start(); - $mtime = filemtime($filespec . '.dat'); + $mtime = filemtime($file); $error = ErrorHandler::stop(); if (!$mtime) { throw new Exception\RuntimeException( - "Error getting mtime of file '{$filespec}.dat'", 0, $error + "Error getting mtime of file '{$file}'", 0, $error ); } @@ -383,66 +684,61 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) * Get metadata * * @param string $key - * @param array $options * @return array|boolean Metadata on success, false on failure */ - public function getMetadata($key, array $options = array()) + public function getMetadata($key) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::getMetadata($key, $options); + return parent::getMetadata($key); } /** * Get metadatas * * @param array $keys - * @param array $options * @return array Associative array of keys and metadata */ public function getMetadatas(array $keys, array $options = array()) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getReadable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getReadable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::getMetadatas($keys, $options); + return parent::getMetadatas($keys); } /** * Get info by key * * @param string $normalizedKey - * @param array $normalizedOptions * @return array|boolean Metadata on success, false on failure */ - protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) + protected function internalGetMetadata(& $normalizedKey) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalHasItem($normalizedKey)) { return false; } - $baseOptions = $this->getOptions(); - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - - $metadata = $this->readInfoFile($filespec . '.ifo'); - if (!$metadata) { - $metadata = array(); - } + $options = $this->getOptions(); + $filespec = $this->getFileSpec($normalizedKey); + $file = $filespec . '.dat'; - $metadata['filespec'] = $filespec; - $metadata['mtime'] = filemtime($filespec . '.dat'); + $metadata = array( + 'filespec' => $filespec, + 'mtime' => filemtime($file) + ); - if (!$baseOptions->getNoCtime()) { - $metadata['ctime'] = filectime($filespec . '.dat'); + if (!$options->getNoCtime()) { + $metadata['ctime'] = filectime($file); } - if (!$baseOptions->getNoAtime()) { - $metadata['atime'] = fileatime($filespec . '.dat'); + if (!$options->getNoAtime()) { + $metadata['atime'] = fileatime($file); } return $metadata; @@ -451,64 +747,33 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti /** * Internal method to get multiple metadata * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface */ - protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetMetadatas(array & $normalizedKeys) { - $baseOptions = $this->getOptions(); - $result = array(); - - // Don't change arguments passed by reference - $keys = $normalizedKeys; - $options = $normalizedOptions; - - while ($keys) { - - // LOCK_NB if more than one items have to read - $nonBlocking = count($keys) > 1; - $wouldblock = null; - - foreach ($keys as $i => $key) { - if (!$this->internalHasItem($key, $options)) { - unset($keys[$i]); - continue; - } - - $filespec = $this->getFileSpec($key, $options); - - $metadata = $this->readInfoFile($filespec . '.ifo', $nonBlocking, $wouldblock); - if ($nonBlocking && $wouldblock) { - continue; - } elseif (!$metadata) { - $metadata = array(); - } + $options = $this->getOptions(); + $result = array(); - $metadata['filespec'] = $filespec; - $metadata['mtime'] = filemtime($filespec . '.dat'); + foreach ($normalizedKeys as $normalizedKey) { + $filespec = $this->getFileSpec($normalizedKey); + $file = $filespec . '.dat'; - if (!$baseOptions->getNoCtime()) { - $metadata['ctime'] = filectime($filespec . '.dat'); - } + $metadata = array( + 'filespec' => $filespec, + 'mtime' => filemtime($file), + ); - if (!$baseOptions->getNoAtime()) { - $metadata['atime'] = fileatime($filespec . '.dat'); - } + if (!$options->getNoCtime()) { + $metadata['ctime'] = filectime($file); + } - $result[$key] = $metadata; - unset($keys[$i]); + if (!$options->getNoAtime()) { + $metadata['atime'] = fileatime($file); } - // Don't check ttl after first iteration - $options['ttl'] = 0; + $result[$normalizedKey] = $metadata; } return $result; @@ -519,15 +784,8 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal /** * Store an item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -535,27 +793,19 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal * @triggers setItem.post(PostEvent) * @triggers setItem.exception(ExceptionEvent) */ - public function setItem($key, $value, array $options = array()) + public function setItem($key, $value) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - - return parent::setItem($key, $value, $options); + return parent::setItem($key, $value); } /** * Store multiple items. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param array $keyValuePairs - * @param array $options * @return array Array of not stored keys * @throws Exception\ExceptionInterface * @@ -563,28 +813,21 @@ public function setItem($key, $value, array $options = array()) * @triggers setItems.post(PostEvent) * @triggers setItems.exception(ExceptionEvent) */ - public function setItems(array $keyValuePairs, array $options = array()) + public function setItems(array $keyValuePairs) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::setItems($keyValuePairs, $options); + return parent::setItems($keyValuePairs); } /** * Add an item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -592,27 +835,20 @@ public function setItems(array $keyValuePairs, array $options = array()) * @triggers addItem.post(PostEvent) * @triggers addItem.exception(ExceptionEvent) */ - public function addItem($key, $value, array $options = array()) + public function addItem($key, $value) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::addItem($key, $value, $options); + return parent::addItem($key, $value); } /** * Add multiple items. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param array $keyValuePairs - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -620,28 +856,21 @@ public function addItem($key, $value, array $options = array()) * @triggers addItems.post(PostEvent) * @triggers addItems.exception(ExceptionEvent) */ - public function addItems(array $keyValuePairs, array $options = array()) + public function addItems(array $keyValuePairs) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::addItems($keyValuePairs, $options); + return parent::addItems($keyValuePairs); } /** * Replace an existing item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -649,27 +878,20 @@ public function addItems(array $keyValuePairs, array $options = array()) * @triggers replaceItem.post(PostEvent) * @triggers replaceItem.exception(ExceptionEvent) */ - public function replaceItem($key, $value, array $options = array()) + public function replaceItem($key, $value) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::replaceItem($key, $value, $options); + return parent::replaceItem($key, $value); } /** * Replace multiple existing items. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param array $keyValuePairs - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -677,56 +899,47 @@ public function replaceItem($key, $value, array $options = array()) * @triggers replaceItems.post(PostEvent) * @triggers replaceItems.exception(ExceptionEvent) */ - public function replaceItems(array $keyValuePairs, array $options = array()) + public function replaceItems(array $keyValuePairs) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::replaceItems($keyValuePairs, $options); + return parent::replaceItems($keyValuePairs); } /** * Internal method to store an item. * - * Options: - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalSetItem(& $normalizedKey, & $value) { - $baseOptions = $this->getOptions(); - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $options = $this->getOptions(); + $filespec = $this->getFileSpec($normalizedKey); $this->prepareDirectoryStructure($filespec); $info = null; - if ($baseOptions->getReadControl()) { - $info['hash'] = Utils::generateHash($baseOptions->getReadControlAlgo(), $value, true); - $info['algo'] = $baseOptions->getReadControlAlgo(); - } - if (isset($options['tags'])) { - $info['tags'] = $normalizedOptions['tags']; + if ($options->getReadControl()) { + $info['hash'] = Utils::generateHash($options->getReadControlAlgo(), $value, true); + $info['algo'] = $options->getReadControlAlgo(); } // write files try { // set umask for files - $oldUmask = umask($baseOptions->getFileUmask()); + $oldUmask = umask($options->getFileUmask()); $contents = array($filespec . '.dat' => & $value); if ($info) { $contents[$filespec . '.ifo'] = serialize($info); } else { $this->unlink($filespec . '.ifo'); + $this->unlink($filespec . '.tag'); } while ($contents) { @@ -746,7 +959,7 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz return true; - } catch (Exception $e) { + } catch (BaseException $e) { // reset umask on exception umask($oldUmask); throw $e; @@ -756,18 +969,11 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to store multiple items. * - * Options: - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalSetItems(array & $normalizedKeyValuePairs) { $baseOptions = $this->getOptions(); $oldUmask = null; @@ -775,7 +981,7 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n // create an associated array of files and contents to write $contents = array(); foreach ($normalizedKeyValuePairs as $key => & $value) { - $filespec = $this->getFileSpec($key, $normalizedOptions); + $filespec = $this->getFileSpec($key); $this->prepareDirectoryStructure($filespec); // *.dat file @@ -787,13 +993,11 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n $info['hash'] = Utils::generateHash($baseOptions->getReadControlAlgo(), $value, true); $info['algo'] = $baseOptions->getReadControlAlgo(); } - if (isset($normalizedOptions['tags'])) { - $info['tags'] = & $normalizedOptions['tags']; - } if ($info) { $contents[$filespec . '.ifo'] = serialize($info); } else { $this->unlink($filespec . '.ifo'); + $this->unlink($filespec . '.tag'); } } @@ -820,7 +1024,7 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n // return OK return array(); - } catch (Exception $e) { + } catch (BaseException $e) { // reset umask on exception umask($oldUmask); throw $e; @@ -833,76 +1037,55 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n * It uses the token received from getItem() to check if the item has * changed before overwriting it. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * - tags optional - * - An array of tags - * * @param mixed $token * @param string $key * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @see getItem() * @see setItem() */ - public function checkAndSetItem($token, $key, $value, array $options = array()) + public function checkAndSetItem($token, $key, $value) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::checkAndSetItem($token, $key, $value, $options); + return parent::checkAndSetItem($token, $key, $value); } /** * Internal method to set an item only if token matches * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param mixed $token * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface * @see getItem() * @see setItem() */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) + protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalHasItem($normalizedKey)) { return false; } // use filemtime + filesize as CAS token - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); - $check = filemtime($filespec . '.dat') . filesize($filespec . '.dat'); + $file = $this->getFileSpec($normalizedKey) . '.dat'; + $check = filemtime($file) . filesize($file); if ($token !== $check) { return false; } - return $this->internalSetItem($normalizedKey, $value, $normalizedOptions); + return $this->internalSetItem($normalizedKey, $value); } /** * Reset lifetime of an item * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -910,25 +1093,20 @@ protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, * @triggers touchItem.post(PostEvent) * @triggers touchItem.exception(ExceptionEvent) */ - public function touchItem($key, array $options = array()) + public function touchItem($key) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::touchItem($key, $options); + return parent::touchItem($key); } /** * Reset lifetime of multiple items. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Array of not updated keys * @throws Exception\ExceptionInterface * @@ -936,37 +1114,30 @@ public function touchItem($key, array $options = array()) * @triggers touchItems.post(PostEvent) * @triggers touchItems.exception(ExceptionEvent) */ - public function touchItems(array $keys, array $options = array()) + public function touchItems(array $keys) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::touchItems($keys, $options); + return parent::touchItems($keys); } /** * Internal method to reset lifetime of an item * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) + protected function internalTouchItem(& $normalizedKey) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalHasItem($normalizedKey)) { return false; } - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $filespec = $this->getFileSpec($normalizedKey); ErrorHandler::start(); $touch = touch($filespec . '.dat'); @@ -983,12 +1154,7 @@ protected function internalTouchItem(& $normalizedKey, array & $normalizedOption /** * Remove an item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $key - * @param array $options * @return boolean * @throws Exception\ExceptionInterface * @@ -996,25 +1162,20 @@ protected function internalTouchItem(& $normalizedKey, array & $normalizedOption * @triggers removeItem.post(PostEvent) * @triggers removeItem.exception(ExceptionEvent) */ - public function removeItem($key, array $options = array()) + public function removeItem($key) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::removeItem($key, $options); + return parent::removeItem($key); } /** * Remove multiple items. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param array $keys - * @param array $options * @return array Array of not removed keys * @throws Exception\ExceptionInterface * @@ -1022,177 +1183,36 @@ public function removeItem($key, array $options = array()) * @triggers removeItems.post(PostEvent) * @triggers removeItems.exception(ExceptionEvent) */ - public function removeItems(array $keys, array $options = array()) + public function removeItems(array $keys) { - $baseOptions = $this->getOptions(); - if ($baseOptions->getWritable() && $baseOptions->getClearStatCache()) { + $options = $this->getOptions(); + if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } - return parent::removeItems($keys, $options); + return parent::removeItems($keys); } /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) + protected function internalRemoveItem(& $normalizedKey) { - $filespec = $this->getFileSpec($normalizedKey, $normalizedOptions); + $filespec = $this->getFileSpec($normalizedKey); if (!file_exists($filespec . '.dat')) { return false; } else { $this->unlink($filespec . '.dat'); + $this->unlink($filespec . '.tag'); $this->unlink($filespec . '.ifo'); } return true; } - /* non-blocking */ - - /** - * internal method to find items. - * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalFind(& $normalizedMode, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - try { - $baseOptions = $this->getOptions(); - - $prefix = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator(); - $find = $baseOptions->getCacheDir() - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $baseOptions->getDirLevel()) - . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new GlobIterator($find); - - $this->stmtActive = true; - $this->stmtGlob = $glob; - $this->stmtMatch = $normalizedMode; - $this->stmtOptions = $normalizedOptions; - } catch (BaseException $e) { - throw new Exception\RuntimeException("new GlobIterator({$find}) failed", 0, $e); - } - - return true; - } - - /** - * Internal method to fetch the next item from result set - * - * @return array|boolean The next item or false - * @throws Exception\ExceptionInterface - */ - protected function internalFetch() - { - if (!$this->stmtActive) { - return false; - } - - if ($this->stmtGlob !== null) { - $result = $this->fetchByGlob(); - - if ($result === false) { - // clear statement - $this->stmtActive = false; - $this->stmtGlob = null; - $this->stmtMatch = null; - $this->stmtOptions = null; - } - } else { - $result = parent::internalFetch(); - } - - return $result; - } - - /* cleaning */ - - /** - * Internal method to clear items off all namespaces. - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - return $this->clearByPrefix('', $normalizedMode, $normalizedOptions); - } - - /** - * Clear items by namespace. - * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clear() - */ - protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) - { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); - return $this->clearByPrefix($prefix, $normalizedMode, $normalizedOptions); - } - - /** - * Internal method to optimize adapter storage. - * - * Options: - * - namespace - * - The namespace to use - * - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - */ - protected function internalOptimize(array & $normalizedOptions) - { - $baseOptions = $this->getOptions(); - if ($baseOptions->getDirLevel()) { - // removes only empty directories - $this->rmDir( - $baseOptions->getCacheDir(), - $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator() - ); - } - - return true; - } - /* status */ /** @@ -1232,15 +1252,11 @@ protected function internalGetCapabilities() 'supportedMetadata' => $metadata, 'maxTtl' => 0, 'staticTtl' => false, - 'tagging' => true, 'ttlPrecision' => 1, 'expiredRead' => true, 'maxKeyLength' => 251, // 255 - strlen(.dat | .ifo) 'namespaceIsPrefix' => true, 'namespaceSeparator' => $options->getNamespaceSeparator(), - 'iterable' => true, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, ) ); @@ -1278,227 +1294,8 @@ protected function internalGetCapabilities() return $this->capabilities; } - /** - * Internal method to get storage capacity. - * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetCapacity(array & $normalizedOptions) - { - return Utils::getDiskCapacity($this->getOptions()->getCacheDir()); - } - /* internal */ - /** - * Fetch by glob - * - * @return array|bool - */ - protected function fetchByGlob() - { - $options = $this->stmtOptions; - $mode = $this->stmtMatch; - - $prefix = $options['namespace'] . $this->getOptions()->getNamespaceSeparator(); - $prefixL = strlen($prefix); - - do { - try { - $valid = $this->stmtGlob->valid(); - } catch (\LogicException $e) { - // @link https://bugs.php.net/bug.php?id=55701 - // GlobIterator throws LogicException with message - // 'The parent constructor was not called: the object is in an invalid state' - $valid = false; - } - if (!$valid) { - return false; - } - - $item = array(); - $meta = null; - - $current = $this->stmtGlob->current(); - $this->stmtGlob->next(); - - $filename = $current->getFilename(); - if ($prefix !== '') { - if (substr($filename, 0, $prefixL) != $prefix) { - continue; - } - - // remove prefix and suffix (.dat) - $key = substr($filename, $prefixL, -4); - } else { - // remove suffix (.dat) - $key = substr($filename, 0, -4); - } - - // if MATCH_ALL mode do not check expired - if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { - $mtime = $current->getMTime(); - - // if MATCH_EXPIRED -> filter not expired items - if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ( time() < ($mtime + $options['ttl']) ) { - continue; - } - - // if MATCH_ACTIVE -> filter expired items - } else { - if ( time() >= ($mtime + $options['ttl']) ) { - continue; - } - } - } - - // check tags only if one of the tag matching mode is selected - if (($mode & 070) > 0) { - - $meta = $this->internalGetMetadata($key, $options); - - // if MATCH_TAGS mode -> check if all given tags available in current cache - if (($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - if (!isset($meta['tags']) || count(array_diff($options['tags'], $meta['tags'])) > 0) { - continue; - } - - // if MATCH_NO_TAGS mode -> check if no given tag available in current cache - } elseif( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - if (isset($meta['tags']) && count(array_diff($options['tags'], $meta['tags'])) != count($options['tags'])) { - continue; - } - - // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache - } elseif ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - if (!isset($meta['tags']) || count(array_diff($options['tags'], $meta['tags'])) == count($options['tags'])) { - continue; - } - - } - } - - foreach ($options['select'] as $select) { - if ($select == 'key') { - $item['key'] = $key; - } else if ($select == 'value') { - $item['value'] = $this->getFileContent($current->getPathname()); - } else if ($select != 'key') { - if ($meta === null) { - $meta = $this->internalGetMetadata($key, $options); - } - $item[$select] = isset($meta[$select]) ? $meta[$select] : null; - } - } - - return $item; - } while (true); - } - - /** - * Clear by prefix - * - * @param $prefix - * @param $mode - * @param array $opts - * @return bool - * @throws RuntimeException - */ - protected function clearByPrefix($prefix, $mode, array &$opts) - { - $baseOptions = $this->getOptions(); - if (!$baseOptions->getWritable()) { - return false; - } - - $ttl = $opts['ttl']; - - if ($baseOptions->getClearStatCache()) { - clearstatcache(); - } - - try { - $find = $baseOptions->getCacheDir() - . str_repeat(\DIRECTORY_SEPARATOR . $prefix . '*', $baseOptions->getDirLevel()) - . \DIRECTORY_SEPARATOR . $prefix . '*.dat'; - $glob = new GlobIterator($find); - } catch (BaseException $e) { - throw new Exception\RuntimeException('Instantiating GlobIterator failed', 0, $e); - } - - $time = time(); - - foreach ($glob as $entry) { - - // if MATCH_ALL mode do not check expired - if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { - - $mtime = $entry->getMTime(); - if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ( $time <= ($mtime + $ttl) ) { - continue; - } - - // if Zend_Cache::MATCH_ACTIVE mode selected do not remove expired data - } else { - if ( $time >= ($mtime + $ttl) ) { - continue; - } - } - } - - // remove file suffix (*.dat) - $pathnameSpec = substr($entry->getPathname(), 0, -4); - - //////////////////////////////////////// - // on this time all expire tests match - //////////////////////////////////////// - - // check tags only if one of the tag matching mode is selected - if (($mode & 070) > 0) { - - $info = $this->readInfoFile($pathnameSpec . '.ifo'); - - // if MATCH_TAGS mode -> check if all given tags available in current cache - if (($mode & self::MATCH_TAGS) == self::MATCH_TAGS ) { - if (!isset($info['tags']) - || count(array_diff($opts['tags'], $info['tags'])) > 0 - ) { - continue; - } - - // if MATCH_NO_TAGS mode -> check if no given tag available in current cache - } elseif(($mode & self::MATCH_NO_TAGS) == self::MATCH_NO_TAGS) { - if (isset($info['tags']) - && count(array_diff($opts['tags'], $info['tags'])) != count($opts['tags']) - ) { - continue; - } - - // if MATCH_ANY_TAGS mode -> check if any given tag available in current cache - } elseif ( ($mode & self::MATCH_ANY_TAGS) == self::MATCH_ANY_TAGS ) { - if (!isset($info['tags']) - || count(array_diff($opts['tags'], $info['tags'])) == count($opts['tags']) - ) { - continue; - } - } - } - - //////////////////////////////////////// - // on this time all tests match - //////////////////////////////////////// - - $this->unlink($pathnameSpec . '.dat'); // delete data file - $this->unlink($pathnameSpec . '.ifo'); // delete info file - } - - return true; - } - /** * Removes directories recursive by namespace * @@ -1537,16 +1334,14 @@ protected function rmDir($dir, $prefix) * Get file spec of the given key and namespace * * @param string $normalizedKey - * @param array $normalizedOptions * @return string */ - protected function getFileSpec($normalizedKey, array & $normalizedOptions) + protected function getFileSpec($normalizedKey) { - $baseOptions = $this->getOptions(); - $prefix = $normalizedOptions['namespace'] . $baseOptions->getNamespaceSeparator(); - - $path = $baseOptions->getCacheDir() . \DIRECTORY_SEPARATOR; - $level = $baseOptions->getDirLevel(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $path = $options->getCacheDir() . \DIRECTORY_SEPARATOR; + $level = $options->getDirLevel(); $fileSpecId = $path . $prefix . $normalizedKey . '/' . $level; if ($this->lastFileSpecId !== $fileSpecId) { diff --git a/src/Storage/Adapter/FilesystemIterator.php b/src/Storage/Adapter/FilesystemIterator.php new file mode 100644 index 000000000..b8e376199 --- /dev/null +++ b/src/Storage/Adapter/FilesystemIterator.php @@ -0,0 +1,194 @@ +storage = $storage; + $this->globIterator = new GlobIterator($path, GlobIterator::KEY_AS_FILENAME); + $this->prefix = $prefix; + $this->prefixLength = strlen($prefix); + } + + /** + * Get storage instance + * + * @return StorageInterface + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Get iterator mode + * + * @return int Value of IteratorInterface::CURRENT_AS_* + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set iterator mode + * + * @param int $mode + * @return ApcIterator Fluent interface + */ + public function setMode($mode) + { + $this->mode = (int) $mode; + return $this; + } + + /* Iterator */ + + /** + * Get current key, value or metadata. + * + * @return mixed + */ + public function current() + { + if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { + return $this; + } + + $key = $this->key(); + + if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { + return $this->storage->getItem($key); + } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { + return $this->storage->getMetadata($key); + } + + return $key; + } + + /** + * Get current key + * + * @return string + */ + public function key() + { + $filename = $this->globIterator->key(); + + // return without namespace prefix and file suffix + return substr($filename, $this->prefixLength, -4); + } + + /** + * Move forward to next element + * + * @return void + */ + public function next() + { + $this->globIterator->next(); + } + + /** + * Checks if current position is valid + * + * @return boolean + */ + public function valid() + { + try { + return $this->globIterator->valid(); + } catch (\LogicException $e) { + // @link https://bugs.php.net/bug.php?id=55701 + // GlobIterator throws LogicException with message + // 'The parent constructor was not called: the object is in an invalid state' + return false; + } + } + + /** + * Rewind the Iterator to the first element. + * + * @return void + */ + public function rewind() + { + return $this->globIterator->rewind(); + } +} diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index d69ca3bc1..0271bd216 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -88,15 +88,6 @@ class FilesystemOptions extends AdapterOptions */ protected $keyPattern = '/^[a-z0-9_\+\-]*$/Di'; - /** - * Overwrite default namespace pattern - * - * Defined in AdapterOptions. - * - * @var string - */ - protected $namespacePattern = '/^[a-z0-9_\+\-]*$/Di'; - /** * Namespace separator * diff --git a/src/Storage/Adapter/KeyListIterator.php b/src/Storage/Adapter/KeyListIterator.php new file mode 100644 index 000000000..12dc88fd6 --- /dev/null +++ b/src/Storage/Adapter/KeyListIterator.php @@ -0,0 +1,191 @@ +storage = $storage; + $this->keys = $keys; + $this->count = count($keys); + } + + /** + * Get storage instance + * + * @return StorageInterface + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Get iterator mode + * + * @return int Value of IteratorInterface::CURRENT_AS_* + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set iterator mode + * + * @param int $mode + * @return KeyListIterator Fluent interface + */ + public function setMode($mode) + { + $this->mode = (int) $mode; + return $this; + } + + /** + * Get current key, value or metadata. + * + * @return mixed + */ + public function current() + { + if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { + return $this; + } + + $key = $this->key(); + + if ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { + return $this->storage->getMetadata($key); + } elseif ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { + return $this->storage->getItem($key); + } + + return $key; + } + + /** + * Get current key + * + * @return string + */ + public function key() + { + return $this->keys[$this->position]; + } + + /** + * Checks if current position is valid + * + * @return boolean + */ + public function valid() + { + return $this->position < $this->count; + } + + /** + * Move forward to next element + * + * @return void + */ + public function next() + { + $this->position++; + } + + /** + * Rewind the Iterator to the first element. + * + * @return void + */ + public function rewind() + { + $this->position = 0; + } + + /** + * Count number of items + * + * @return int + */ + public function count() + { + return $this->count(); + } +} diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 94076c336..aa9aa718e 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -29,7 +29,10 @@ Zend\Cache\Exception, Zend\Cache\Storage\Event, Zend\Cache\Storage\CallbackEvent, - Zend\Cache\Storage\Capabilities; + Zend\Cache\Storage\Capabilities, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\AvailableSpaceCapableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @package Zend_Cache @@ -37,9 +40,10 @@ * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @todo Implement the find() method */ -class Memcached extends AbstractAdapter +class Memcached + extends AbstractAdapter + implements FlushableInterface, AvailableSpaceCapableInterface, TotalSpaceCapableInterface { /** * Major version of ext/memcached @@ -88,6 +92,7 @@ public function __construct($options = null) $this->memcached->setOption($k, $v); } } + $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options->getNamespace()); $servers = $options->getServers(); if (!$servers) { @@ -96,6 +101,8 @@ public function __construct($options = null) } $this->memcached->addServers($servers); + + // get notified on change options $memc = $this->memcached; $memcMV = static::$extMemcachedMajorVersion; @@ -112,6 +119,10 @@ public function __construct($options = null) } } + if (isset($params['namespace'])) { + $memc->setOption(MemcachedResource::OPT_PREFIX_KEY, $params['namespace']); + } + // TODO: update on change/add server(s) }); } @@ -148,32 +159,75 @@ public function getOptions() return $this->options; } + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + if (!$this->memcached->flush()) { + throw $this->getExceptionByResultCode($this->memcached->getResultCode()); + } + return true; + } + + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + $stats = $this->memcached->getStats(); + if ($stats === false) { + throw new Exception\RuntimeException($this->memcached->getResultMessage()); + } + + $mem = array_pop($stats); + return $mem['limit_maxbytes']; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $stats = $this->memcached->getStats(); + if ($stats === false) { + throw new Exception\RuntimeException($this->memcached->getResultMessage()); + } + + $mem = array_pop($stats); + return $mem['limit_maxbytes'] - $mem['bytes']; + } + /* reading */ /** * Internal method to get an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - // TODO: option to enable CAS feature - //if (array_key_exists('token', $normalizedOptions)) { + if (func_num_args() > 2) { $result = $this->memcached->get($normalizedKey, null, $casToken); - //} else { - // $result = $this->memcached->get($normalizedKey); - //} + } else { + $result = $this->memcached->get($normalizedKey); + } $success = true; if ($result === false || $result === null) { @@ -193,19 +247,12 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, /** * Internal method to get multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $result = $this->memcached->getMulti($normalizedKeys); if ($result === false) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); @@ -217,19 +264,12 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Internal method to test if an item exists. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $value = $this->memcached->get($normalizedKey); if ($value === false || $value === null) { $rsCode = $this->memcached->getResultCode(); @@ -248,19 +288,12 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) /** * Internal method to test multiple items. * - * Options: - * - namespace - * - The namespace to use - * - * @param array $keys - * @param array $options + * @param array $normalizedKeys * @return array Array of found keys * @throws Exception\ExceptionInterface */ - protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalHasItems(array & $normalizedKeys) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $result = $this->memcached->getMulti($normalizedKeys); if ($result === false) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); @@ -272,23 +305,12 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized /** * Get metadata of multiple items * - * Options: - * - namespace optional - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and metadata * @throws Exception\ExceptionInterface - * - * @triggers getMetadatas.pre(PreEvent) - * @triggers getMetadatas.post(PostEvent) - * @triggers getMetadatas.exception(ExceptionEvent) */ - protected function internalGetMetadatas(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetMetadatas(array & $normalizedKeys) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $result = $this->memcached->getMulti($normalizedKeys); if ($result === false) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); @@ -306,23 +328,14 @@ protected function internalGetMetadatas(array & $normalizedKeys, array & $normal /** * Internal method to store an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalSetItem(& $normalizedKey, & $value) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - $expiration = $this->expirationTime($normalizedOptions['ttl']); + $expiration = $this->expirationTime(); if (!$this->memcached->set($normalizedKey, $value, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -333,22 +346,13 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to store multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalSetItems(array & $normalizedKeyValuePairs) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - $expiration = $this->expirationTime($normalizedOptions['ttl']); + $expiration = $this->expirationTime(); if (!$this->memcached->setMulti($normalizedKeyValuePairs, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } @@ -359,23 +363,14 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n /** * Add an item. * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalAddItem(& $normalizedKey, & $value) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - $expiration = $this->expirationTime($normalizedOptions['ttl']); + $expiration = $this->expirationTime(); if (!$this->memcached->add($normalizedKey, $value, $expiration)) { if ($this->memcached->getResultCode() == MemcachedResource::RES_NOTSTORED) { return false; @@ -389,23 +384,14 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to replace an existing item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalReplaceItem(& $normalizedKey, & $value) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - $expiration = $this->expirationTime($normalizedOptions['ttl']); + $expiration = $this->expirationTime(); if (!$this->memcached->replace($normalizedKey, $value, $expiration)) { if ($this->memcached->getResultCode() == MemcachedResource::RES_NOTSTORED) { return false; @@ -419,28 +405,17 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm /** * Internal method to set an item only if token matches * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param mixed $token * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface * @see getItem() * @see setItem() */ - protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, array & $normalizedOptions) + protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - $expiration = $this->expirationTime($normalizedOptions['ttl']); + $expiration = $this->expirationTime(); $result = $this->memcached->cas($token, $normalizedKey, $value, $expiration); if ($result === false) { @@ -457,18 +432,12 @@ protected function internalCheckAndSetItem(& $token, & $normalizedKey, & $value, /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) + protected function internalRemoveItem(& $normalizedKey) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); $result = $this->memcached->delete($normalizedKey); if ($result === false) { @@ -486,23 +455,17 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio /** * Internal method to remove multiple items. * - * Options: - * - namespace - * - The namespace to use - * - * @param array $keys - * @param array $options + * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ - protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalRemoveItems(array & $normalizedKeys) { // support for removing multiple items at once has been added in ext/memcached-2.0.0 if (static::$extMemcachedMajorVersion < 2) { - return parent::internalRemoveItems($normalizedKeys, $normalizedOptions); + return parent::internalRemoveItems($normalizedKeys); } - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); $rsCodes = $this->memcached->deleteMulti($normalizedKeys); $missingKeys = array(); @@ -521,22 +484,13 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali /** * Internal method to increment an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalIncrementItem(& $normalizedKey, & $value) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $value = (int)$value; $newValue = $this->memcached->increment($normalizedKey, $value); @@ -545,9 +499,8 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no // initial value if ($rsCode == MemcachedResource::RES_NOTFOUND) { - $newValue = $value; - $expiration = $this->expirationTime($normalizedOptions['ttl']); - $this->memcached->add($normalizedKey, $newValue, $expiration); + $newValue = $value; + $this->memcached->add($normalizedKey, $newValue, $this->expirationTime()); $rsCode = $this->memcached->getResultCode(); } @@ -562,22 +515,13 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no /** * Internal method to decrement an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalDecrementItem(& $normalizedKey, & $value) { - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - $value = (int)$value; $newValue = $this->memcached->decrement($normalizedKey, $value); @@ -586,9 +530,8 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no // initial value if ($rsCode == MemcachedResource::RES_NOTFOUND) { - $newValue = -$value; - $expiration = $this->expirationTime($normalizedOptions['ttl']); - $this->memcached->add($normalizedKey, $newValue, $expiration); + $newValue = -$value; + $this->memcached->add($normalizedKey, $newValue, $this->expirationTime()); $rsCode = $this->memcached->getResultCode(); } @@ -600,154 +543,6 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no return $newValue; } - /* non-blocking */ - - /** - * Internal method to request multiple items. - * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * - select - * - An array of the information the returned item contains - * - callback optional - * - An result callback will be invoked for each item in the result set. - * - The first argument will be the item array. - * - The callback does not have to return anything. - * - * @param array $normalizedKeys - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalGetDelayed(array & $normalizedKeys, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - if (isset($normalizedOptions['callback']) && !is_callable($normalizedOptions['callback'], false)) { - throw new Exception\InvalidArgumentException('Invalid callback'); - } - - $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); - - // redirect callback - if (isset($normalizedOptions['callback'])) { - $cb = function (MemcachedResource $memc, array & $item) use (& $normalizedOptions) { - $select = & $normalizedOptions['select']; - - // handle selected key - if (!in_array('key', $select)) { - unset($item['key']); - } - - // handle selected value - if (!in_array('value', $select)) { - unset($item['value']); - } - - call_user_func($normalizedOptions['callback'], $item); - }; - - if (!$this->memcached->getDelayed($normalizedKeys, false, $cb)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - } else { - if (!$this->memcached->getDelayed($normalizedKeys)) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - $this->stmtActive = true; - $this->stmtOptions = & $normalizedOptions; - } - - return true; - } - - /** - * Internal method to fetch the next item from result set - * - * @return array|boolean The next item or false - * @throws Exception\ExceptionInterface - */ - protected function internalFetch() - { - if (!$this->stmtActive) { - return false; - } - - $result = $this->memcached->fetch(); - if (!empty($result)) { - $select = & $this->stmtOptions['select']; - - // handle selected key - if (!in_array('key', $select)) { - unset($result['key']); - } - - // handle selected value - if (!in_array('value', $select)) { - unset($result['value']); - } - - } else { - // clear stmt - $this->stmtActive = false; - $this->stmtOptions = null; - } - - return $result; - } - - /** - * Internal method to return all items of result set. - * - * @return array The result set as array containing all items - * @throws Exception\ExceptionInterface - * @see fetch() - */ - protected function internalFetchAll() - { - $result = $this->memcached->fetchAll(); - if ($result === false) { - throw new Exception\RuntimeException("Memcached::fetchAll() failed"); - } - - $select = $this->stmtOptions['select']; - foreach ($result as & $elem) { - if (!in_array('key', $select)) { - unset($elem['key']); - } - } - - return $result; - } - - /* cleaning */ - - /** - * Internal method to clear items off all namespaces. - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - if (!$this->memcached->flush()) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - return true; - } - /* status */ /** @@ -776,15 +571,11 @@ protected function internalGetCapabilities() 'supportedMetadata' => array(), 'maxTtl' => 0, 'staticTtl' => true, - 'tagging' => false, 'ttlPrecision' => 1, 'useRequestTime' => false, 'expiredRead' => false, 'maxKeyLength' => 255, 'namespaceIsPrefix' => true, - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => false, ) ); } @@ -792,27 +583,6 @@ protected function internalGetCapabilities() return $this->capabilities; } - /** - * Internal method to get storage capacity. - * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetCapacity(array & $normalizedOptions) - { - $stats = $this->memcached->getStats(); - if ($stats === false) { - throw $this->getExceptionByResultCode($this->memcached->getResultCode()); - } - - $mem = array_pop($stats); - return array( - 'free' => $mem['limit_maxbytes'] - $mem['bytes'], - 'total' => $mem['limit_maxbytes'], - ); - } - /* internal */ /** @@ -827,11 +597,11 @@ protected function internalGetCapacity(array & $normalizedOptions) * expiration value is larger than that, the server will consider it to be * real Unix time value rather than an offset from current time. * - * @param int $ttl * @return int */ - protected function expirationTime($ttl) + protected function expirationTime() { + $ttl = $this->getOptions()->getTtl(); if ($ttl > 2592000) { return time() + $ttl; } diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index ca916e766..b69756b67 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -25,7 +25,13 @@ stdClass, Zend\Cache\Exception, Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\Adapter\MemoryOptions, + Zend\Cache\Storage\ClearExpiredInterface, + Zend\Cache\Storage\ClearByPrefixInterface, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\IterableInterface, + Zend\Cache\Storage\TagableInterface, + Zend\Cache\Storage\AvailableSpaceCapableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface, Zend\Cache\Utils; /** @@ -35,7 +41,10 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Memory extends AbstractAdapter +class Memory + extends AbstractAdapter + implements ClearExpiredInterface, ClearByPrefixInterface, FlushableInterface, TagableInterface, + IterableInterface, AvailableSpaceCapableInterface, TotalSpaceCapableInterface { /** * Data Array @@ -46,7 +55,7 @@ class Memory extends AbstractAdapter * => array( * 0 => * 1 => - * 2 => + * ['tags' => ] * ) * ) * ) @@ -85,31 +94,220 @@ public function getOptions() return $this->options; } + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + return $this->getOptions()->getMemoryLimit(); + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $total = $this->getOptions()->getMemoryLimit(); + $avail = $total - (float) memory_get_usage(true); + return ($avail > 0) ? $avail : 0; + } + + /* IterableInterface */ + + /** + * Get the storage iterator + * + * @return MemoryIterator + */ + public function getIterator() + { + $ns = $this->getOptions()->getNamespace(); + $keys = array(); + + if (isset($this->data[$ns])) { + foreach ($this->data[$ns] as $key => & $tmp) { + if ($this->internalHasItem($key)) { + $keys[] = $key; + } + } + } + + return new KeyListIterator($this, $keys); + } + + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + $this->data = array(); + return true; + } + + /* ClearExpiredInterface */ + + /** + * Remove expired items + * + * @return boolean + */ + public function clearExpired() + { + $ttl = $this->getOptions()->getTtl(); + if ($ttl <= 0) { + return true; + } + + $ns = $this->getOptions()->getNamespace(); + if (!isset($this->data[$ns])) { + return true; + } + + $data = & $this->data[$ns]; + foreach ($data as $key => & $item) { + if (microtime(true) >= $data[$key][1] + $ttl) { + unset($data[$key]); + } + } + + return true; + } + + /* ClearByPrefixInterface */ + + /** + * Remove items matching given prefix + * + * @param string $prefix + * @return boolean + */ + public function clearByPrefix($prefix) + { + $ns = $this->getOptions()->getNamespace(); + if (!isset($this->data[$ns])) { + return true; + } + + $prefixL = strlen($prefix); + $data = & $this->data[$ns]; + foreach ($data as $key => & $item) { + if (substr($key, 0, $prefixL) === $prefix) { + unset($data[$key]); + } + } + + return true; + } + + /* TagableInterface */ + + /** + * Set tags to an item by given key. + * An empty array will remove all tags. + * + * @param string $key + * @param string[] $tags + * @return boolean + */ + public function setTags($key, array $tags) + { + $ns = $this->getOptions()->getNamespace(); + if (!$this->data[$ns]) { + return false; + } + + $data = & $this->data[$ns]; + if (isset($data[$key])) { + $data[$key]['tags'] = $tags; + return true; + } + + return false; + } + + /** + * Get tags of an item by given key + * + * @param string $key + * @return string[]|FALSE + */ + public function getTags($key) + { + $ns = $this->getOptions()->getNamespace(); + if (!$this->data[$ns]) { + return false; + } + + $data = & $this->data[$ns]; + if (!isset($data[$key])) { + return false; + } + + return isset($data[$key]['tags']) ? $data[$key]['tags'] : array(); + } + + /** + * Remove items matching given tags. + * + * If $disjunction only one of the given tags must match + * else all given tags must match. + * + * @param string[] $tags + * @param boolean $disjunction + * @return boolean + */ + public function clearByTags(array $tags, $disjunction = false) + { + $ns = $this->getOptions()->getNamespace(); + if (!$this->data[$ns]) { + return true; + } + + $tagCount = count($tags); + $data = & $this->data[$ns]; + foreach ($data as $key => & $item) { + if (isset($item['tags'])) { + $diff = array_diff($tags, $item['tags']); + if (($disjunction && count($diff) < $tagCount) || (!$disjunction && !$diff)) { + unset($data[$key]); + } + } + } + + return true; + } + /* reading */ /** * Internal method to get an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) { - $ns = $normalizedOptions['namespace']; + $options = $this->getOptions(); + $ns = $options->getNamespace(); $success = isset($this->data[$ns][$normalizedKey]); if ($success) { $data = & $this->data[$ns][$normalizedKey]; - $ttl = $normalizedOptions['ttl']; + $ttl = $options->getTtl(); if ($ttl && microtime(true) >= ($data[1] + $ttl) ) { $success = false; } @@ -126,31 +324,26 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, /** * Internal method to get multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { - $ns = $normalizedOptions['namespace']; + $options = $this->getOptions(); + $ns = $options->getNamespace(); if (!isset($this->data[$ns])) { return array(); } $data = & $this->data[$ns]; - $ttl = $normalizedOptions['ttl']; + $ttl = $options->getTtl(); + $now = microtime(true); $result = array(); foreach ($normalizedKeys as $normalizedKey) { if (isset($data[$normalizedKey])) { - if (!$ttl || microtime(true) < ($data[$normalizedKey][1] + $ttl) ) { + if (!$ttl || $now < ($data[$normalizedKey][1] + $ttl) ) { $result[$normalizedKey] = $data[$normalizedKey][0]; } } @@ -162,26 +355,21 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Internal method to test if an item exists. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { - $ns = $normalizedOptions['namespace']; + $options = $this->getOptions(); + $ns = $options->getNamespace(); if (!isset($this->data[$ns][$normalizedKey])) { return false; } // check if expired - $ttl = $normalizedOptions['ttl']; + $ttl = $options->getTtl(); if ($ttl && microtime(true) >= ($this->data[$ns][$normalizedKey][1] + $ttl) ) { return false; } @@ -192,31 +380,26 @@ protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) /** * Internal method to test multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $keys - * @param array $options * @return array Array of found keys * @throws Exception\ExceptionInterface */ - protected function internalHasItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalHasItems(array & $normalizedKeys) { - $ns = $normalizedOptions['namespace']; + $options = $this->getOptions(); + $ns = $options->getNamespace(); if (!isset($this->data[$ns])) { return array(); } $data = & $this->data[$ns]; - $ttl = $normalizedOptions['ttl']; + $ttl = $options->getTtl(); + $now = microtime(true); $result = array(); foreach ($normalizedKeys as $normalizedKey) { if (isset($data[$normalizedKey])) { - if (!$ttl || microtime(true) < ($data[$normalizedKey][1] + $ttl) ) { + if (!$ttl || $now < ($data[$normalizedKey][1] + $ttl) ) { $result[] = $normalizedKey; } } @@ -228,14 +411,7 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized /** * Get metadata of an item. * - * Options: - * - ttl optional - * - The time-to-life (Default: ttl of object) - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $normalizedKey - * @param array $normalizedOptions * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface * @@ -243,16 +419,15 @@ protected function internalHasItems(array & $normalizedKeys, array & $normalized * @triggers getMetadata.post(PostEvent) * @triggers getMetadata.exception(ExceptionEvent) */ - protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) + protected function internalGetMetadata(& $normalizedKey) { - if (!$this->internalHasItem($normalizedKey, $normalizedOptions)) { + if (!$this->internalHasItem($normalizedKey)) { return false; } - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); return array( 'mtime' => $this->data[$ns][$normalizedKey][1], - 'tags' => $this->data[$ns][$normalizedKey][2], ); } @@ -261,29 +436,24 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti /** * Internal method to store an item. * - * Options: - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalSetItem(& $normalizedKey, & $value) { - if (!$this->hasFreeCapacity()) { - $memoryLimit = $this->getOptions()->getMemoryLimit(); - throw new Exception\OutOfCapacityException( + $options = $this->getOptions(); + + if (!$this->hasAvailableSpace()) { + $memoryLimit = $options->getMemoryLimit(); + throw new Exception\OutOfSpaceException( "Memory usage exceeds limit ({$memoryLimit})." ); } - $ns = $normalizedOptions['namespace']; - $this->data[$ns][$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); + $ns = $options->getNamespace(); + $this->data[$ns][$normalizedKey] = array($value, microtime(true)); return true; } @@ -291,34 +461,30 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to store multiple items. * - * Options: - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalSetItems(array & $normalizedKeyValuePairs) { - if (!$this->hasFreeCapacity()) { - $memoryLimit = $this->getOptions()->getMemoryLimit(); - throw new Exception\OutOfCapacityException( - 'Memory usage exceeds limit ({$memoryLimit}).' + $options = $this->getOptions(); + + if (!$this->hasAvailableSpace()) { + $memoryLimit = $options->getMemoryLimit(); + throw new Exception\OutOfSpaceException( + "Memory usage exceeds limit ({$memoryLimit})." ); } - $ns = $normalizedOptions['namespace']; + $ns = $options->getNamespace(); if (!isset($this->data[$ns])) { $this->data[$ns] = array(); } $data = & $this->data[$ns]; + $now = microtime(true); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { - $data[$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); + $data[$normalizedKey] = array($value, $now); } return array(); @@ -327,60 +493,50 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n /** * Add an item. * - * Options: - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalAddItem(& $normalizedKey, & $value) { - if (!$this->hasFreeCapacity()) { - $memoryLimit = $this->getOptions()->getMemoryLimit(); - throw new Exception\OutOfCapacityException( + $options = $this->getOptions(); + + if (!$this->hasAvailableSpace()) { + $memoryLimit = $options->getMemoryLimit(); + throw new Exception\OutOfSpaceException( "Memory usage exceeds limit ({$memoryLimit})." ); } - $ns = $normalizedOptions['namespace']; + $ns = $options->getNamespace(); if (isset($this->data[$ns][$normalizedKey])) { return false; } - $this->data[$ns][$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); + $this->data[$ns][$normalizedKey] = array($value, microtime(true)); return true; } /** * Internal method to add multiple items. * - * Options: - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalAddItems(array & $normalizedKeyValuePairs) { - if (!$this->hasFreeCapacity()) { - $memoryLimit = $this->getOptions()->getMemoryLimit(); - throw new Exception\OutOfCapacityException( - 'Memory usage exceeds limit ({$memoryLimit}).' + $options = $this->getOptions(); + + if (!$this->hasAvailableSpace()) { + $memoryLimit = $options->getMemoryLimit(); + throw new Exception\OutOfSpaceException( + "Memory usage exceeds limit ({$memoryLimit})." ); } - $ns = $normalizedOptions['namespace']; + $ns = $options->getNamespace(); if (!isset($this->data[$ns])) { $this->data[$ns] = array(); } @@ -392,7 +548,7 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n if (isset($data[$normalizedKey])) { $result[] = $normalizedKey; } else { - $data[$normalizedKey] = array($value, $now, $normalizedOptions['tags']); + $data[$normalizedKey] = array($value, $now); } } @@ -402,27 +558,18 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n /** * Internal method to replace an existing item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalReplaceItem(& $normalizedKey, & $value) { - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); if (!isset($this->data[$ns][$normalizedKey])) { return false; } - $this->data[$ns][$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); + $this->data[$ns][$normalizedKey] = array($value, microtime(true)); return true; } @@ -430,22 +577,13 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm /** * Internal method to replace multiple existing items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - An array of tags - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalReplaceItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalReplaceItems(array & $normalizedKeyValuePairs) { - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); if (!isset($this->data[$ns])) { return array_keys($normalizedKeyValuePairs); } @@ -456,7 +594,7 @@ protected function internalReplaceItems(array & $normalizedKeyValuePairs, array if (!isset($data[$normalizedKey])) { $result[] = $normalizedKey; } else { - $data[$normalizedKey] = array($value, microtime(true), $normalizedOptions['tags']); + $data[$normalizedKey] = array($value, microtime(true)); } } @@ -466,18 +604,13 @@ protected function internalReplaceItems(array & $normalizedKeyValuePairs, array /** * Internal method to reset lifetime of an item * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalTouchItem(& $normalizedKey, array & $normalizedOptions) + protected function internalTouchItem(& $normalizedKey) { - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); if (!isset($this->data[$ns][$normalizedKey])) { return false; @@ -490,18 +623,13 @@ protected function internalTouchItem(& $normalizedKey, array & $normalizedOption /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) + protected function internalRemoveItem(& $normalizedKey) { - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); if (!isset($this->data[$ns][$normalizedKey])) { return false; } @@ -519,21 +647,14 @@ protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptio /** * Internal method to increment an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalIncrementItem(& $normalizedKey, & $value) { - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); $data = & $this->data[$ns]; if (isset($data[$normalizedKey])) { $data[$normalizedKey][0]+= $value; @@ -542,7 +663,7 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no } else { // initial value $newValue = $value; - $data[$normalizedKey] = array($newValue, microtime(true), null); + $data[$normalizedKey] = array($newValue, microtime(true)); } return $newValue; @@ -551,21 +672,14 @@ protected function internalIncrementItem(& $normalizedKey, & $value, array & $no /** * Internal method to decrement an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalDecrementItem(& $normalizedKey, & $value) { - $ns = $normalizedOptions['namespace']; + $ns = $this->getOptions()->getNamespace(); $data = & $this->data[$ns]; if (isset($data[$normalizedKey])) { $data[$normalizedKey][0]-= $value; @@ -574,203 +688,12 @@ protected function internalDecrementItem(& $normalizedKey, & $value, array & $no } else { // initial value $newValue = -$value; - $data[$normalizedKey] = array($newValue, microtime(true), null); + $data[$normalizedKey] = array($newValue, microtime(true)); } return $newValue; } - /* find */ - - /** - * internal method to find items. - * - * Options: - * - ttl - * - The time-to-live - * - namespace - * - The namespace to use - * - tags - * - Tags to search for used with matching modes of - * Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see fetch() - * @see fetchAll() - */ - protected function internalFind(& $normalizedMode, array & $normalizedOptions) - { - if ($this->stmtActive) { - throw new Exception\RuntimeException('Statement already in use'); - } - - $tags = & $normalizedOptions['tags']; - $emptyTags = $keys = array(); - foreach ($this->data[ $normalizedOptions['namespace'] ] as $key => &$item) { - - // compare expired / active - if (($normalizedMode & self::MATCH_ALL) != self::MATCH_ALL) { - - // if MATCH_EXPIRED -> filter active items - if (($normalizedMode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($this->internalHasItem($key, $normalizedOptions)) { - continue; - } - - // if MATCH_ACTIVE -> filter expired items - } else { - if (!$this->internalHasItem($key, $normalizedOptions)) { - continue; - } - } - } - - // compare tags - if ($tags !== null) { - $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; - - if ( ($normalizedMode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); - } elseif ( ($normalizedMode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - $matched = (count(array_diff($tags, $tagsStored)) == 0); - } - - // negate - if ( ($normalizedMode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - $matched = !$matched; - } - - if (!$matched) { - continue; - } - } - - $keys[] = $key; - } - - // don't check expiry on fetch - $normalizedOptions['ttl'] = 0; - - $this->stmtKeys = $keys; - $this->stmtOptions = $normalizedOptions; - $this->stmtActive = true; - - return true; - } - - /** - * Internal method to fetch the next item from result set - * - * @return array|boolean The next item or false - * @throws Exception\ExceptionInterface - */ - protected function internalFetch() - { - if (!$this->stmtActive) { - return false; - } - - $options = & $this->stmtOptions; - - // get the next valid item - do { - $key = array_shift($this->stmtKeys); - if ($key === null) { - break; - } - - if (!$this->internalHasItem($key, $options)) { - continue; - } - - break; - } while (true); - - // free statement after last item - if (!$key) { - $this->stmtActive = false; - $this->stmtKeys = null; - $this->stmtOptions = null; - - return false; - } - - $ref = & $this->data[ $options['namespace'] ][$key]; - $result = array(); - foreach ($options['select'] as $select) { - if ($select == 'key') { - $result['key'] = $key; - } elseif ($select == 'value') { - $result['value'] = $ref[0]; - } elseif ($select == 'mtime') { - $result['mtime'] = $ref[1]; - } elseif ($select == 'tags') { - $result['tags'] = $ref[2]; - } else { - $result[$select] = null; - } - } - - return $result; - } - - /* cleaning */ - - /** - * Internal method to clear items off all namespaces. - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - if (!$normalizedOptions['tags'] && ($normalizedMode & self::MATCH_ALL) == self::MATCH_ALL) { - $this->data = array(); - } else { - foreach ($this->data as & $data) { - $this->clearNamespacedDataArray($data, $normalizedMode, $normalizedOptions); - } - } - - return true; - } - - /** - * Clear items by namespace. - * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - tags - * - Tags to search for used with matching modes of Adapter::MATCH_TAGS_* - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clear() - */ - protected function internalClearByNamespace(& $normalizedMode, array & $normalizedOptions) - { - if (isset($this->data[ $normalizedOptions['namespace'] ])) { - if (!$normalizedOptions['tags'] && ($normalizedMode & self::MATCH_ALL) == self::MATCH_ALL) { - unset($this->data[ $normalizedOptions['namespace'] ]); - } else { - $this->clearNamespacedDataArray($this->data[ $normalizedOptions['namespace'] ], $normalizedMode, $normalizedOptions); - } - } - - return true; - } - /* status */ /** @@ -796,21 +719,14 @@ protected function internalGetCapabilities() 'object' => true, 'resource' => true, ), - 'supportedMetadata' => array( - 'mtime', - 'tags', - ), + 'supportedMetadata' => array('mtime'), 'maxTtl' => PHP_INT_MAX, 'staticTtl' => false, - 'tagging' => true, 'ttlPrecision' => 0.05, 'expiredRead' => true, 'maxKeyLength' => 0, 'namespaceIsPrefix' => false, 'namespaceSeparator' => '', - 'iterable' => true, - 'clearAllNamespaces' => true, - 'clearByNamespace' => true, ) ); } @@ -818,35 +734,14 @@ protected function internalGetCapabilities() return $this->capabilities; } - /** - * Internal method to get storage capacity. - * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetCapacity(array & $normalizedOptions) - { - $total = $this->getOptions()->getMemoryLimit(); - $free = $total - (float) memory_get_usage(true); - return array( - 'total' => $total, - 'free' => ($free >= 0) ? $free : 0, - ); - } - /* internal */ /** - * Has the memory adapter storage free capacity - * to store items - * - * Similar logic as getCapacity() but without triggering - * events and returns boolean. + * Has space available to store items? * * @return boolean */ - protected function hasFreeCapacity() + protected function hasAvailableSpace() { $total = $this->getOptions()->getMemoryLimit(); @@ -855,67 +750,7 @@ protected function hasFreeCapacity() return true; } - $free = $total - (float) memory_get_usage(true); + $free = $total - (float) memory_get_usage(true); return ($free > 0); } - - /** - * Internal method to run a clear command - * on a given data array which doesn't contain namespaces. - * - * Options: - * - ttl required - * - tags required - * - * @param array $data - * @param int $mode - * @param array $options - */ - protected function clearNamespacedDataArray(array &$data, $mode, array &$options) - { - $tags = &$options['tags']; - $time = microtime(true); - $ttl = $options['ttl']; - - $emptyTags = $keys = array(); - foreach ($data as $key => &$item) { - - // compare expired / active - if (($mode & self::MATCH_ALL) != self::MATCH_ALL) { - - // if MATCH_EXPIRED mode selected don't match active items - if (($mode & self::MATCH_EXPIRED) == self::MATCH_EXPIRED) { - if ($ttl == 0 || $time <= ($item[1]+$ttl) ) { - continue; - } - - // if MATCH_ACTIVE mode selected don't match expired items - } elseif ($ttl > 0 && $time >= ($item[1]+$ttl)) { - continue; - } - } - - // compare tags - if ($tags !== null) { - $tagsStored = isset($item[2]) ? $item[2] : $emptyTags; - - if ( ($mode & self::MATCH_TAGS_OR) == self::MATCH_TAGS_OR ) { - $matched = (count(array_diff($tags, $tagsStored)) != count($tags)); - } elseif ( ($mode & self::MATCH_TAGS_AND) == self::MATCH_TAGS_AND ) { - $matched = (count(array_diff($tags, $tagsStored)) == 0); - } - - // negate - if ( ($mode & self::MATCH_TAGS_NEGATE) == self::MATCH_TAGS_NEGATE ) { - $matched = !$matched; - } - - if (!$matched) { - continue; - } - } - - unset($data[$key]); - } - } } diff --git a/src/Storage/Adapter/MemoryOptions.php b/src/Storage/Adapter/MemoryOptions.php index 777ba2b04..b9356e2a1 100644 --- a/src/Storage/Adapter/MemoryOptions.php +++ b/src/Storage/Adapter/MemoryOptions.php @@ -46,7 +46,7 @@ class MemoryOptions extends AdapterOptions * Set memory limit * * - Bytes of less or equal 0 will disable the memory limit - * - If the used memory of PHP exceeds this limit an OutOfCapacityException + * - If the used memory of PHP exceeds this limit an OutOfSpaceException * will be thrown. * * @param int $bytes @@ -55,6 +55,15 @@ class MemoryOptions extends AdapterOptions public function setMemoryLimit($bytes) { $bytes = (int) $bytes; + + // use PHP's memory limit if possible + if ($bytes <= 0) { + $bytes = Utils::bytesFromString(ini_get('memory_limit')); + if ($bytes <= 0) { + $bytes = 0; + } + } + $this->triggerOptionEvent('memory_limit', $bytes); $this->memoryLimit = $bytes; return $this; @@ -63,7 +72,7 @@ public function setMemoryLimit($bytes) /** * Get memory limit * - * If the used memory of PHP exceeds this limit an OutOfCapacityException + * If the used memory of PHP exceeds this limit an OutOfSpaceException * will be thrown. * * @return int @@ -71,6 +80,7 @@ public function setMemoryLimit($bytes) public function getMemoryLimit() { if ($this->memoryLimit === null) { + // By default use half of PHP's memory limit if possible $memoryLimit = Utils::bytesFromString(ini_get('memory_limit')); if ($memoryLimit >= 0) { $this->memoryLimit = floor($memoryLimit / 2); diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 8ac4ab37a..1704519ed 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -24,7 +24,10 @@ use ArrayObject, stdClass, Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities; + Zend\Cache\Storage\Capabilities, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\AvailableSpaceCapableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @package Zend_Cache @@ -32,16 +35,11 @@ * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License - * @todo Implement the find() method */ -class WinCache extends AbstractAdapter +class WinCache + extends AbstractAdapter + implements FlushableInterface, AvailableSpaceCapableInterface, TotalSpaceCapableInterface { - /** - * The used namespace separator - * - * @var string - */ - protected $namespaceSeparator = ':'; /** * Constructor @@ -102,27 +100,59 @@ public function getOptions() return $this->options; } + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + $mem = wincache_ucache_meminfo(); + return $mem['memory_total']; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $mem = wincache_ucache_meminfo(); + return $mem['memory_free']; + } + + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + return wincache_ucache_clear(); + } + /* reading */ /** * Internal method to get an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @param boolean $success * @param mixed $casToken * @return mixed Data on success, null on failure * @throws Exception\ExceptionInterface */ - protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, & $success = null, & $casToken = null) + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKey = $prefix . $normalizedKey; $result = wincache_ucache_get($internalKey, $success); @@ -136,18 +166,14 @@ protected function internalGetItem(& $normalizedKey, array & $normalizedOptions, /** * Internal method to get multiple items. * - * Options: - * - namespace - * - The namespace to use - * * @param array $normalizedKeys - * @param array $normalizedOptions * @return array Associative array of keys and values * @throws Exception\ExceptionInterface */ - protected function internalGetItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalGetItems(array & $normalizedKeys) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { $internalKeys[] = $prefix . $normalizedKey; @@ -159,7 +185,7 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized $prefixL = strlen($prefix); $result = array(); foreach ($fetch as $internalKey => & $value) { - $result[ substr($internalKey, $prefixL) ] = $value; + $result[ substr($internalKey, $prefixL) ] = & $value; } return $result; @@ -168,40 +194,29 @@ protected function internalGetItems(array & $normalizedKeys, array & $normalized /** * Internal method to test if an item exists. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalHasItem(& $normalizedKey, array & $normalizedOptions) + protected function internalHasItem(& $normalizedKey) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); return wincache_ucache_exists($prefix . $normalizedKey); } /** * Get metadata of an item. * - * Options: - * - namespace optional - * - The namespace to use (Default: namespace of object) - * * @param string $normalizedKey - * @param array $normalizedOptions * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface - * - * @triggers getMetadata.pre(PreEvent) - * @triggers getMetadata.post(PostEvent) - * @triggers getMetadata.exception(ExceptionEvent) */ - protected function internalGetMetadata(& $normalizedKey, array & $normalizedOptions) + protected function internalGetMetadata(& $normalizedKey) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; $info = wincache_ucache_info(true, $internalKey); if (isset($info['ucache_entries'][1])) { @@ -218,25 +233,22 @@ protected function internalGetMetadata(& $normalizedKey, array & $normalizedOpti /** * Internal method to store an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalSetItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalSetItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - if (!wincache_ucache_set($internalKey, $value, $normalizedOptions['ttl'])) { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $ttl = $options->getTtl(); + + if (!wincache_ucache_set($internalKey, $value, $ttl)) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "wincache_ucache_set('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + "wincache_ucache_set('{$internalKey}', <{$type}>, {$ttl}) failed" ); } @@ -246,20 +258,14 @@ protected function internalSetItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to store multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalSetItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalSetItems(array & $normalizedKeyValuePairs) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $prefixL = strlen($prefix); $internalKeyValuePairs = array(); @@ -268,7 +274,7 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n $internalKeyValuePairs[$internalKey] = $value; } - $result = wincache_ucache_set($internalKeyValuePairs, null, $normalizedOptions['ttl']); + $result = wincache_ucache_set($internalKeyValuePairs, null, $options->getTtl()); // remove key prefic foreach ($result as & $key) { @@ -281,25 +287,22 @@ protected function internalSetItems(array & $normalizedKeyValuePairs, array & $n /** * Add an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * - * @param string $key + * @param string $normalizedKey * @param mixed $value - * @param array $options * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalAddItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalAddItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; - if (!wincache_ucache_add($internalKey, $value, $normalizedOptions['ttl'])) { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + $ttl = $options->getTtl(); + + if (!wincache_ucache_add($internalKey, $value, $ttl)) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "wincache_ucache_add('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + "wincache_ucache_add('{$internalKey}', <{$type}>, {$ttl}) failed" ); } @@ -309,27 +312,23 @@ protected function internalAddItem(& $normalizedKey, & $value, array & $normaliz /** * Internal method to add multiple items. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ - protected function internalAddItems(array & $normalizedKeyValuePairs, array & $normalizedOptions) + protected function internalAddItems(array & $normalizedKeyValuePairs) { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $prefixL = strlen($prefix); + $internalKeyValuePairs = array(); - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); foreach ($normalizedKeyValuePairs as $normalizedKey => $value) { $internalKey = $prefix . $normalizedKey; $internalKeyValuePairs[$internalKey] = $value; } - $result = wincache_ucache_add($internalKeyValuePairs, null, $normalizedOptions['ttl']); + $result = wincache_ucache_add($internalKeyValuePairs, null, $options->getTtl()); // remove key prefic foreach ($result as & $key) { @@ -342,29 +341,25 @@ protected function internalAddItems(array & $normalizedKeyValuePairs, array & $n /** * Internal method to replace an existing item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param mixed $value - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalReplaceItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalReplaceItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; if (!wincache_ucache_exists($internalKey)) { return false; } - if (!wincache_ucache_set($internalKey, $value, $normalizedOptions['ttl'])) { + $ttl = $options->getTtl(); + if (!wincache_ucache_set($internalKey, $value, $ttl)) { $type = is_object($value) ? get_class($value) : gettype($value); throw new Exception\RuntimeException( - "wincache_ucache_set('{$internalKey}', <{$type}>, {$normalizedOptions['ttl']}) failed" + "wincache_ucache_set('{$internalKey}', <{$type}>, {$ttl}) failed" ); } @@ -374,36 +369,29 @@ protected function internalReplaceItem(& $normalizedKey, & $value, array & $norm /** * Internal method to remove an item. * - * Options: - * - namespace - * - The namespace to use - * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ - protected function internalRemoveItem(& $normalizedKey, array & $normalizedOptions) + protected function internalRemoveItem(& $normalizedKey) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; return wincache_ucache_delete($internalKey); } /** * Internal method to remove multiple items. * - * Options: - * - namespace - * - The namespace to use - * - * @param array $keys - * @param array $options + * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ - protected function internalRemoveItems(array & $normalizedKeys, array & $normalizedOptions) + protected function internalRemoveItems(array & $normalizedKeys) { - $prefix = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator(); + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKeys = array(); foreach ($normalizedKeys as $normalizedKey) { @@ -427,65 +415,35 @@ protected function internalRemoveItems(array & $normalizedKeys, array & $normali /** * Internal method to increment an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalIncrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalIncrementItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; return wincache_ucache_inc($internalKey, (int)$value); } /** * Internal method to decrement an item. * - * Options: - * - ttl - * - The time-to-life - * - namespace - * - The namespace to use - * * @param string $normalizedKey * @param int $value - * @param array $normalizedOptions * @return int|boolean The new value on success, false on failure * @throws Exception\ExceptionInterface */ - protected function internalDecrementItem(& $normalizedKey, & $value, array & $normalizedOptions) + protected function internalDecrementItem(& $normalizedKey, & $value) { - $internalKey = $normalizedOptions['namespace'] . $this->getOptions()->getNamespaceSeparator() . $normalizedKey; + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; return wincache_ucache_dec($internalKey, (int)$value); } - /* cleaning */ - - /** - * Internal method to clear items off all namespaces. - * - * Options: - * - ttl - * - The time-to-life - * - * @param int $normalizedMode Matching mode (Value of Adapter::MATCH_*) - * @param array $normalizedOptions - * @return boolean - * @throws Exception\ExceptionInterface - * @see clearByNamespace() - */ - protected function internalClear(& $normalizedMode, array & $normalizedOptions) - { - return wincache_ucache_clear(); - } - /* status */ /** @@ -512,10 +470,7 @@ protected function internalGetCapabilities() 'resource' => false, ), 'supportedMetadata' => array( - 'ttl', - 'num_hits', - 'internal_key', - 'mem_size' + 'internal_key', 'ttl', 'hits', 'size' ), 'maxTtl' => 0, 'staticTtl' => true, @@ -524,9 +479,6 @@ protected function internalGetCapabilities() 'expiredRead' => false, 'namespaceIsPrefix' => true, 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), - 'iterable' => false, - 'clearAllNamespaces' => true, - 'clearByNamespace' => false, ) ); @@ -546,22 +498,6 @@ protected function internalGetCapabilities() return $this->capabilities; } - /** - * Internal method to get storage capacity. - * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface - */ - protected function internalGetCapacity(array & $normalizedOptions) - { - $mem = wincache_ucache_meminfo(); - return array( - 'free' => $mem['memory_free'], - 'total' => $mem['memory_total'], - ); - } - /* internal */ /** @@ -572,24 +508,16 @@ protected function internalGetCapacity(array & $normalizedOptions) */ protected function normalizeMetadata(array & $metadata) { - if (isset($metadata['hitcount'])) { - $metadata['num_hits'] = $metadata['hitcount']; - unset($metadata['hitcount']); - } - - if (isset($metadata['ttl_seconds'])) { - $metadata['ttl'] = $metadata['ttl_seconds']; - unset($metadata['ttl_seconds']); - } - - if (isset($metadata['value_size'])) { - $metadata['mem_size'] = $metadata['value_size']; - unset($metadata['value_size']); - } - - if (isset($metadata['key_name'])) { - $metadata['internal_key'] = $metadata['key_name']; - unset($metadata['key_name']); - } + $metadata['internal_key'] = $metadata['key_name']; + $metadata['hits'] = $metadata['hitcount']; + $metadata['ttl'] = $metadata['ttl_seconds']; + $metadata['size'] = $metadata['value_size']; + + unset( + $metadata['key_name'], + $metadata['hitcount'], + $metadata['ttl_seconds'], + $metadata['value_size'] + ); } } diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index 01c88bcde..53f3cedc7 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -22,8 +22,12 @@ namespace Zend\Cache\Storage\Adapter; use ArrayObject, - Zend\Cache\Utils, - Zend\Cache\Exception; + Zend\Cache\Exception, + Zend\Cache\Storage\ClearByNamespaceInterface, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\AvailableSpaceCapableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface, + Zend\Stdlib\ErrorHandler; /** * @category Zend @@ -32,9 +36,19 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class ZendServerDisk extends AbstractZendServer +class ZendServerDisk + extends AbstractZendServer + implements FlushableInterface, ClearByNamespaceInterface, + AvailableSpaceCapableInterface, TotalSpaceCapableInterface { + /** + * Buffered total space in bytes + * + * @var null|int|float + */ + protected $totalSpace; + /** * Constructor * @@ -53,18 +67,76 @@ public function __construct($options = array()) parent::__construct($options); } + /* FlushableInterface */ + /** - * Internal method to get storage capacity. + * Flush the whole storage * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface + * @return boolean */ - protected function internalGetCapacity(array & $normalizedOptions) + public function flush() { - return Utils::getDiskCapacity(ini_get('zend_datacache.disk.save_path')); + return zend_disk_cache_clear(); } + /* ClearByNamespaceInterface */ + + /** + * Remove items of given namespace + * + * @param string $namespace + * @return boolean + */ + public function clearByNamespace($namespace) + { + return zend_disk_cache_clear($namespace); + } + + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + if ($this->totalSpace !== null) { + $path = $this->getOptions()->getCacheDir(); + + ErrorHandler::start(); + $total = disk_total_space($path); + $error = ErrorHandler::stop(); + if ($total === false) { + throw new Exception\RuntimeException("Can't detect total space of '{$path}'", 0, $error); + } + } + return $this->totalSpace; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $path = $this->getOptions()->getCacheDir(); + + ErrorHandler::start(); + $avail = disk_free_space($path); + $error = ErrorHandler::stop(); + if ($avail === false) { + throw new Exception\RuntimeException("Can't detect free space of '{$path}'", 0, $error); + } + + return $avail; + } + + /* internal */ + /** * Store data into Zend Data Disk Cache * @@ -123,35 +195,4 @@ protected function zdcDelete($internalKey) { return zend_disk_cache_delete($internalKey); } - - /** - * Clear items of all namespaces from Zend Data Disk Cache - * - * @return void - * @throws Exception\RuntimeException - */ - protected function zdcClear() - { - if (!zend_disk_cache_clear()) { - throw new Exception\RuntimeException( - 'zend_disk_cache_clear() failed' - ); - } - } - - /** - * Clear items of the given namespace from Zend Data Disk Cache - * - * @param string $namespace - * @return void - * @throws Exception\RuntimeException - */ - protected function zdcClearByNamespace($namespace) - { - if (!zend_disk_cache_clear($namespace)) { - throw new Exception\RuntimeException( - "zend_disk_cache_clear({$namespace}) failed" - ); - } - } } diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 3ce9d18ce..5c1f8d0be 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -22,7 +22,10 @@ namespace Zend\Cache\Storage\Adapter; use ArrayObject, - Zend\Cache\Exception; + Zend\Cache\Exception, + Zend\Cache\Storage\ClearByNamespaceInterface, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @category Zend @@ -31,7 +34,9 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class ZendServerShm extends AbstractZendServer +class ZendServerShm + extends AbstractZendServer + implements FlushableInterface, ClearByNamespaceInterface, TotalSpaceCapableInterface { /** @@ -52,23 +57,45 @@ public function __construct($options = array()) parent::__construct($options); } + /* FlushableInterface */ + /** - * Internal method to get storage capacity. + * Flush the whole storage * - * @param array $normalizedOptions - * @return array|boolean Associative array of capacity, false on failure - * @throws Exception\ExceptionInterface + * @return boolean */ - protected function internalGetCapacity(array & $normalizedOptions) + public function flush() { - $total = (int)ini_get('zend_datacache.shm.memory_cache_size'); - $total*= 1048576; // MB -> Byte - return array( - 'total' => $total, - // TODO: How to get free capacity status - ); + return zend_shm_cache_clear(); } + /* ClearByNamespaceInterface */ + + /** + * Remove items of given namespace + * + * @param string $namespace + * @return boolean + */ + public function clearByNamespace($namespace) + { + return zend_shm_cache_clear($namespace); + } + + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + return (int) ini_get('zend_datacache.shm.memory_cache_size') * 1048576; + } + + /* internal */ + /** * Store data into Zend Data SHM Cache * @@ -127,35 +154,4 @@ protected function zdcDelete($internalKey) { return zend_shm_cache_delete($internalKey); } - - /** - * Clear items of all namespaces from Zend Data SHM Cache - * - * @return void - * @throws Exception\RuntimeException - */ - protected function zdcClear() - { - if (!zend_shm_cache_clear()) { - throw new Exception\RuntimeException( - 'zend_shm_cache_clear() failed' - ); - } - } - - /** - * Clear items of the given namespace from Zend Data SHM Cache - * - * @param string $namespace - * @return void - * @throws Exception\RuntimeException - */ - protected function zdcClearByNamespace($namespace) - { - if (!zend_shm_cache_clear($namespace)) { - throw new Exception\RuntimeException( - "zend_shm_cache_clear({$namespace}) failed" - ); - } - } } diff --git a/src/Storage/AdapterBroker.php b/src/Storage/AdapterBroker.php index 95cf6e200..7e9a99630 100644 --- a/src/Storage/AdapterBroker.php +++ b/src/Storage/AdapterBroker.php @@ -49,9 +49,9 @@ class AdapterBroker extends PluginBroker */ protected function validatePlugin($plugin) { - if (!$plugin instanceof Adapter\AdapterInterface) { + if (!$plugin instanceof StorageInterface) { throw new Exception\RuntimeException( - 'Cache storage adapters must implement Zend\Cache\Storage\Adapter\AdapterInterface' + 'Cache storage adapters must implement Zend\Cache\Storage\StorageInterface' ); } return true; diff --git a/src/Storage/AvailableSpaceCapableInterface.php b/src/Storage/AvailableSpaceCapableInterface.php new file mode 100644 index 000000000..6e1ab7442 --- /dev/null +++ b/src/Storage/AvailableSpaceCapableInterface.php @@ -0,0 +1,39 @@ +adapter = $adapter; + $this->storage = $storage; $this->marker = $marker; $this->baseCapabilities = $baseCapabilities; @@ -163,7 +141,7 @@ public function __construct( */ public function getAdapter() { - return $this->adapter; + return $this->storage; } /** @@ -446,93 +424,6 @@ public function setNamespaceSeparator(stdClass $marker, $separator) return $this->setCapability($marker, 'namespaceSeparator', (string) $separator); } - /** - * Get if items are iterable - * - * @return boolean - */ - public function getIterable() - { - return $this->getCapability('iterable', false); - } - - /** - * Set if items are iterable - * - * @param stdClass $marker - * @param boolean $flag - * @return Capabilities Fluent interface - */ - public function setIterable(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'iterable', (bool)$flag); - } - - /** - * Get support to clear items of all namespaces - * - * @return boolean - */ - public function getClearAllNamespaces() - { - return $this->getCapability('clearAllNamespaces', false); - } - - /** - * Set support to clear items of all namespaces - * - * @param stdClass $marker - * @param boolean $flag - * @return Capabilities Fluent interface - */ - public function setClearAllNamespaces(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'clearAllNamespaces', (bool)$flag); - } - - /** - * Get support to clear items by namespace - * - * @return boolean - */ - public function getClearByNamespace() - { - return $this->getCapability('clearByNamespace', false); - } - - /** - * Set support to clear items by namespace - * - * @param stdClass $marker - * @param boolean $flag - * @return Capabilities Fluent interface - */ - public function setClearByNamespace(stdClass $marker, $flag) - { - return $this->setCapability($marker, 'clearByNamespace', (bool)$flag); - } - - /** - * Set value for tagging - * - * @param mixed tagging - * @return $this - */ - public function setTagging(stdClass $marker, $tagging) - { - return $this->setCapability($marker, 'tagging', (bool) $tagging); - } - - /** - * Get value for tagging - * - * @return mixed - */ - public function getTagging() - { - return $this->getCapability('tagging', false); - } - /** * Get a capability * @@ -572,8 +463,8 @@ protected function setCapability(stdClass $marker, $name, $value) $this->$property = $value; // trigger event - if ($this->adapter instanceof EventsCapableInterface) { - $this->adapter->events()->trigger('capability', $this->adapter, new ArrayObject(array( + if ($this->storage instanceof EventsCapableInterface) { + $this->storage->events()->trigger('capability', $this->storage, new ArrayObject(array( $name => $value ))); } diff --git a/src/Storage/ClearByNamespaceInterface.php b/src/Storage/ClearByNamespaceInterface.php new file mode 100644 index 000000000..6d1e88644 --- /dev/null +++ b/src/Storage/ClearByNamespaceInterface.php @@ -0,0 +1,40 @@ +target = $adapter; + $this->target = $storage; return $this; } /** * Alias of getTarget * - * @return Adapter\AdapterInterface + * @return StorageInterface */ public function getStorage() { diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index 145c0c265..d7158a14d 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -59,7 +59,7 @@ class ExceptionEvent extends PostEvent * @param Exception $exception * @return void */ - public function __construct($name, Adapter\AdapterInterface $storage, ArrayObject $params, & $result, Exception $exception) + public function __construct($name, StorageInterface $storage, ArrayObject $params, & $result, Exception $exception) { parent::__construct($name, $storage, $params, $result); $this->setException($exception); diff --git a/src/Storage/FlushableInterface.php b/src/Storage/FlushableInterface.php new file mode 100644 index 000000000..1a25f482c --- /dev/null +++ b/src/Storage/FlushableInterface.php @@ -0,0 +1,39 @@ +handles[$index] = & $handles; - $callback = array($this, 'clearByFactor'); + $callback = array($this, 'clearExpiredByFactor'); $handles[] = $events->attach('setItem.post', $callback, $priority); $handles[] = $events->attach('setItems.post', $callback, $priority); $handles[] = $events->attach('addItem.post', $callback, $priority); @@ -96,22 +97,21 @@ public function detach(EventManagerInterface $events) } /** - * Clear storage by factor on a success _RESULT_ + * Clear expired items by factor after writing new item(s) * * @param PostEvent $event * @return void */ - public function clearByFactor(PostEvent $event) + public function clearExpiredByFactor(PostEvent $event) { - $options = $this->getOptions(); - $factor = $options->getClearingFactor(); - if ($factor && $event->getResult() && mt_rand(1, $factor) == 1) { - $params = $event->getParams(); - if ($options->getClearByNamespace()) { - $event->getStorage()->clearByNamespace(Adapter::MATCH_EXPIRED, $params['options']); - } else { - $event->getStorage()->clear(Adapter::MATCH_EXPIRED, $params['options']); - } + $storage = $event->getStorage(); + if ( !($storage instanceof ClearExpiredInterface) ) { + return; + } + + $factor = $this->getOptions()->getClearingFactor(); + if ($factor && mt_rand(1, $factor) == 1) { + $storage->clearExpired(); } } } diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 4e8bc202b..ba64a6a40 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -70,13 +70,6 @@ public function attach(EventManagerInterface $events, $priority = 1) $handles[] = $events->attach('getMetadata.exception', $callback, $priority); $handles[] = $events->attach('getMetadatas.exception', $callback, $priority); - // non-blocking - $handles[] = $events->attach('getDelayed.exception', $callback, $priority); - $handles[] = $events->attach('find.exception', $callback, $priority); - - $handles[] = $events->attach('fetch.exception', $callback, $priority); - $handles[] = $events->attach('fetchAll.exception', $callback, $priority); - // write $handles[] = $events->attach('setItem.exception', $callback, $priority); $handles[] = $events->attach('setItems.exception', $callback, $priority); @@ -102,14 +95,6 @@ public function attach(EventManagerInterface $events, $priority = 1) $handles[] = $events->attach('decrementItem.exception', $callback, $priority); $handles[] = $events->attach('decrementItems.exception', $callback, $priority); - // clear - $handles[] = $events->attach('clear.exception', $callback, $priority); - $handles[] = $events->attach('clearByNamespace.exception', $callback, $priority); - - // additional - $handles[] = $events->attach('optimize.exception', $callback, $priority); - $handles[] = $events->attach('getCapacity.exception', $callback, $priority); - return $this; } diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php index 4c8703b4d..7710a97ba 100644 --- a/src/Storage/Plugin/IgnoreUserAbort.php +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -42,9 +42,9 @@ class IgnoreUserAbort extends AbstractPlugin protected $handles = array(); /** - * The storage adapter target who activated ignore_user_abort. + * The storage who activated ignore_user_abort. * - * @var null|\Zend\Cache\Storage\Adapter\AdapterInterface + * @var null|Zend\Cache\Storage\StorageInterface */ protected $activatedTarget = null; diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index a72f24096..64d8de293 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -23,6 +23,7 @@ use Traversable, Zend\Cache\Exception, + Zend\Cache\Storage\OptimizableInterface, Zend\Cache\Storage\PostEvent, Zend\EventManager\EventManagerInterface; @@ -61,10 +62,8 @@ public function attach(EventManagerInterface $events, $priority = 1) $this->handles[$index] = & $handles; $callback = array($this, 'optimizeByFactor'); - $handles[] = $events->attach('removeItem.post', $callback, $priority); - $handles[] = $events->attach('removeItems.post', $callback, $priority); - $handles[] = $events->attach('clear.post', $callback, $priority); - $handles[] = $events->attach('clearByNamespace.post', $callback, $priority); + $handles[] = $events->attach('removeItem.post', $callback, $priority); + $handles[] = $events->attach('removeItems.post', $callback, $priority); return $this; } @@ -102,10 +101,14 @@ public function detach(EventManagerInterface $events) */ public function optimizeByFactor(PostEvent $event) { + $storage = $event->getStorage(); + if ( !($storage instanceof OptimizableInterface) ) { + return; + } + $factor = $this->getOptions()->getOptimizingFactor(); - if ($factor && $event->getResult() && mt_rand(1, $factor) == 1) { - $params = $event->getParams(); - $event->getStorage()->optimize($params['options']); + if ($factor && mt_rand(1, $factor) == 1) { + $storage->optimize(); } } } diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index 1d3fb9ee3..828c95956 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -42,13 +42,6 @@ class PluginOptions extends Options */ protected $clearingFactor = 0; - /** - * Used by: - * - ClearByFactor - * @var int - */ - protected $clearByNamespace = true; - /** * Used by: * - ExceptionHandler @@ -95,7 +88,7 @@ class PluginOptions extends Options * Set automatic clearing factor * * Used by: - * - ClearByFactor + * - ClearExpiredByFactor * * @param int $clearingFactor * @return PluginOptions @@ -110,7 +103,7 @@ public function setClearingFactor($clearingFactor) * Get automatic clearing factor * * Used by: - * - ClearByFactor + * - ClearExpiredByFactor * * @return int */ @@ -119,34 +112,6 @@ public function getClearingFactor() return $this->clearingFactor; } - /** - * Set flag indicating whether or not to clear by namespace - * - * Used by: - * - ClearByFactor - * - * @param bool $clearByNamespace - * @return PluginOptions - */ - public function setClearByNamespace($clearByNamespace) - { - $this->clearByNamespace = $clearByNamespace; - return $this; - } - - /** - * Clear items by namespace? - * - * Used by: - * - ClearByFactor - * - * @return bool - */ - public function getClearByNamespace() - { - return $this->clearByNamespace; - } - /** * Set callback to call on intercepted exception * diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 3916e5eee..027091ebd 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -77,10 +77,6 @@ public function attach(EventManagerInterface $events, $priority = 1) $handles[] = $events->attach('getItem.post', array($this, 'onReadItemPost'), $postPriority); $handles[] = $events->attach('getItems.post', array($this, 'onReadItemsPost'), $postPriority); - // fetch / fetchAll - $handles[] = $events->attach('fetch.post', array($this, 'onFetchPost'), $postPriority); - $handles[] = $events->attach('fetchAll.post', array($this, 'onFetchAllPost'), $postPriority); - // write $handles[] = $events->attach('setItem.pre', array($this, 'onWriteItemPre'), $prePriority); $handles[] = $events->attach('setItems.pre', array($this, 'onWriteItemsPre'), $prePriority); @@ -139,8 +135,7 @@ public function detach(EventManagerInterface $events) */ public function onReadItemPost(PostEvent $event) { - $options = $this->getOptions(); - $serializer = $options->getSerializer(); + $serializer = $this->getOptions()->getSerializer(); $result = $event->getResult(); $result = $serializer->unserialize($result); $event->setResult($result); @@ -154,8 +149,7 @@ public function onReadItemPost(PostEvent $event) */ public function onReadItemsPost(PostEvent $event) { - $options = $this->getOptions(); - $serializer = $options->getSerializer(); + $serializer = $this->getOptions()->getSerializer(); $result = $event->getResult(); foreach ($result as &$value) { $value = $serializer->unserialize($value); @@ -163,42 +157,6 @@ public function onReadItemsPost(PostEvent $event) $event->setResult($result); } - /** - * On fetch post - * - * @param PostEvent $event - * @return void - */ - public function onFetchPost(PostEvent $event) - { - $options = $this->getOptions(); - $serializer = $options->getSerializer(); - $item = $event->getResult(); - if (isset($item['value'])) { - $item['value'] = $serializer->unserialize($item['value']); - } - $event->setResult($item); - } - - /** - * On fetch all post - * - * @param PostEvent $event - * @return void - */ - public function onFetchAllPost(PostEvent $event) - { - $options = $this->getOptions(); - $serializer = $options->getSerializer(); - $result = $event->getResult(); - foreach ($result as &$item) { - if (isset($item['value'])) { - $item['value'] = $serializer->unserialize($item['value']); - } - } - $event->setResult($result); - } - /** * On write item pre * @@ -207,8 +165,7 @@ public function onFetchAllPost(PostEvent $event) */ public function onWriteItemPre(Event $event) { - $options = $this->getOptions(); - $serializer = $options->getSerializer(); + $serializer = $this->getOptions()->getSerializer(); $params = $event->getParams(); $params['value'] = $serializer->serialize($params['value']); } @@ -221,8 +178,7 @@ public function onWriteItemPre(Event $event) */ public function onWriteItemsPre(Event $event) { - $options = $this->getOptions(); - $serializer = $options->getSerializer(); + $serializer = $this->getOptions()->getSerializer(); $params = $event->getParams(); foreach ($params['keyValuePairs'] as &$value) { $value = $serializer->serialize($value); @@ -237,21 +193,22 @@ public function onWriteItemsPre(Event $event) */ public function onIncrementItemPre(Event $event) { - $event->stopPropagation(true); - - $cache = $event->getTarget(); + $storage = $event->getTarget(); $params = $event->getParams(); - $token = null; - $oldValue = $cache->getItem( - $params['key'], - array('token' => &$token) + $params['options'] - ); - return $cache->checkAndSetItem( - $token, - $oldValue + $params['value'], - $params['key'], - $params['options'] - ); + $casToken = null; + $success = null; + $oldValue = $storage->getItem($params['key'], $success, $casToken); + $newValue = $oldValue + $params['value']; + + if ($success) { + $storage->checkAndSetItem($casToken, $params['key'], $oldValue + $params['value']); + $result = $newValue; + } else { + $result = false; + } + + $event->stopPropagation(true); + return $result; } /** @@ -262,19 +219,25 @@ public function onIncrementItemPre(Event $event) */ public function onIncrementItemsPre(Event $event) { - $event->stopPropagation(true); - - $cache = $event->getTarget(); - $params = $event->getParams(); - $keyValuePairs = $cache->getItems(array_keys($params['keyValuePairs']), $params['options']); - foreach ($params['keyValuePairs'] as $key => &$value) { + $storage = $event->getTarget(); + $params = $event->getParams(); + $keyValuePairs = $storage->getItems(array_keys($params['keyValuePairs'])); + foreach ($params['keyValuePairs'] as $key => & $value) { if (isset($keyValuePairs[$key])) { $keyValuePairs[$key]+= $value; } else { $keyValuePairs[$key] = $value; } } - return $cache->setItems($keyValuePairs, $params['options']); + + $failedKeys = $storage->setItems($keyValuePairs); + $result = array(); + foreach ($failedKeys as $failedKey) { + unset($keyValuePairs[$failedKey]); + } + + $event->stopPropagation(true); + return $keyValuePairs; } /** @@ -285,21 +248,22 @@ public function onIncrementItemsPre(Event $event) */ public function onDecrementItemPre(Event $event) { - $event->stopPropagation(true); - - $cache = $event->getTarget(); + $storage = $event->getTarget(); $params = $event->getParams(); - $token = null; - $oldValue = $cache->getItem( - $params['key'], - array('token' => &$token) + $params['options'] - ); - return $cache->checkAndSetItem( - $token, - $oldValue - $params['value'], - $params['key'], - $params['options'] - ); + $success = null; + $casToken = null; + $oldValue = $storage->getItem($params['key'], $success, $casToken); + $newValue = $oldValue - $params['value']; + + if ($success) { + $storage->checkAndSetItem($casToken, $params['key'], $oldValue + $params['value']); + $result = $newValue; + } else { + $result = false; + } + + $event->stopPropagation(true); + return $result; } /** @@ -310,11 +274,9 @@ public function onDecrementItemPre(Event $event) */ public function onDecrementItemsPre(Event $event) { - $event->stopPropagation(true); - - $cache = $event->getTarget(); + $storage = $event->getTarget(); $params = $event->getParams(); - $keyValuePairs = $cache->getItems(array_keys($params['keyValuePairs']), $params['options']); + $keyValuePairs = $storage->getItems(array_keys($params['keyValuePairs'])); foreach ($params['keyValuePairs'] as $key => &$value) { if (isset($keyValuePairs[$key])) { $keyValuePairs[$key]-= $value; @@ -322,7 +284,14 @@ public function onDecrementItemsPre(Event $event) $keyValuePairs[$key] = -$value; } } - return $cache->setItems($keyValuePairs, $params['options']); + + $failedKeys = $storage->setItems($keyValuePairs); + foreach ($failedKeys as $failedKey) { + unset($keyValuePairs[$failedKey]); + } + + $event->stopPropagation(true); + return $keyValuePairs; } /** diff --git a/src/Storage/PluginBroker.php b/src/Storage/PluginBroker.php index 65cce6657..58f6caf69 100644 --- a/src/Storage/PluginBroker.php +++ b/src/Storage/PluginBroker.php @@ -22,6 +22,7 @@ namespace Zend\Cache\Storage; use Zend\Cache\Exception, + Zend\Cache\Storage\Plugin\PluginInterface, Zend\Loader\PluginBroker as BasePluginBroker; /** @@ -51,9 +52,9 @@ class PluginBroker extends BasePluginBroker */ protected function validatePlugin($plugin) { - if (!$plugin instanceof Plugin) { + if (!$plugin instanceof PluginInterface) { throw new Exception\RuntimeException( - 'Cache storage plugins must implement Zend\Cache\Storage\Plugin' + 'Cache storage plugins must implement Zend\Cache\Storage\Plugin\PluginInterface' ); } return true; diff --git a/src/Storage/PluginLoader.php b/src/Storage/PluginLoader.php index 5f79c9210..5161da174 100644 --- a/src/Storage/PluginLoader.php +++ b/src/Storage/PluginLoader.php @@ -40,27 +40,14 @@ class PluginLoader extends PluginClassLoader * @var array */ protected $plugins = array( - 'clear_by_factor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', - 'clearbyfactor' => 'Zend\Cache\Storage\Plugin\ClearByFactor', + 'clear_expired_by_factor' => 'Zend\Cache\Storage\Plugin\ClearExpiredByFactor', + 'clearexpiredbyfactor' => 'Zend\Cache\Storage\Plugin\ClearExpiredByFactor', 'exception_handler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', 'exceptionhandler' => 'Zend\Cache\Storage\Plugin\ExceptionHandler', - //'filter' => 'Zend\Cache\Storage\Plugin\Filter', 'ignore_user_abort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', 'ignoreuserabort' => 'Zend\Cache\Storage\Plugin\IgnoreUserAbort', - //'key_filter' => 'Zend\Cache\Storage\Plugin\KeyFilter', - //'keyfilter' => 'Zend\Cache\Storage\Plugin\KeyFilter', - //'levels' => 'Zend\Cache\Storage\Plugin\Levels', - //'locking' => 'Zend\Cache\Storage\Plugin\Locking', - //'master_file' => 'Zend\Cache\Storage\Plugin\MasterFile', - //'masterfile' => 'Zend\Cache\Storage\Plugin\MasterFile', 'optimize_by_factor' => 'Zend\Cache\Storage\Plugin\OptimizeByFactor', 'optimizebyfactor' => 'Zend\Cache\Storage\Plugin\OptimizeByFactor', - //'reluctant' => 'Zend\Cache\Storage\Plugin\Reluctant', 'serializer' => 'Zend\Cache\Storage\Plugin\Serializer', - //'store_times' => 'Zend\Cache\Storage\Plugin\StoreTimes', - //'storetimes' => 'Zend\Cache\Storage\Plugin\StoreTimes', - //'tagging' => 'Zend\Cache\Storage\Plugin\Tagging', - //'write_control' => 'Zend\Cache\Storage\Plugin\WriteControl', - //'writecontrol' => 'Zend\Cache\Storage\Plugin\WriteControl', ); } diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index 497c20bbb..7fe4f28bf 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -44,13 +44,13 @@ class PostEvent extends Event * * Accept a target and its parameters. * - * @param string $name - * @param Adapter $storage - * @param ArrayObject $params - * @param mixed $result + * @param string $name + * @param StorageInterface $storage + * @param ArrayObject $params + * @param mixed $result * @return void */ - public function __construct($name, Adapter\AdapterInterface $storage, ArrayObject $params, & $result) + public function __construct($name, StorageInterface $storage, ArrayObject $params, & $result) { parent::__construct($name, $storage, $params); $this->setResult($result); diff --git a/src/Storage/StorageInterface.php b/src/Storage/StorageInterface.php new file mode 100644 index 000000000..7936fd0d0 --- /dev/null +++ b/src/Storage/StorageInterface.php @@ -0,0 +1,263 @@ +load($adapterName); } - if ($options !== null) { + if ($options) { $adapter->setOptions($options); } @@ -198,7 +198,7 @@ public static function resetAdapterBroker() /** * Instantiate a storage plugin * - * @param string|Storage\Plugin $pluginName + * @param string|Storage\Plugin $pluginName * @param array|Traversable|Storage\Plugin\PluginOptions $options * @return Storage\Plugin * @throws Exception\RuntimeException @@ -216,7 +216,9 @@ public static function pluginFactory($pluginName, $options = array()) $options = new Storage\Plugin\PluginOptions($options); } - $plugin->setOptions($options); + if ($options) { + $plugin->setOptions($options); + } return $plugin; } diff --git a/src/Utils.php b/src/Utils.php index 7f7eb5d1b..db91b6fb1 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -28,33 +28,6 @@ */ abstract class Utils { - /** - * Get disk capacity - * - * @param string $path A directory of the filesystem or disk partition - * @return array - * @throws Exception\RuntimeException - */ - public static function getDiskCapacity($path) - { - $total = @disk_total_space($path); - if ($total === false) { - $err = error_get_last(); - throw new Exception\RuntimeException($err['message']); - } - - $free = @disk_free_space($path); - if ($free === false) { - $err = error_get_last(); - throw new Exception\RuntimeException($err['message']); - } - - return array( - 'total' => $total, - 'free' => $free, - ); - } - /** * Get php memory capacity * @@ -199,7 +172,7 @@ static protected function getSystemMemoryCapacityOSX() $cmd = 'sysctl -n hw.memsize'; $out = $ret = null; $line = exec($cmd, $out, $ret); - + if ($ret) { $out = implode("\n", $out); throw new Exception\RuntimeException( @@ -214,7 +187,7 @@ static protected function getSystemMemoryCapacityOSX() $cmd = 'vm_stat | grep free'; $out = $ret = null; $line = exec($cmd, $out, $ret); - + if ($ret) { $out = implode("\n", $out); throw new Exception\RuntimeException( diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index b00ddd7bd..9bddc3947 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -66,7 +66,7 @@ class CallbackCacheTest extends CommonPatternTest { /** - * @var Zend\Cache\Storage\Adapter\AdapterInterface + * @var Zend\Cache\Storage\StorageInterface */ protected $_storage; @@ -113,26 +113,6 @@ public function testMagicFunctionCall() ); } - public function testCallWithPredefinedCallbackAndArgumentKey() - { - $callback = __NAMESPACE__ . '\TestCallbackCache::emptyMethod'; - $args = array('arg1', 2, 3.33, null); - $options = array( - 'callback_key' => 'callback', - 'argument_key' => 'arguments', - ); - - $expectedKey = md5($options['callback_key'].$options['argument_key']); - $usedKey = null; - $this->_options->getStorage()->events()->attach('setItem.pre', function ($event) use (&$usedKey) { - $params = $event->getParams(); - $usedKey = $params['key']; - }); - - $this->_pattern->call($callback, $args, $options); - $this->assertEquals($expectedKey, $usedKey); - } - public function testGenerateKey() { $callback = __NAMESPACE__ . '\TestCallbackCache::emptyMethod'; @@ -149,23 +129,6 @@ public function testGenerateKey() $this->assertEquals($generatedKey, $usedKey); } - public function testGenerateKeyWithPredefinedCallbackAndArgumentKey() - { - $callback = __NAMESPACE__ . '\TestCallbackCache::emptyMethod'; - $args = array('arg1', 2, 3.33, null); - $options = array( - 'callback_key' => 'callback', - 'argument_key' => 'arguments', - ); - - $expectedKey = md5($options['callback_key'].$options['argument_key']); - - $this->assertEquals( - $expectedKey, - $this->_pattern->generateKey($callback, $args, $options) - ); - } - public function testCallInvalidCallbackException() { $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); @@ -212,5 +175,4 @@ protected function _testCall($callback, array $args) $this->assertEquals('', $data); } } - } diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php index 43743cb52..4c61aff39 100644 --- a/test/Pattern/CaptureCacheTest.php +++ b/test/Pattern/CaptureCacheTest.php @@ -49,5 +49,4 @@ public function tearDown() // TODO parent::tearDown(); } - } diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index b0bca4141..09fd02ad8 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -57,7 +57,7 @@ class ClassCacheTest extends CommonPatternTest { /** - * @var Zend\Cache\Storage\Adapter\AdapterInterface + * @var Zend\Cache\Storage\StorageInterface */ protected $_storage; @@ -111,12 +111,6 @@ public function testGenerateKey() $this->assertEquals($generatedKey, $usedKey); } - public function testCallUnknownMethodException() - { - $this->setExpectedException('Zend\\Cache\\Exception\\InvalidArgumentException'); - $this->_pattern->call('notExiststingMethod'); - } - protected function _testCall($method, array $args) { $returnSpec = 'foobar_return(' . implode(', ', $args) . ') : '; @@ -146,5 +140,4 @@ protected function _testCall($method, array $args) $this->assertEquals('', $data); } } - } diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index df39f8e86..99b2aa9ab 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -64,7 +64,7 @@ class ObjectCacheTest extends CommonPatternTest { /** - * @var Zend\Cache\Storage\Adapter\AdapterInterface + * @var Zend\Cache\Storage\StorageInterface */ protected $_storage; @@ -125,84 +125,6 @@ public function testGenerateKey() $this->assertEquals($generatedKey, $usedKey); } - public function testGenerateKeyWithPredefinedCallbackAndArgumentKey() - { - $args = array('arg1', 2, 3.33, null); - $options = array( - 'callback_key' => 'callback', - 'argument_key' => 'arguments', - ); - - $expectedKey = md5($options['callback_key'].$options['argument_key']); - - $this->assertEquals( - $expectedKey, - $this->_pattern->generateKey('emptyMethod', $args, $options) - ); - } - - public function testGenerateKeyWithPredefinedEntityKey() - { - $args = array('arg1', 2, 3.33, null); - $options = array( - 'entity_key' => 'object', - 'argument_key' => 'arguments', - ); - $callbackKey = $options['entity_key'].'::emptymethod'; - - $expectedKey = md5($callbackKey.$options['argument_key']); - - $this->assertEquals( - $expectedKey, - $this->_pattern->generateKey('emptyMethod', $args, $options) - ); - } - - public function testGenerateKeyWithClassObjectKey() - { - $args = array('arg1', 2, 3.33, null); - $key = $this->_pattern->generateKey('emptyMethod', $args, array('callback_key' => 'test-object-cache::emptymethod')); - - $class = __NAMESPACE__ . '\TestObjectCache'; - $options = new Cache\Pattern\PatternOptions(array( - 'object' => new $class(), - 'storage' => $this->_storage, - 'objectKey' => 'test-object-cache', - )); - $this->_pattern->setOptions($options); - - $keyWithClassObjectKey = $this->_pattern->generateKey('emptyMethod', $args); - $this->assertEquals($key, $keyWithClassObjectKey); - } - - public function testCallWithClassObjectKey() - { - $class = __NAMESPACE__ . '\TestObjectCache'; - $options = new Cache\Pattern\PatternOptions(array( - 'object' => new $class(), - 'storage' => $this->_storage, - 'objectKey' => 'test-object-cache', - )); - $this->_pattern->setOptions($options); - - $args = array('arg1', 2, 3.33, null); - - $usedCallbackKey = null; - $this->_options->getStorage()->events()->attach('setItem.pre', function ($event) use (&$usedCallbackKey) { - $params = $event->getParams(); - $usedCallbackKey = $params['options']['callback_key']; - }); - - $this->_pattern->call('emptyMethod', $args); - $this->assertEquals('test-object-cache::emptymethod', $usedCallbackKey); - } - - public function testCallUnknownMethodException() - { - $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_pattern->call('notExiststingMethod'); - } - public function testSetProperty() { $this->_pattern->property = 'testSetProperty'; @@ -258,5 +180,4 @@ protected function _testCall($method, array $args) $this->assertEquals('', $data); } } - } diff --git a/test/Pattern/OutputCacheTest.php b/test/Pattern/OutputCacheTest.php index f08e449d2..3b28fe1b1 100644 --- a/test/Pattern/OutputCacheTest.php +++ b/test/Pattern/OutputCacheTest.php @@ -35,7 +35,7 @@ class OutputCacheTest extends CommonPatternTest { /** - * @var Zend\Cache\Storage\Adapter\AdapterInterface + * @var Zend\Cache\Storage\StorageInterface */ protected $_storage; @@ -112,5 +112,4 @@ public function testThrowMissingKeyException() $this->setExpectedException('Zend\Cache\Exception\MissingKeyException'); $this->_pattern->start(''); // empty key } - } diff --git a/test/PatternFactoryTest.php b/test/PatternFactoryTest.php index 8f3f7b7c0..041fa7a56 100644 --- a/test/PatternFactoryTest.php +++ b/test/PatternFactoryTest.php @@ -67,5 +67,4 @@ public function testFactory() $this->assertNotSame($pattern1, $pattern2); } - } diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 9d14cc996..501b05aae 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -57,7 +57,6 @@ public function testGetOptions() $this->assertInternalType('boolean', $options->getReadable()); $this->assertInternalType('integer', $options->getTtl()); $this->assertInternalType('string', $options->getNamespace()); - $this->assertInternalType('string', $options->getNamespacePattern()); $this->assertInternalType('string', $options->getKeyPattern()); } @@ -103,38 +102,12 @@ public function testSetNamespace() $this->assertSame('new_namespace', $this->_options->getNamespace()); } - public function testSetNamespacePattern() - { - $pattern = '/^.*$/'; - $this->_options->setNamespacePattern($pattern); - $this->assertEquals($pattern, $this->_options->getNamespacePattern()); - } - - public function testUnsetNamespacePattern() - { - $this->_options->setNamespacePattern(null); - $this->assertSame('', $this->_options->getNamespacePattern()); - } - public function testSetNamespace0() { $this->_options->setNamespace('0'); $this->assertSame('0', $this->_options->getNamespace()); } - public function testSetNamespacePatternThrowsExceptionOnInvalidPattern() - { - $this->setExpectedException('Zend\Cache\Exception\InvalidArgumentException'); - $this->_options->setNamespacePattern('#'); - } - - public function testSetNamespacePatternThrowsExceptionOnInvalidNamespace() - { - $this->_options->setNamespace('ns'); - $this->setExpectedException('Zend\Cache\Exception\RuntimeException'); - $this->_options->setNamespacePattern('/[abc]/'); - } - public function testSetKeyPattern() { $this->_options->setKeyPattern('/^[key]+$/Di'); @@ -161,13 +134,13 @@ public function testPluginRegistry() // no plugin registered $this->assertFalse($this->_storage->hasPlugin($plugin)); - $this->assertEquals(0, count($this->_storage->getPlugins())); + $this->assertEquals(0, count($this->_storage->getPluginRegistry())); $this->assertEquals(0, count($plugin->getHandles())); // register a plugin $this->assertSame($this->_storage, $this->_storage->addPlugin($plugin)); $this->assertTrue($this->_storage->hasPlugin($plugin)); - $this->assertEquals(1, count($this->_storage->getPlugins())); + $this->assertEquals(1, count($this->_storage->getPluginRegistry())); // test registered callback handles $handles = $plugin->getHandles(); @@ -177,7 +150,7 @@ public function testPluginRegistry() // test unregister a plugin $this->assertSame($this->_storage, $this->_storage->removePlugin($plugin)); $this->assertFalse($this->_storage->hasPlugin($plugin)); - $this->assertEquals(0, count($this->_storage->getPlugins())); + $this->assertEquals(0, count($this->_storage->getPluginRegistry())); $this->assertEquals(0, count($plugin->getHandles())); } @@ -268,17 +241,16 @@ public function testGetItemCallsInternalGetItem() { $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); - $options = array('ttl' => 123); - $key = 'key1'; - $result = 'value1'; + $key = 'key1'; + $result = 'value1'; $this->_storage ->expects($this->once()) ->method('internalGetItem') - ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->with($this->equalTo($key)) ->will($this->returnValue($result)); - $rs = $this->_storage->getItem($key, $options); + $rs = $this->_storage->getItem($key); $this->assertEquals($result, $rs); } @@ -286,17 +258,16 @@ public function testGetItemsCallsInternalGetItems() { $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItems')); - $options = array('ttl' => 123); - $keys = array('key1', 'key2'); - $result = array('key2' => 'value2'); + $keys = array('key1', 'key2'); + $result = array('key2' => 'value2'); $this->_storage ->expects($this->once()) ->method('internalGetItems') - ->with($this->equalTo($keys), $this->equalTo($this->normalizeOptions($options))) + ->with($this->equalTo($keys)) ->will($this->returnValue($result)); - $rs = $this->_storage->getItems($keys, $options); + $rs = $this->_storage->getItems($keys); $this->assertEquals($result, $rs); } @@ -309,9 +280,8 @@ public function testInternalGetItemsCallsInternalGetItemForEachKey() $this->_storage = $this->getMockForAbstractAdapter(array('internalGetItem')); - $options = array('ttl' => 123); - $items = array('key1' => 'value1', 'notFound' => false, 'key2' => 'value2'); - $result = array('key1' => 'value1', 'key2' => 'value2'); + $items = array('key1' => 'value1', 'notFound' => false, 'key2' => 'value2'); + $result = array('key1' => 'value1', 'key2' => 'value2'); $i = 0; // method call counter foreach ($items as $k => $v) { @@ -319,11 +289,10 @@ public function testInternalGetItemsCallsInternalGetItemForEachKey() ->method('internalGetItem') ->with( $this->equalTo($k), - $this->equalTo($this->normalizeOptions($options)), $this->equalTo(null), $this->equalTo(null) ) - ->will($this->returnCallback(function ($k, $options, & $success, & $casToken) use ($items) { + ->will($this->returnCallback(function ($k, & $success, & $casToken) use ($items) { if ($items[$k]) { $success = true; return $items[$k]; @@ -342,17 +311,16 @@ public function testHasItemCallsInternalHasItem() { $this->_storage = $this->getMockForAbstractAdapter(array('internalHasItem')); - $options = array('ttl' => 123); - $key = 'key1'; - $result = true; + $key = 'key1'; + $result = true; $this->_storage ->expects($this->once()) ->method('internalHasItem') - ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->with($this->equalTo($key)) ->will($this->returnValue($result)); - $rs = $this->_storage->hasItem($key, $options); + $rs = $this->_storage->hasItem($key); $this->assertSame($result, $rs); } @@ -360,17 +328,16 @@ public function testHasItemsCallsInternalHasItems() { $this->_storage = $this->getMockForAbstractAdapter(array('internalHasItems')); - $options = array('ttl' => 123); - $keys = array('key1', 'key2'); - $result = array('key2'); + $keys = array('key1', 'key2'); + $result = array('key2'); $this->_storage ->expects($this->once()) ->method('internalHasItems') - ->with($this->equalTo($keys), $this->equalTo($this->normalizeOptions($options))) + ->with($this->equalTo($keys)) ->will($this->returnValue($result)); - $rs = $this->_storage->hasItems($keys, $options); + $rs = $this->_storage->hasItems($keys); $this->assertEquals($result, $rs); } @@ -378,20 +345,19 @@ public function testInternalHasItemsCallsInternalHasItem() { $this->_storage = $this->getMockForAbstractAdapter(array('internalHasItem')); - $options = array('ttl' => 123); - $items = array('key1' => true, 'key2' => false); - $result = array('key1'); + $items = array('key1' => true, 'key2' => false); + $result = array('key1'); $i = 0; // method call counter foreach ($items as $k => $v) { $this->_storage ->expects($this->at($i++)) ->method('internalHasItem') - ->with($this->equalTo($k), $this->equalTo($this->normalizeOptions($options))) + ->with($this->equalTo($k)) ->will($this->returnValue($v)); } - $rs = $this->_storage->hasItems(array_keys($items), $options); + $rs = $this->_storage->hasItems(array_keys($items)); $this->assertEquals($result, $rs); } @@ -399,17 +365,16 @@ public function testGetMetadataCallsInternalGetMetadata() { $this->_storage = $this->getMockForAbstractAdapter(array('internalGetMetadata')); - $options = array('ttl' => 123); - $key = 'key1'; - $result = array(); + $key = 'key1'; + $result = array(); $this->_storage ->expects($this->once()) ->method('internalGetMetadata') - ->with($this->equalTo($key), $this->equalTo($this->normalizeOptions($options))) + ->with($this->equalTo($key)) ->will($this->returnValue($result)); - $rs = $this->_storage->getMetadata($key, $options); + $rs = $this->_storage->getMetadata($key); $this->assertSame($result, $rs); } @@ -599,7 +564,6 @@ public function testRemoveItemsFail() $this->assertFalse($this->_storage->removeItems($items, $options)); } */ - // TODO: getDelayed + fatch[All] // TODO: incrementItem[s] + decrementItem[s] // TODO: touchItem[s] @@ -609,45 +573,39 @@ public function testPreEventsCanChangeArguments() $this->checkPreEventCanChangeArguments('getItem', array( 'key' => 'key' ), array( - 'key' => 'changedKey', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', )); $this->checkPreEventCanChangeArguments('getItems', array( 'keys' => array('key') ), array( - 'keys' => array('changedKey'), - 'options' => array('ttl' => 456) + 'keys' => array('changedKey'), )); // hasItem(s) $this->checkPreEventCanChangeArguments('hasItem', array( 'key' => 'key' ), array( - 'key' => 'changedKey', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', )); $this->checkPreEventCanChangeArguments('hasItems', array( 'keys' => array('key'), ), array( - 'keys' => array('changedKey'), - 'options' => array('ttl' => 456) + 'keys' => array('changedKey'), )); // getMetadata(s) $this->checkPreEventCanChangeArguments('getMetadata', array( 'key' => 'key' ), array( - 'key' => 'changedKey', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', )); $this->checkPreEventCanChangeArguments('getMetadatas', array( 'keys' => array('key'), ), array( - 'keys' => array('changedKey'), - 'options' => array('ttl' => 456) + 'keys' => array('changedKey'), )); // setItem(s) @@ -655,16 +613,14 @@ public function testPreEventsCanChangeArguments() 'key' => 'key', 'value' => 'value', ), array( - 'key' => 'changedKey', - 'value' => 'changedValue', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', + 'value' => 'changedValue', )); $this->checkPreEventCanChangeArguments('setItems', array( 'keyValuePairs' => array('key' => 'value'), ), array( 'keyValuePairs' => array('changedKey' => 'changedValue'), - 'options' => array('ttl' => 456) )); // addItem(s) @@ -672,16 +628,14 @@ public function testPreEventsCanChangeArguments() 'key' => 'key', 'value' => 'value', ), array( - 'key' => 'changedKey', - 'value' => 'changedValue', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', + 'value' => 'changedValue', )); $this->checkPreEventCanChangeArguments('addItems', array( 'keyValuePairs' => array('key' => 'value'), ), array( 'keyValuePairs' => array('changedKey' => 'changedValue'), - 'options' => array('ttl' => 456) )); // replaceItem(s) @@ -689,16 +643,14 @@ public function testPreEventsCanChangeArguments() 'key' => 'key', 'value' => 'value', ), array( - 'key' => 'changedKey', - 'value' => 'changedValue', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', + 'value' => 'changedValue', )); $this->checkPreEventCanChangeArguments('replaceItems', array( 'keyValuePairs' => array('key' => 'value'), ), array( 'keyValuePairs' => array('changedKey' => 'changedValue'), - 'options' => array('ttl' => 456) )); // CAS @@ -707,40 +659,35 @@ public function testPreEventsCanChangeArguments() 'key' => 'key', 'value' => 'value', ), array( - 'token' => 'changedToken', - 'key' => 'changedKey', - 'value' => 'changedValue', - 'options' => array('ttl' => 456) + 'token' => 'changedToken', + 'key' => 'changedKey', + 'value' => 'changedValue', )); // touchItem(s) $this->checkPreEventCanChangeArguments('touchItem', array( 'key' => 'key', ), array( - 'key' => 'changedKey', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', )); $this->checkPreEventCanChangeArguments('touchItems', array( 'keys' => array('key'), ), array( - 'keys' => array('changedKey'), - 'options' => array('ttl' => 456) + 'keys' => array('changedKey'), )); // removeItem(s) $this->checkPreEventCanChangeArguments('removeItem', array( 'key' => 'key', ), array( - 'key' => 'changedKey', - 'options' => array('ttl' => 456) + 'key' => 'changedKey', )); $this->checkPreEventCanChangeArguments('removeItems', array( 'keys' => array('key'), ), array( - 'keys' => array('changedKey'), - 'options' => array('ttl' => 456) + 'keys' => array('changedKey'), )); // incrementItem(s) @@ -748,16 +695,14 @@ public function testPreEventsCanChangeArguments() 'key' => 'key', 'value' => 1 ), array( - 'key' => 'changedKey', - 'value' => 2, - 'options' => array('ttl' => 456) + 'key' => 'changedKey', + 'value' => 2, )); $this->checkPreEventCanChangeArguments('incrementItems', array( 'keyValuePairs' => array('key' => 1), ), array( 'keyValuePairs' => array('changedKey' => 2), - 'options' => array('ttl' => 456) )); // decrementItem(s) @@ -765,57 +710,14 @@ public function testPreEventsCanChangeArguments() 'key' => 'key', 'value' => 1 ), array( - 'key' => 'changedKey', - 'value' => 2, - 'options' => array('ttl' => 456) + 'key' => 'changedKey', + 'value' => 2, )); $this->checkPreEventCanChangeArguments('decrementItems', array( 'keyValuePairs' => array('key' => 1), ), array( 'keyValuePairs' => array('changedKey' => 2), - 'options' => array('ttl' => 456) - )); - - // getDelayed - $this->checkPreEventCanChangeArguments('getDelayed', array( - 'keys' => array('key'), - ), array( - 'keys' => array('changedKey'), - 'options' => array('ttl' => 456) - )); - - // find - $this->checkPreEventCanChangeArguments('find', array( - 'mode' => Cache\Storage\Adapter\AdapterInterface::MATCH_ACTIVE, - ), array( - 'mode' => Cache\Storage\Adapter\AdapterInterface::MATCH_ALL, - 'options' => array('ttl' => 456) - )); - - // clear[ByNamespace] - $this->checkPreEventCanChangeArguments('clear', array( - 'mode' => Cache\Storage\Adapter\AdapterInterface::MATCH_ACTIVE, - ), array( - 'mode' => Cache\Storage\Adapter\AdapterInterface::MATCH_ALL, - 'options' => array('ttl' => 456) - )); - - $this->checkPreEventCanChangeArguments('clearByNamespace', array( - 'mode' => Cache\Storage\Adapter\AdapterInterface::MATCH_ACTIVE, - ), array( - 'mode' => Cache\Storage\Adapter\AdapterInterface::MATCH_ALL, - 'options' => array('ttl' => 456) - )); - - // optimize - $this->checkPreEventCanChangeArguments('optimize', array(), array( - 'options' => array('ttl' => 456) - )); - - // getCapacity - $this->checkPreEventCanChangeArguments('getCapacity', array(), array( - 'options' => array('ttl' => 456) )); } @@ -871,30 +773,4 @@ protected function getMockForAbstractAdapter(array $methods = array()) $adapter->setOptions($this->_options); return $adapter; } - - protected function normalizeOptions($options) - { - // ttl - if (!isset($options['ttl'])) { - $options['ttl'] = $this->_options->getTtl(); - } - - // namespace - if (!isset($options['namespace'])) { - $options['namespace'] = $this->_options->getNamespace(); - } - - // tags - if (!isset($options['tags'])) { - $options['tags'] = null; - } - - // select - if (!isset($options['select'])) { - $options['select'] = array('key', 'value'); - } - - return $options; - } - } diff --git a/test/Storage/Adapter/AbstractZendServerTest.php b/test/Storage/Adapter/AbstractZendServerTest.php index dc552d9b5..9a8f07997 100644 --- a/test/Storage/Adapter/AbstractZendServerTest.php +++ b/test/Storage/Adapter/AbstractZendServerTest.php @@ -21,7 +21,7 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache\Storage\Adapter\AdapterInterface as Adapter, +use Zend\Cache\Storage\StorageInterface, Zend\Cache\Storage\Adapter\AdapterOptions, Zend\Cache\Storage\Adapter\AbstractZendServer; @@ -54,91 +54,54 @@ public function testGetOptions() $this->assertInternalType('boolean', $options->getReadable()); $this->assertInternalType('integer', $options->getTtl()); $this->assertInternalType('string', $options->getNamespace()); - $this->assertInternalType('string', $options->getNamespacePattern()); $this->assertInternalType('string', $options->getKeyPattern()); } - public function testGetWithDefaultNamespace() + public function testGetItem() { - $this->_options->setNamespace('defaultns'); + $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') - ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue('value')); $this->assertEquals('value', $this->_storage->getItem('key')); } - public function testGetWithArgNamespace() + public function testGetMetadata() { - $this->_options->setNamespace('defaultns'); + $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') - ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) - ->will($this->returnValue('value')); - - $this->assertEquals('value', $this->_storage->getItem('key', array('namespace' => 'argns'))); - } - - public function testInfoWithDefaultNamespace() - { - $this->_options->setNamespace('defaultns'); - - $this->_storage->expects($this->once()) - ->method('zdcFetch') - ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue('value')); $this->assertEquals(array(), $this->_storage->getMetadata('key')); } - public function testInfoWithArgNamespace() + public function testHasItem() { - $this->_options->setNamespace('defaultns'); + $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcFetch') - ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) - ->will($this->returnValue('value')); - - $this->assertEquals(array(), $this->_storage->getMetadata('key', array('namespace' => 'argns'))); - } - - public function testExistsWithDefaultNamespace() - { - $this->_options->setNamespace('defaultns'); - - $this->_storage->expects($this->once()) - ->method('zdcFetch') - ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue('value')); $this->assertEquals(true, $this->_storage->hasItem('key')); } - public function testExistsWithArgNamespace() - { - $this->_options->setNamespace('defaultns'); - - $this->_storage->expects($this->once()) - ->method('zdcFetch') - ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) - ->will($this->returnValue('value')); - - $this->assertEquals(true, $this->_storage->hasItem('key', array('namespace' => 'argns'))); - } - - public function testSetWithDefaultNamespaceAndTtl() + public function testSetItem() { $this->_options->setTtl(10); - $this->_options->setNamespace('defaultns'); + $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcStore') ->with( - $this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key'), + $this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key'), $this->equalTo('value'), $this->equalTo(10) ) @@ -147,86 +110,15 @@ public function testSetWithDefaultNamespaceAndTtl() $this->assertEquals(true, $this->_storage->setItem('key', 'value')); } - public function testSetWithArgNamespaceAndTtl() + public function testRemoveItem() { - $this->_options->setTtl(10); - $this->_options->setNamespace('defaultns'); - - $this->_storage->expects($this->once()) - ->method('zdcStore') - ->with( - $this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key'), - $this->equalTo('value'), - $this->equalTo(100) - ) - ->will($this->returnValue(true)); - - $this->assertEquals(true, $this->_storage->setItem('key', 'value', array('namespace' => 'argns', 'ttl' => 100))); - } - - public function testRemoveWithDefaultNamespace() - { - $this->_options->setNamespace('defaultns'); + $this->_options->setNamespace('ns'); $this->_storage->expects($this->once()) ->method('zdcDelete') - ->with($this->equalTo('defaultns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) + ->with($this->equalTo('ns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) ->will($this->returnValue(true)); $this->assertEquals(true, $this->_storage->removeItem('key')); } - - public function testRemoveWithArgNamespace() - { - $this->_options->setNamespace('defaultns'); - - $this->_storage->expects($this->once()) - ->method('zdcDelete') - ->with($this->equalTo('argns' . AbstractZendServer::NAMESPACE_SEPARATOR . 'key')) - ->will($this->returnValue(true)); - - $this->assertEquals(true, $this->_storage->removeItem('key', array('namespace' => 'argns'))); - } - - public function testClearExpired() - { - $this->_storage->expects($this->never()) - ->method('zdcClear'); - - $this->assertEquals(true, $this->_storage->clear(Adapter::MATCH_EXPIRED)); - } - - public function testClearActive() - { - $this->_storage->expects($this->once()) - ->method('zdcClear') - ->will($this->returnValue(true)); - - $rs = $this->_storage->clear(Adapter::MATCH_ACTIVE); - $this->assertEquals(true, $rs); - } - - public function testClearActiveByDefaultNamespace() - { - $this->_storage->expects($this->once()) - ->method('zdcClearByNamespace') - ->with($this->equalTo($this->_options->getNamespace())) - ->will($this->returnValue(true)); - - $rs = $this->_storage->clearByNamespace(Adapter::MATCH_ACTIVE); - $this->assertEquals(true, $rs); - } - - public function testClearActiveByArgNamespace() - { - $ns = 'namespace'; - $this->_storage->expects($this->once()) - ->method('zdcClearByNamespace') - ->with($this->equalTo($ns)) - ->will($this->returnValue(true)); - - $rs = $this->_storage->clearByNamespace(Adapter::MATCH_ACTIVE, array('namespace' => $ns)); - $this->assertEquals(true, $rs); - } - } diff --git a/test/Storage/Adapter/ApcTest.php b/test/Storage/Adapter/ApcTest.php index b55e30eed..a2ded30df 100644 --- a/test/Storage/Adapter/ApcTest.php +++ b/test/Storage/Adapter/ApcTest.php @@ -91,5 +91,4 @@ public function tearDown() parent::tearDown(); } - } diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index a35ec175a..18eb58e55 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -21,7 +21,15 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache\Storage\Adapter\AdapterInterface, +use Zend\Cache\Storage\IterableInterface, + Zend\Cache\Storage\IteratorInterface, + Zend\Cache\Storage\StorageInterface, + Zend\Cache\Storage\ClearExpiredInterface, + Zend\Cache\Storage\ClearByNamespaceInterface, + Zend\Cache\Storage\ClearByPrefixInterface, + Zend\Cache\Storage\FlushableInterface, + Zend\Cache\Storage\OptimizableInterface, + Zend\Cache\Storage\TagableInterface, Zend\Cache, Zend\Stdlib\ErrorHandler; @@ -43,7 +51,7 @@ abstract class CommonAdapterTest extends \PHPUnit_Framework_TestCase /** * The storage adapter * - * @var AdapterInterface + * @var StorageInterface */ protected $_storage; @@ -60,7 +68,7 @@ abstract class CommonAdapterTest extends \PHPUnit_Framework_TestCase public function setUp() { $this->assertInstanceOf( - 'Zend\Cache\Storage\Adapter\AdapterInterface', + 'Zend\Cache\Storage\StorageInterface', $this->_storage, 'Storage adapter instance is needed for tests' ); @@ -276,12 +284,12 @@ public function testGetItemSetsSuccessFlag() $success = null; // $success = false on get missing item - $this->_storage->getItem('unknown', array(), $success); + $this->_storage->getItem('unknown', $success); $this->assertFalse($success); // $success = true on get valid item $this->_storage->setItem('test', 'test'); - $this->_storage->getItem('test', array(), $success); + $this->_storage->getItem('test', $success); $this->assertTrue($success); } @@ -522,88 +530,6 @@ public function testSetGetHasAndRemoveItemsWithNamespace() } } - public function testSetGetHasAndRemoveItemWithSpecificNamespace() - { - $this->_options->setNamespace('defaultns'); - - // write "key" without a namespace - $this->assertTrue( $this->_storage->setItem('key', 'nons')); - - // write "key" with a default namespace - $this->assertTrue( $this->_storage->setItem('key', 'ns1', array('namespace' => 'ns1'))); - - // write "key" with an other default namespace - $this->assertTrue( $this->_storage->setItem('key', 'ns2', array('namespace' => 'ns2'))); - - // test value of ns2 - $this->assertEquals('ns2', $this->_storage->getItem('key', array('namespace' => 'ns2'))); - - // test value of ns1 - $this->assertEquals('ns1', $this->_storage->getItem('key', array('namespace' => 'ns1'))); - - // test value without namespace - $this->assertEquals('nons', $this->_storage->getItem('key')); - - // remove item without namespace - $this->assertTrue($this->_storage->removeItem('key')); - $this->assertFalse($this->_storage->hasItem('key')); - - // remove item of ns1 - $this->assertTrue($this->_storage->removeItem('key', array('namespace' => 'ns1'))); - $this->assertFalse($this->_storage->hasItem('key', array('namespace' => 'ns1'))); - - // remove item of ns2 - $this->assertTrue($this->_storage->removeItem('key', array('namespace' => 'ns2'))); - $this->assertFalse($this->_storage->hasItem('key', array('namespace' => 'ns2'))); - } - - public function testSetGetHasAndRemoveItemsWithSpecificNamespace() - { - $this->_options->setNamespace('defaultns'); - - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3', - ); - - $this->assertSame(array(), $this->_storage->setItems($items, array('namespace' => 'specificns'))); - $this->assertEquals(array(), $this->_storage->hasItems(array_keys($items))); - - $rs = $this->_storage->getItems(array_keys($items), array('namespace' => 'specificns')); - $this->assertInternalType('array', $rs); - foreach ($items as $key => $value) { - $this->assertArrayHasKey($key, $rs); - $this->assertEquals($value, $rs[$key]); - } - - - $rs = $this->_storage->hasItems(array_keys($items), array('namespace' => 'specificns')); - $this->assertInternalType('array', $rs); - $this->assertEquals(count($items), count($rs)); - foreach ($items as $key => $value) { - $this->assertContains($key, $rs); - } - - // remove the first and the last item - $this->assertSame(array('missing'), $this->_storage->removeItems(array('missing', 'key1', 'key3'), array('namespace' => 'specificns'))); - unset($items['key1'], $items['key3']); - - $rs = $this->_storage->getItems(array_keys($items), array('namespace' => 'specificns')); - $this->assertInternalType('array', $rs); - foreach ($items as $key => $value) { - $this->assertArrayHasKey($key, $rs); - $this->assertEquals($value, $rs[$key]); - } - - $rs = $this->_storage->hasItems(array_keys($items), array('namespace' => 'specificns')); - $this->assertInternalType('array', $rs); - $this->assertEquals(count($items), count($rs)); - foreach ($items as $key => $value) { - $this->assertContains($key, $rs); - } - } - public function testSetAndGetExpiredItem() { $capabilities = $this->_storage->getCapabilities(); @@ -623,10 +549,11 @@ public function testSetAndGetExpiredItem() $this->assertEquals('value', $this->_storage->getItem('key')); } + $this->_options->setTtl(0); if ($capabilities->getExpiredRead()) { - $this->assertEquals('value', $this->_storage->getItem('key', array('ttl' => 0))); + $this->assertEquals('value', $this->_storage->getItem('key')); } else { - $this->assertNull($this->_storage->getItem('key', array('ttl' => 0))); + $this->assertNull($this->_storage->getItem('key')); } } @@ -656,8 +583,9 @@ public function testSetAndGetExpiredItems() $this->assertEquals($items, $rs); } + $this->_options->setTtl(0); if ($capabilities->getExpiredRead()) { - $rs = $this->_storage->getItems(array_keys($items), array('ttl' => 0)); + $rs = $this->_storage->getItems(array_keys($items)); ksort($rs); $this->assertEquals($items, $rs); } @@ -792,7 +720,7 @@ public function testCheckAndSetItem() $success = null; $casToken = null; - $this->assertEquals('value', $this->_storage->getItem('key', array(), $success, $casToken)); + $this->assertEquals('value', $this->_storage->getItem('key', $success, $casToken)); $this->assertNotNull($casToken); $this->assertTrue($this->_storage->checkAndSetItem($casToken, 'key', 'newValue')); @@ -800,166 +728,6 @@ public function testCheckAndSetItem() $this->assertEquals('newValue', $this->_storage->getItem('key')); } - public function testGetDelayedAndFetch() - { - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3' - ); - - $this->assertSame(array(), $this->_storage->setItems($items)); - $this->assertTrue($this->_storage->getDelayed(array_keys($items))); - - $fetchedKeys = array(); - while ( $item = $this->_storage->fetch() ) { - $this->assertArrayHasKey('key', $item); - $this->assertArrayHasKey('value', $item); - - $this->assertArrayHasKey($item['key'], $items); - $this->assertEquals($items[$item['key']], $item['value']); - $fetchedKeys[] = $item['key']; - } - sort($fetchedKeys); - $this->assertEquals(array_keys($items), $fetchedKeys); - } - - public function testGetDelayedAndFetchAll() - { - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3' - ); - - $this->assertSame(array(), $this->_storage->setItems($items)); - $this->assertTrue($this->_storage->getDelayed(array_keys($items))); - - $fetchedItems = $this->_storage->fetchAll(); - $this->assertEquals(count($items), count($fetchedItems)); - foreach ($fetchedItems as $item) { - $this->assertArrayHasKey('key', $item); - $this->assertArrayHasKey('value', $item); - $this->assertEquals($items[$item['key']], $item['value']); - } - } - - public function testGetDelayedAndFetchAllWithSelectValue() - { - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3' - ); - - $this->assertSame(array(), $this->_storage->setItems($items)); - $this->assertTrue($this->_storage->getDelayed(array_keys($items), array( - 'select' => 'value' - ))); - - $fetchedItems = $this->_storage->fetchAll(); - $this->assertEquals(count($items), count($fetchedItems)); - foreach ($fetchedItems as $item) { - $this->assertArrayNotHasKey('key', $item); - $this->assertArrayHasKey('value', $item); - $this->assertContains($item['value'], $items); - } - } - - public function testGetDelayedAndFetchAllWithSelectInfo() - { - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3' - ); - - $this->assertSame(array(), $this->_storage->setItems($items)); - - $capabilities = $this->_storage->getCapabilities(); - $this->assertTrue($this->_storage->getDelayed(array_keys($items), array( - 'select' => $capabilities->getSupportedMetadata() - ))); - - $fetchedItems = $this->_storage->fetchAll(); - - $this->assertEquals(count($items), count($fetchedItems)); - foreach ($fetchedItems as $item) { - if (is_array($capabilities->getSupportedMetadata())) { - foreach ($capabilities->getSupportedMetadata() as $selectProperty) { - $this->assertArrayHasKey($selectProperty, $item); - } - } - } - } - - public function testGetDelayedWithCallback() - { - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3' - ); - - $this->assertSame(array(), $this->_storage->setItems($items)); - - $fetchedItems = array(); - $this->assertTrue($this->_storage->getDelayed(array_keys($items), array( - 'callback' => function($item) use (&$fetchedItems) { - $fetchedItems[] = $item; - }, - ))); - - // wait for callback - sleep(1); - - $this->assertEquals(count($items), count($fetchedItems)); - foreach ($fetchedItems as $item) { - $this->assertArrayHasKey('key', $item); - $this->assertArrayHasKey('value', $item); - $this->assertEquals($items[$item['key']], $item['value']); - } - } - - public function testGetDelayedWithCallbackAndSelectInfo() - { - $items = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3' - ); - - $this->assertSame(array(), $this->_storage->setItems($items)); - - $fetchedItems = array(); - $capabilities = $this->_storage->getCapabilities(); - $this->assertTrue($this->_storage->getDelayed(array_keys($items), array( - 'callback' => function($item) use (&$fetchedItems) { - $fetchedItems[] = $item; - }, - 'select' => $capabilities->getSupportedMetadata() - ))); - - // wait for callback - sleep(1); - - $this->assertEquals(count($items), count($fetchedItems)); - foreach ($fetchedItems as $item) { - foreach ($capabilities->getSupportedMetadata() as $selectProperty) { - $this->assertArrayHasKey($selectProperty, $item); - } - } - } - - public function testGetDelayedThrowExceptionOnActiveStatement() - { - $this->assertTrue($this->_storage->setItem('key', 'value')); - $this->assertTrue($this->_storage->getDelayed(array('key'))); - - $this->setExpectedException('Zend\Cache\Exception\ExceptionInterface'); - $this->_storage->getDelayed(array('key')); - } - public function testIncrementItem() { $this->assertTrue($this->_storage->setItem('counter', 10)); @@ -1076,278 +844,187 @@ public function testTouchItemsReturnsGivenKeysIfNonWritable() $this->assertSame(array('key'), $this->_storage->touchItems(array('key'))); } - public function testClearExpiredByNamespace() - { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getClearByNamespace()) { - $this->setExpectedException('Zend\Cache\Exception\RuntimeException'); - $this->_storage->clearByNamespace(AdapterInterface::MATCH_EXPIRED); - return; - } - - $ttl = $capabilities->getTtlPrecision(); - $this->_options->setTtl($ttl); - - $this->assertTrue($this->_storage->setItem('key1', 'value1')); - - // wait until the first item expired - $wait = $ttl + $capabilities->getTtlPrecision(); - usleep($wait * 2000000); - - $this->assertTrue($this->_storage->setItem('key2', 'value2')); - - $this->assertTrue($this->_storage->clearByNamespace(AdapterInterface::MATCH_EXPIRED)); - - if ($capabilities->getUseRequestTime()) { - $this->assertTrue($this->_storage->hasItem('key1')); - } else { - $this->assertFalse($this->_storage->hasItem('key1', array('ttl' => 0))); - } - - $this->assertTrue($this->_storage->hasItem('key2')); - } - - public function testClearActiveByNamespace() + public function testOptimize() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getClearByNamespace()) { - $this->setExpectedException('Zend\Cache\Exception\RuntimeException'); - $this->_storage->clearByNamespace(AdapterInterface::MATCH_ACTIVE); - return; + if ( !($this->_storage instanceof OptimizableInterface) ) { + $this->markTestSkipped("Storage doesn't implement OptimizableInterface"); } - $ttl = $capabilities->getTtlPrecision(); - $this->_options->setTtl($ttl); - - $this->assertTrue($this->_storage->setItem('key1', 'value1')); - - // wait until the first item expired - $wait = $ttl + $capabilities->getTtlPrecision(); - usleep($wait * 2000000); - - $this->assertTrue($this->_storage->setItem('key2', 'value2')); - - $this->assertTrue($this->_storage->clearByNamespace(AdapterInterface::MATCH_ACTIVE)); - - if ($capabilities->getExpiredRead() && !$capabilities->getUseRequestTime()) { - $this->assertTrue($this->_storage->hasItem('key1', array('ttl' => 0))); - } - $this->assertFalse($this->_storage->hasItem('key2', array('ttl' => 0))); + $this->assertTrue($this->_storage->optimize()); } - public function testClearAllByNamespace() + public function testIterator() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getClearByNamespace()) { - $this->setExpectedException('Zend\Cache\Exception\RuntimeException'); - $this->_storage->clearByNamespace(AdapterInterface::MATCH_ALL); - return; + if (!$this->_storage instanceof IterableInterface) { + $this->markTestSkipped("Storage doesn't implement IterableInterface"); } $items = array( 'key1' => 'value1', 'key2' => 'value2', - 'key3' => 'value3' ); - $namespaces = array('ns1', 'ns2'); - - foreach ($namespaces as $ns) { - $this->_options->setNamespace($ns); - foreach ($items as $k => $v) { - $this->assertTrue($this->_storage->setItem($ns.$k, $ns.$v)); - } - } - - $clearNs = array_shift($namespaces); - $this->_options->setNamespace($clearNs); - $this->assertTrue($this->_storage->clearByNamespace(AdapterInterface::MATCH_ALL)); + $this->assertSame(array(), $this->_storage->setItems($items)); - // wait - usleep($capabilities->getTtlPrecision() * 2000000); + // check iterator aggregate + $iterator = $this->_storage->getIterator(); + $this->assertInstanceOf('Zend\Cache\Storage\IteratorInterface', $iterator); + $this->assertSame(IteratorInterface::CURRENT_AS_KEY, $iterator->getMode()); + + // check mode CURRENT_AS_KEY + $iterator = $this->_storage->getIterator(); + $iterator->setMode(IteratorInterface::CURRENT_AS_KEY); + $keys = iterator_to_array($iterator, false); + sort($keys); + $this->assertSame(array_keys($items), $keys); + + // check mode CURRENT_AS_VALUE + $iterator = $this->_storage->getIterator(); + $iterator->setMode(IteratorInterface::CURRENT_AS_VALUE); + $result = iterator_to_array($iterator, true); + ksort($result); + $this->assertSame($items, $result); + } - foreach ($items as $k => $v) { - $this->assertFalse($this->_storage->hasItem($clearNs.$k)); + public function testFlush() + { + if ( !($this->_storage instanceof FlushableInterface) ) { + $this->markTestSkipped("Storage doesn't implement OptimizableInterface"); } - foreach ($namespaces as $ns) { - $this->_options->setNamespace($ns); - foreach ($items as $k => $v) { - $this->assertTrue($this->_storage->hasItem($ns.$k)); - } - } + $this->assertSame(array(), $this->_storage->setItems(array( + 'key1' => 'value1', + 'key2' => 'value2', + ))); + + $this->assertTrue($this->_storage->flush()); + $this->assertFalse($this->_storage->hasItem('key1')); + $this->assertFalse($this->_storage->hasItem('key2')); } - public function testClearAll() + public function testClearByPrefix() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getClearAllNamespaces()) { - $this->setExpectedException('Zend\Cache\Exception\ExceptionInterface'); - $this->_storage->clear(AdapterInterface::MATCH_ALL); - return; + if ( !($this->_storage instanceof ClearByPrefixInterface) ) { + $this->markTestSkipped("Storage doesn't implement ClearByPrefixInterface"); } - $items = array( + $this->assertSame(array(), $this->_storage->setItems(array( 'key1' => 'value1', 'key2' => 'value2', - 'key3' => 'value3' - ); - $namespaces = array('ns1', 'ns2'); - - foreach ($namespaces as $ns) { - $this->_options->setNamespace($ns); - foreach ($items as $k => $v) { - $this->assertTrue($this->_storage->setItem($ns.$k, $ns.$v)); - } - } - - $this->assertTrue($this->_storage->clear(AdapterInterface::MATCH_ALL)); - - // wait - usleep($capabilities->getTtlPrecision() * 2000000); + 'test' => 'value', + ))); - foreach ($namespaces as $ns) { - $this->_options->setNamespace($ns); - foreach ($items as $k => $v) { - $this->assertFalse($this->_storage->hasItem($ns.$k)); - } - } + $this->assertTrue($this->_storage->clearByPrefix('key')); + $this->assertFalse($this->_storage->hasItem('key1')); + $this->assertFalse($this->_storage->hasItem('key2')); + $this->assertTrue($this->_storage->hasItem('test')); } - public function testFindActive() + public function testClearByNamespace() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getIterable()) { - $this->markTestSkipped("Find isn't supported by this adapter"); + if ( !($this->_storage instanceof ClearByNamespaceInterface) ) { + $this->markTestSkipped("Storage doesn't implement ClearByNamespaceInterface"); } - $this->_options->setTtl($capabilities->getTtlPrecision()); - + // write 2 items of 2 different namespaces + $this->_options->setNamespace('ns1'); $this->assertTrue($this->_storage->setItem('key1', 'value1')); + $this->_options->setNamespace('ns2'); $this->assertTrue($this->_storage->setItem('key2', 'value2')); - // wait until first 2 items expired - usleep(($capabilities->getTtlPrecision() * 1000000) + 1000000); - - $this->assertTrue($this->_storage->setItem('key3', 'value3')); - $this->assertTrue($this->_storage->setItem('key4', 'value4')); - - $this->assertTrue($this->_storage->find(AdapterInterface::MATCH_ACTIVE)); - - if ($capabilities->getUseRequestTime()) { - $expectedItems = array( - 'key1' => 'value1', - 'key2' => 'value2', - 'key3' => 'value3', - 'key4' => 'value4' - ); - } else { - $expectedItems = array( - 'key3' => 'value3', - 'key4' => 'value4' - ); - } - - $actualItems = array(); - while (($item = $this->_storage->fetch()) !== false) { - // check $item - $this->assertArrayHasKey('key', $item); - $this->assertArrayHasKey('value', $item); + // clear unknown namespace should return true but clear nothing + $this->assertTrue($this->_storage->clearByNamespace('unknown')); + $this->_options->setNamespace('ns1'); + $this->assertTrue($this->_storage->hasItem('key1')); + $this->_options->setNamespace('ns2'); + $this->assertTrue($this->_storage->hasItem('key2')); - $actualItems[ $item['key'] ] = $item['value']; - } + // clear "ns1" + $this->assertTrue($this->_storage->clearByNamespace('ns1')); + $this->_options->setNamespace('ns1'); + $this->assertFalse($this->_storage->hasItem('key1')); + $this->_options->setNamespace('ns2'); + $this->assertTrue($this->_storage->hasItem('key2')); - ksort($actualItems); - $this->assertEquals($expectedItems, $actualItems); + // clear "ns2" + $this->assertTrue($this->_storage->clearByNamespace('ns2')); + $this->_options->setNamespace('ns1'); + $this->assertFalse($this->_storage->hasItem('key1')); + $this->_options->setNamespace('ns2'); + $this->assertFalse($this->_storage->hasItem('key2')); } - public function testFindExpired() + public function testClearExpired() { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getIterable()) { - $this->markTestSkipped("Find isn't supported by this adapter"); + if ( !($this->_storage instanceof ClearExpiredInterface) ) { + $this->markTestSkipped("Storage doesn't implement ClearExpiredInterface"); } - $this->_options->setTtl($capabilities->getTtlPrecision()); + $capabilities = $this->_storage->getCapabilities(); + $ttl = $capabilities->getTtlPrecision(); + $this->_options->setTtl($ttl); $this->assertTrue($this->_storage->setItem('key1', 'value1')); - $this->assertTrue($this->_storage->setItem('key2', 'value2')); - // wait until first 2 items expired - usleep($capabilities->getTtlPrecision() * 2000000); + // wait until the first item expired + $wait = $ttl + $capabilities->getTtlPrecision(); + usleep($wait * 2000000); - $this->assertTrue($this->_storage->setItem('key3', 'value3')); - $this->assertTrue($this->_storage->setItem('key4', 'value4')); + $this->assertTrue($this->_storage->setItem('key2', 'value2')); - $this->assertTrue($this->_storage->find(AdapterInterface::MATCH_EXPIRED)); + $this->assertTrue($this->_storage->clearExpired()); - if ($capabilities->getExpiredRead() && !$capabilities->getUseRequestTime()) { - $expectedItems = array( - 'key1' => 'value1', - 'key2' => 'value2' - ); + if ($capabilities->getUseRequestTime()) { + $this->assertTrue($this->_storage->hasItem('key1')); } else { - $expectedItems = array(); - } - - $actualItems = array(); - while (($item = $this->_storage->fetch()) !== false) { - // check $item - $this->assertArrayHasKey('key', $item); - $this->assertArrayHasKey('value', $item); - $this->assertEquals(2, count($item)); - - $actualItems[ $item['key'] ] = $item['value']; + $this->assertFalse($this->_storage->hasItem('key1', array('ttl' => 0))); } - ksort($actualItems); - $this->assertEquals($expectedItems, $actualItems); + $this->assertTrue($this->_storage->hasItem('key2')); } - /* - public function testGetCapacity() + public function testTagable() { - $capacity = $this->_storage->getCapacity(); + if ( !($this->_storage instanceof TagableInterface) ) { + $this->markTestSkipped("Storage doesn't implement TagableInterface"); + } - $this->assertArrayHasKey('total', $capacity); - $this->assertInternalType('numeric', $capacity['total']); + $capabilities = $this->_storage->getCapabilities(); + $ttl = $capabilities->getTtlPrecision(); + $this->_options->setTtl($ttl); - $this->assertArrayHasKey('free', $capacity); - $this->assertInternalType('numeric', $capacity['free']); + $this->assertSame(array(), $this->_storage->setItems(array( + 'key1' => 'value1', + 'key2' => 'value2', + 'key3' => 'value3', + ))); - $this->assertGreaterThanOrEqual( - $capacity['free'], $capacity['total'], - "The total storage space must be greater or equal than the free space" - ); - } + $this->assertTrue($this->_storage->setTags('key1', array('tag1a', 'tag1b'))); + $this->assertTrue($this->_storage->setTags('key2', array('tag2a', 'tag2b'))); + $this->assertTrue($this->_storage->setTags('key3', array('tag3a', 'tag3b'))); + $this->assertFalse($this->_storage->setTags('missing', array('tag'))); - public function testOptimizeSimpleCall() - { - $rs = $this->_storage->optimize(); - $this->assertTrue($rs); - } + // return tags + $tags = $this->_storage->getTags('key1'); + $this->assertInternalType('array', $tags); + sort($tags); + $this->assertSame(array('tag1a', 'tag1b'), $tags); - public function testTagsAreUsedWhenCaching() - { - $capabilities = $this->_storage->getCapabilities(); - if (!$capabilities->getTagging()) { - $this->markTestSkipped("Tags are not supported by this adapter"); - } + // this should remove nothing + $this->assertTrue($this->_storage->clearByTags(array('tag1a', 'tag2a'))); + $this->assertTrue($this->_storage->hasItem('key1')); + $this->assertTrue($this->_storage->hasItem('key2')); + $this->assertTrue($this->_storage->hasItem('key3')); - // Ensure we don't have expired items in the cache for this test - $this->_options->setTtl(60); - $this->_storage->setItem('someitem', 'somevalue', array('tags' => array('foo'))); - $this->assertTrue($this->_storage->find(AdapterInterface::MATCH_TAGS_OR, array('tags' => array('foo')))); - $actualItems = array(); - while (($item = $this->_storage->fetch()) !== false) { - // check $item - $this->assertArrayHasKey('key', $item); - $this->assertArrayHasKey('value', $item); - - $actualItems[ $item['key'] ] = $item['value']; - } - $this->assertEquals(1, count($actualItems)); - $this->assertArrayHasKey('someitem', $actualItems); - $this->assertEquals('somevalue', $actualItems['someitem']); + // this should remove key1 and key2 + $this->assertTrue($this->_storage->clearByTags(array('tag1a', 'tag2b'), true)); + $this->assertFalse($this->_storage->hasItem('key1')); + $this->assertFalse($this->_storage->hasItem('key2')); + $this->assertTrue($this->_storage->hasItem('key3')); + + // this should remove key3 + $this->assertTrue($this->_storage->clearByTags(array('tag3a', 'tag3b'), true)); + $this->assertFalse($this->_storage->hasItem('key1')); + $this->assertFalse($this->_storage->hasItem('key2')); + $this->assertFalse($this->_storage->hasItem('key3')); } - */ } diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index 63ade8961..87949e260 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -101,8 +101,8 @@ public function testNoOptionsSetsDefaultServer() public function tearDown() { - if (!empty($this->_storage)) { - $this->_storage->clear(); + if ($this->_storage) { + $this->_storage->flush(); } parent::tearDown(); diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index 9bea8fd26..81450cd84 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -43,12 +43,11 @@ public function setUp() parent::setUp(); } - public function testThrowOutOfCapacityException() + public function testThrowOutOfSpaceException() { $this->_options->setMemoryLimit(memory_get_usage(true) - 8); - $this->setExpectedException('Zend\Cache\Exception\OutOfCapacityException'); + $this->setExpectedException('Zend\Cache\Exception\OutOfSpaceException'); $this->_storage->addItem('test', 'test'); } - } diff --git a/test/Storage/Adapter/WinCacheTest.php b/test/Storage/Adapter/WinCacheTest.php index 712a39d0a..a3d5cbd53 100644 --- a/test/Storage/Adapter/WinCacheTest.php +++ b/test/Storage/Adapter/WinCacheTest.php @@ -70,5 +70,4 @@ public function tearDown() parent::tearDown(); } - } diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php index 4de5b63e5..1e0dbb7b8 100644 --- a/test/Storage/Adapter/ZendServerDiskTest.php +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -63,5 +63,4 @@ public function tearDown() parent::tearDown(); } - } diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index 54c091820..fbf90e654 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -68,5 +68,4 @@ public function tearDown() parent::tearDown(); } - } diff --git a/test/Storage/Plugin/ClearByFactorTest.php b/test/Storage/Plugin/ClearExpiredByFactorTest.php similarity index 57% rename from test/Storage/Plugin/ClearByFactorTest.php rename to test/Storage/Plugin/ClearExpiredByFactorTest.php index bf14fac56..d1b179f28 100644 --- a/test/Storage/Plugin/ClearByFactorTest.php +++ b/test/Storage/Plugin/ClearExpiredByFactorTest.php @@ -3,10 +3,10 @@ namespace ZendTest\Cache\Storage\Plugin; use Zend\Cache, Zend\Cache\Storage\PostEvent, - ZendTest\Cache\Storage\TestAsset\MockAdapter, + ZendTest\Cache\Storage\TestAsset\ClearExpiredMockAdapter, ArrayObject; -class ClearByFactorTest extends CommonPluginTest +class ClearExpiredByFactorTest extends CommonPluginTest { /** @@ -18,11 +18,11 @@ class ClearByFactorTest extends CommonPluginTest public function setUp() { - $this->_adapter = new MockAdapter(); + $this->_adapter = new ClearExpiredMockAdapter(); $this->_options = new Cache\Storage\Plugin\PluginOptions(array( 'clearing_factor' => 1, )); - $this->_plugin = new Cache\Storage\Plugin\ClearByFactor(); + $this->_plugin = new Cache\Storage\Plugin\ClearExpiredByFactor(); $this->_plugin->setOptions($this->_options); parent::setUp(); @@ -34,10 +34,10 @@ public function testAddPlugin() // check attached callbacks $expectedListeners = array( - 'setItem.post' => 'clearByFactor', - 'setItems.post' => 'clearByFactor', - 'addItem.post' => 'clearByFactor', - 'addItems.post' => 'clearByFactor', + 'setItem.post' => 'clearExpiredByFactor', + 'setItems.post' => 'clearExpiredByFactor', + 'addItem.post' => 'clearExpiredByFactor', + 'addItems.post' => 'clearExpiredByFactor', ); foreach ($expectedListeners as $eventName => $expectedCallbackMethod) { $listeners = $this->_adapter->events()->getListeners($eventName); @@ -63,50 +63,24 @@ public function testRemovePlugin() $this->assertEquals(0, count($this->_adapter->events()->getEvents())); } - public function testClearByFactorUsingNamespace() + public function testClearExpiredByFactor() { - $adapter = $this->getMock(get_class($this->_adapter), array('clearByNamespace')); + $adapter = $this->getMock(get_class($this->_adapter), array('clearExpired')); $this->_options->setClearingFactor(1); - $this->_options->setClearByNamespace(true); - // test optimize will be called + // test clearByNamespace will be called $adapter ->expects($this->once()) - ->method('clearByNamespace') + ->method('clearExpired') ->will($this->returnValue(true)); // call event callback $result = true; $event = new PostEvent('setItem.post', $adapter, new ArrayObject(array( - 'options' => array(), + 'options' => array(), )), $result); - - $this->_plugin->clearByFactor($event); - - $this->assertTrue($event->getResult()); - } - - public function testClearByFactorAllNamespaces() - { - $adapter = $this->getMock(get_class($this->_adapter), array('clear')); - $this->_options->setClearingFactor(1); - $this->_options->setClearByNamespace(false); - - // test optimize will be called - $adapter - ->expects($this->once()) - ->method('clear') - ->will($this->returnValue(true)); - - // call event callback - $result = true; - $event = new PostEvent('setItem.post', $adapter, new ArrayObject(array( - 'options' => array(), - )), $result); - - $this->_plugin->clearByFactor($event); + $this->_plugin->clearExpiredByFactor($event); $this->assertTrue($event->getResult()); } - } diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php index efac4fcff..49321c3eb 100644 --- a/test/Storage/Plugin/ExceptionHandlerTest.php +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -41,12 +41,6 @@ public function testAddPlugin() 'getMetadata.exception' => 'onException', 'getMetadatas.exception' => 'onException', - 'getDelayed.exception' => 'onException', - 'find.exception' => 'onException', - - 'fetch.exception' => 'onException', - 'fetchAll.exception' => 'onException', - 'setItem.exception' => 'onException', 'setItems.exception' => 'onException', @@ -69,12 +63,6 @@ public function testAddPlugin() 'decrementItem.exception' => 'onException', 'decrementItems.exception' => 'onException', - - 'clear.exception' => 'onException', - 'clearByNamespace.exception' => 'onException', - - 'optimize.exception' => 'onException', - 'getCapacity.exception' => 'onException', ); foreach ($expectedListeners as $eventName => $expectedCallbackMethod) { $listeners = $this->_adapter->events()->getListeners($eventName); @@ -138,5 +126,4 @@ public function testDontThrowException() $this->assertFalse($event->getThrowException()); $this->assertSame('test', $event->getResult()); } - } diff --git a/test/Storage/Plugin/IgnoreUserAbortTest.php b/test/Storage/Plugin/IgnoreUserAbortTest.php index 4b64ebf3d..3eccce91c 100644 --- a/test/Storage/Plugin/IgnoreUserAbortTest.php +++ b/test/Storage/Plugin/IgnoreUserAbortTest.php @@ -125,5 +125,4 @@ public function testRemovePlugin() // no events should be attached $this->assertEquals(0, count($this->_adapter->events()->getEvents())); } - } diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index b011051d9..9789f63ed 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -3,7 +3,7 @@ namespace ZendTest\Cache\Storage\Plugin; use Zend\Cache, Zend\Cache\Storage\PostEvent, - ZendTest\Cache\Storage\TestAsset\MockAdapter, + ZendTest\Cache\Storage\TestAsset\OptimizableMockAdapter, ArrayObject; class OptimizeByFactorTest extends CommonPluginTest @@ -18,7 +18,7 @@ class OptimizeByFactorTest extends CommonPluginTest public function setUp() { - $this->_adapter = new MockAdapter(); + $this->_adapter = new OptimizableMockAdapter(); $this->_options = new Cache\Storage\Plugin\PluginOptions(array( 'optimizing_factor' => 1, )); @@ -32,10 +32,8 @@ public function testAddPlugin() // check attached callbacks $expectedListeners = array( - 'removeItem.post' => 'optimizeByFactor', - 'removeItems.post' => 'optimizeByFactor', - 'clear.post' => 'optimizeByFactor', - 'clearByNamespace.post' => 'optimizeByFactor', + 'removeItem.post' => 'optimizeByFactor', + 'removeItems.post' => 'optimizeByFactor', ); foreach ($expectedListeners as $eventName => $expectedCallbackMethod) { $listeners = $this->_adapter->events()->getListeners($eventName); @@ -80,5 +78,4 @@ public function testOptimizeByFactor() $this->assertTrue($event->getResult()); } - } diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index fb5bcce5e..8ebf853c4 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -61,9 +61,6 @@ public function testAddPlugin() 'getItem.post' => 'onReadItemPost', 'getItems.post' => 'onReadItemsPost', - 'fetch.post' => 'onFetchPost', - 'fetchAll.post' => 'onFetchAllPost', - 'setItem.pre' => 'onWriteItemPre', 'setItems.pre' => 'onWriteItemsPre', 'addItem.pre' => 'onWriteItemPre', @@ -135,5 +132,4 @@ public function testUnserializeOnReadItems() $this->assertSame(123, $values['key1']); $this->assertSame(456, $values['key2']); } - } diff --git a/test/Storage/TestAsset/ClearExpiredMockAdapter.php b/test/Storage/TestAsset/ClearExpiredMockAdapter.php new file mode 100644 index 000000000..2e9d8bd71 --- /dev/null +++ b/test/Storage/TestAsset/ClearExpiredMockAdapter.php @@ -0,0 +1,12 @@ +calledEvents; } - } diff --git a/test/Storage/TestAsset/OptimizableMockAdapter.php b/test/Storage/TestAsset/OptimizableMockAdapter.php new file mode 100644 index 000000000..04e08862a --- /dev/null +++ b/test/Storage/TestAsset/OptimizableMockAdapter.php @@ -0,0 +1,12 @@ + $adapter, @@ -127,7 +127,7 @@ public function testFactoryWithPlugins() // test plugin structure $i = 0; - foreach ($cache->getPlugins() as $plugin) { + foreach ($cache->getPluginRegistry() as $plugin) { $this->assertInstanceOf('Zend\Cache\Storage\Plugin\\' . $plugins[$i++], $plugin); } } @@ -147,7 +147,7 @@ public function testFactoryWithPluginsAndOptionsArray() 'Serializer', // plugin as name-options pair - 'ClearByFactor' => array( + 'ClearExpiredByFactor' => array( 'clearing_factor' => 1, ), @@ -172,14 +172,14 @@ public function testFactoryWithPluginsAndOptionsArray() $this->assertEquals('test', $storage->getOptions()->getNamespace()); // test plugin structure - foreach ($storage->getPlugins() as $i => $plugin) { + foreach ($storage->getPluginRegistry() as $plugin) { // test plugin options $pluginClass = get_class($plugin); switch ($pluginClass) { - case 'Zend\Cache\Storage\Plugin\ClearByFactor': + case 'Zend\Cache\Storage\Plugin\ClearExpiredByFactor': $this->assertSame( - $factory['plugins']['ClearByFactor']['clearing_factor'], + $factory['plugins']['ClearExpiredByFactor']['clearing_factor'], $plugin->getOptions()->getClearingFactor() ); break; @@ -197,5 +197,4 @@ public function testFactoryWithPluginsAndOptionsArray() } } - } diff --git a/test/TestAsset/DummyPattern.php b/test/TestAsset/DummyPattern.php index d71e3dbdf..7fb86010b 100644 --- a/test/TestAsset/DummyPattern.php +++ b/test/TestAsset/DummyPattern.php @@ -18,5 +18,4 @@ public function getDummyOption() { return $this->_dummyOption; } - } diff --git a/test/TestAsset/DummyStoragePlugin.php b/test/TestAsset/DummyStoragePlugin.php index ec5d88532..f65f55347 100644 --- a/test/TestAsset/DummyStoragePlugin.php +++ b/test/TestAsset/DummyStoragePlugin.php @@ -13,5 +13,4 @@ public function __construct($options = array()) { $this->setOptions($options); } - } diff --git a/test/UtilsTest.php b/test/UtilsTest.php index 99c4673a1..99b49ca7c 100644 --- a/test/UtilsTest.php +++ b/test/UtilsTest.php @@ -30,11 +30,6 @@ class UtilsTest extends \PHPUnit_Framework_TestCase { - public function testGetDiskCapacity() - { - $this->_assertCapacity(Utils::getDiskCapacity(__DIR__)); - } - public function testGetPhpMemoryCapacity() { $this->_assertCapacity(Utils::getPhpMemoryCapacity()); @@ -69,5 +64,4 @@ public function testGenerateHashStrlenRaw() { $this->assertEquals(pack('l', strlen('test')), Utils::generateHash('strlen', 'test', true)); } - } From 25967c67adc42df171a10f88d2cdc63eb2d4b200 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 31 May 2012 09:33:59 +0200 Subject: [PATCH 270/311] format exception classes --- src/Exception/BadMethodCallException.php | 5 +++-- src/Exception/InvalidArgumentException.php | 5 +++-- src/Exception/LogicException.php | 4 +++- src/Exception/OutOfSpaceException.php | 4 +++- src/Exception/RuntimeException.php | 4 +++- src/Exception/UnexpectedValueException.php | 5 +++-- src/Exception/UnsupportedMethodCallException.php | 5 +++-- 7 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index 4aa41fa93..f1c5ee9a7 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -26,7 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class BadMethodCallException extends \BadMethodCallException implements - ExceptionInterface +class BadMethodCallException + extends \BadMethodCallException + implements ExceptionInterface { } diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index c051e6995..80ffa308e 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -26,7 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class InvalidArgumentException extends \InvalidArgumentException implements - ExceptionInterface +class InvalidArgumentException + extends \InvalidArgumentException + implements ExceptionInterface { } diff --git a/src/Exception/LogicException.php b/src/Exception/LogicException.php index 6d4f4b5f3..ae122152e 100644 --- a/src/Exception/LogicException.php +++ b/src/Exception/LogicException.php @@ -26,6 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class LogicException extends \LogicException implements ExceptionInterface +class LogicException + extends \LogicException + implements ExceptionInterface { } diff --git a/src/Exception/OutOfSpaceException.php b/src/Exception/OutOfSpaceException.php index 290592c8d..847843b2d 100644 --- a/src/Exception/OutOfSpaceException.php +++ b/src/Exception/OutOfSpaceException.php @@ -26,6 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class OutOfSpaceException extends \OverflowException implements ExceptionInterface +class OutOfSpaceException + extends \OverflowException + implements ExceptionInterface { } diff --git a/src/Exception/RuntimeException.php b/src/Exception/RuntimeException.php index 432113373..e4d939ac1 100644 --- a/src/Exception/RuntimeException.php +++ b/src/Exception/RuntimeException.php @@ -26,6 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class RuntimeException extends \RuntimeException implements ExceptionInterface +class RuntimeException + extends \RuntimeException + implements ExceptionInterface { } diff --git a/src/Exception/UnexpectedValueException.php b/src/Exception/UnexpectedValueException.php index 455da7c99..98581aa65 100644 --- a/src/Exception/UnexpectedValueException.php +++ b/src/Exception/UnexpectedValueException.php @@ -26,7 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class UnexpectedValueException extends \UnexpectedValueException implements - ExceptionInterface +class UnexpectedValueException + extends \UnexpectedValueException + implements ExceptionInterface { } diff --git a/src/Exception/UnsupportedMethodCallException.php b/src/Exception/UnsupportedMethodCallException.php index 73a999b00..d9aa61080 100644 --- a/src/Exception/UnsupportedMethodCallException.php +++ b/src/Exception/UnsupportedMethodCallException.php @@ -26,7 +26,8 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class UnsupportedMethodCallException extends \BadMethodCallException implements - ExceptionInterface +class UnsupportedMethodCallException + extends \BadMethodCallException + implements ExceptionInterface { } From 96613be8f9828b1027e55cd64c599deaa5e4068e Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 31 May 2012 09:47:26 +0200 Subject: [PATCH 271/311] disabled memory_limit of memory cache storage for callback pattern tests --- test/Pattern/CallbackCacheTest.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index 9bddc3947..d5082e05c 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -72,7 +72,9 @@ class CallbackCacheTest extends CommonPatternTest public function setUp() { - $this->_storage = new Cache\Storage\Adapter\Memory(); + $this->_storage = new Cache\Storage\Adapter\Memory(array( + 'memory_limit' => 0 + )); $this->_options = new Cache\Pattern\PatternOptions(array( 'storage' => $this->_storage, )); From f77af73d199fac37f88273059917da6b37448e20 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 31 May 2012 09:50:01 +0200 Subject: [PATCH 272/311] disabled memory_limit of memory cache storage for pattern tests --- test/Pattern/ClassCacheTest.php | 4 +++- test/Pattern/ObjectCacheTest.php | 4 +++- test/Pattern/OutputCacheTest.php | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 09fd02ad8..c7dc08e06 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -63,7 +63,9 @@ class ClassCacheTest extends CommonPatternTest public function setUp() { - $this->_storage = new Cache\Storage\Adapter\Memory(); + $this->_storage = new Cache\Storage\Adapter\Memory(array( + 'memory_limit' => 0 + )); $this->_options = new Cache\Pattern\PatternOptions(array( 'class' => __NAMESPACE__ . '\TestClassCache', 'storage' => $this->_storage, diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index 99b2aa9ab..211e830c4 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -71,7 +71,9 @@ class ObjectCacheTest extends CommonPatternTest public function setUp() { $class = __NAMESPACE__ . '\TestObjectCache'; - $this->_storage = new Cache\Storage\Adapter\Memory(); + $this->_storage = new Cache\Storage\Adapter\Memory(array( + 'memory_limit' => 0 + )); $this->_options = new Cache\Pattern\PatternOptions(array( 'object' => new $class(), 'storage' => $this->_storage, diff --git a/test/Pattern/OutputCacheTest.php b/test/Pattern/OutputCacheTest.php index 3b28fe1b1..3407197f3 100644 --- a/test/Pattern/OutputCacheTest.php +++ b/test/Pattern/OutputCacheTest.php @@ -48,7 +48,9 @@ class OutputCacheTest extends CommonPatternTest public function setUp() { - $this->_storage = new Cache\Storage\Adapter\Memory(); + $this->_storage = new Cache\Storage\Adapter\Memory(array( + 'memory_limit' => 0 + )); $this->_options = new Cache\Pattern\PatternOptions(array( 'storage' => $this->_storage, )); From bf97fd20580cc0b2a26dc88c6e6876c0bef89d8a Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Thu, 31 May 2012 22:15:07 +0200 Subject: [PATCH 273/311] use of offsetExists instead of isset --- src/Storage/Adapter/AbstractAdapter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 14dae6458..0df497b10 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -381,9 +381,9 @@ public function getItem($key, & $success = null, & $casToken = null) return $eventRs->last(); } - if (isset($args['success'], $args['casToken'])) { + if ($args->offsetExists('success') && $args->offsetExists('casToken')) { $result = $this->internalGetItem($args['key'], $args['success'], $args['casToken']); - } elseif (isset($args['success'])) { + } elseif ($args->offsetExists('success')) { $result = $this->internalGetItem($args['key'], $args['success']); } else { $result = $this->internalGetItem($args['key']); From ccb455e575faf1b77b167517d08836f672633bd9 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Sat, 2 Jun 2012 13:21:07 +0200 Subject: [PATCH 274/311] PHP 5.3.3: Fatal error: Can't inherit abstract function IteratorAggregate::getIterator() (previously declared abstract in Zend\Cache\Storage\IterableInterface) --- src/Storage/IterableInterface.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Storage/IterableInterface.php b/src/Storage/IterableInterface.php index 344d8551d..8a35497d8 100644 --- a/src/Storage/IterableInterface.php +++ b/src/Storage/IterableInterface.php @@ -35,5 +35,7 @@ interface IterableInterface extends \IteratorAggregate * * @return IteratorInterface */ - public function getIterator(); + // PHP 5.3.3: Fatal error: Can't inherit abstract function IteratorAggregate::getIterator() + // (previously declared abstract in Zend\Cache\Storage\IterableInterface) + //public function getIterator(); } From 5417fc2a033dad8ef1b83f24141377f82e569e58 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 13 Jun 2012 04:18:07 +0200 Subject: [PATCH 275/311] phpdoc: Use class level method definition to re-define method return type --- src/Storage/IterableInterface.php | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/Storage/IterableInterface.php b/src/Storage/IterableInterface.php index 8a35497d8..5197c4fcf 100644 --- a/src/Storage/IterableInterface.php +++ b/src/Storage/IterableInterface.php @@ -27,15 +27,9 @@ * @subpackage Storage * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License + * + * @method IteratorInterface getIterator() Get the storage iterator */ interface IterableInterface extends \IteratorAggregate { - /** - * Get the storage iterator - * - * @return IteratorInterface - */ - // PHP 5.3.3: Fatal error: Can't inherit abstract function IteratorAggregate::getIterator() - // (previously declared abstract in Zend\Cache\Storage\IterableInterface) - //public function getIterator(); } From 1d190a2fd2a33252039e634956b39a349186ae60 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Wed, 13 Jun 2012 11:49:58 -0500 Subject: [PATCH 276/311] [zendframework/zf2#1403] CS cleanup of exceptions - following PSR-1/2, put extends and implements keywords on same line; list interfaces implemented on separate lines following, only if line length exceeds recommended soft limits --- src/Exception/BadMethodCallException.php | 5 ++--- src/Exception/InvalidArgumentException.php | 5 ++--- src/Exception/LogicException.php | 4 +--- src/Exception/OutOfSpaceException.php | 4 +--- src/Exception/RuntimeException.php | 4 +--- src/Exception/UnexpectedValueException.php | 5 ++--- src/Exception/UnsupportedMethodCallException.php | 5 ++--- 7 files changed, 11 insertions(+), 21 deletions(-) diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index f1c5ee9a7..4aa41fa93 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -26,8 +26,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class BadMethodCallException - extends \BadMethodCallException - implements ExceptionInterface +class BadMethodCallException extends \BadMethodCallException implements + ExceptionInterface { } diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index 80ffa308e..c051e6995 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -26,8 +26,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class InvalidArgumentException - extends \InvalidArgumentException - implements ExceptionInterface +class InvalidArgumentException extends \InvalidArgumentException implements + ExceptionInterface { } diff --git a/src/Exception/LogicException.php b/src/Exception/LogicException.php index ae122152e..6d4f4b5f3 100644 --- a/src/Exception/LogicException.php +++ b/src/Exception/LogicException.php @@ -26,8 +26,6 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class LogicException - extends \LogicException - implements ExceptionInterface +class LogicException extends \LogicException implements ExceptionInterface { } diff --git a/src/Exception/OutOfSpaceException.php b/src/Exception/OutOfSpaceException.php index 847843b2d..290592c8d 100644 --- a/src/Exception/OutOfSpaceException.php +++ b/src/Exception/OutOfSpaceException.php @@ -26,8 +26,6 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class OutOfSpaceException - extends \OverflowException - implements ExceptionInterface +class OutOfSpaceException extends \OverflowException implements ExceptionInterface { } diff --git a/src/Exception/RuntimeException.php b/src/Exception/RuntimeException.php index e4d939ac1..432113373 100644 --- a/src/Exception/RuntimeException.php +++ b/src/Exception/RuntimeException.php @@ -26,8 +26,6 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class RuntimeException - extends \RuntimeException - implements ExceptionInterface +class RuntimeException extends \RuntimeException implements ExceptionInterface { } diff --git a/src/Exception/UnexpectedValueException.php b/src/Exception/UnexpectedValueException.php index 98581aa65..455da7c99 100644 --- a/src/Exception/UnexpectedValueException.php +++ b/src/Exception/UnexpectedValueException.php @@ -26,8 +26,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class UnexpectedValueException - extends \UnexpectedValueException - implements ExceptionInterface +class UnexpectedValueException extends \UnexpectedValueException implements + ExceptionInterface { } diff --git a/src/Exception/UnsupportedMethodCallException.php b/src/Exception/UnsupportedMethodCallException.php index d9aa61080..73a999b00 100644 --- a/src/Exception/UnsupportedMethodCallException.php +++ b/src/Exception/UnsupportedMethodCallException.php @@ -26,8 +26,7 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class UnsupportedMethodCallException - extends \BadMethodCallException - implements ExceptionInterface +class UnsupportedMethodCallException extends \BadMethodCallException implements + ExceptionInterface { } From 688f1426d13722834a8cb65fcb5ff4205c065b7f Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Thu, 21 Jun 2012 23:44:20 -0500 Subject: [PATCH 277/311] Better capabilities surrounding sharing - Added flag "sharedByDefault" to ServiceManager implementation, set to true by default - Disabling the flag disables storing created instances for re-use - Used with a variety of components: Cache, Crypt, Paginator, and the static variants of Filter and Validator - Cannot re-set the flag if allowOverride is false --- src/PatternPluginManager.php | 9 +-------- src/Storage/AdapterPluginManager.php | 15 +-------------- src/Storage/PluginManager.php | 8 +------- 3 files changed, 3 insertions(+), 29 deletions(-) diff --git a/src/PatternPluginManager.php b/src/PatternPluginManager.php index d25c87f6d..fd60d9f00 100644 --- a/src/PatternPluginManager.php +++ b/src/PatternPluginManager.php @@ -55,14 +55,7 @@ class PatternPluginManager extends AbstractPluginManager * * @var array */ - protected $shared = array( - 'callback' => false, - 'capture' => false, - 'class' => false, - 'object' => false, - 'output' => false, - 'page' => false, - ); + protected $shareByDefault = false; /** * Validate the plugin diff --git a/src/Storage/AdapterPluginManager.php b/src/Storage/AdapterPluginManager.php index 99c613d94..3b4da9419 100644 --- a/src/Storage/AdapterPluginManager.php +++ b/src/Storage/AdapterPluginManager.php @@ -64,20 +64,7 @@ class AdapterPluginManager extends AbstractPluginManager * * @var array */ - protected $shared = array( - 'apc' => false, - 'filesystem' => false, - 'memcached' => false, - 'memory' => false, - 'sysvshm' => false, - 'systemvshm' => false, - 'sqlite' => false, - 'dba' => false, - 'wincache' => false, - 'xcache' => false, - 'zendserverdisk' => false, - 'zendservershm' => false, - ); + protected $shareByDefault = false; /** * Validate the plugin diff --git a/src/Storage/PluginManager.php b/src/Storage/PluginManager.php index b84798a02..6caa8ca7a 100644 --- a/src/Storage/PluginManager.php +++ b/src/Storage/PluginManager.php @@ -57,13 +57,7 @@ class PluginManager extends AbstractPluginManager * * @var array */ - protected $shared = array( - 'clearexpiredbyfactor' => false, - 'exceptionhandler' => false, - 'ignoreuserabort' => false, - 'optimizebyfactor' => false, - 'serializer' => false, - ); + protected $shareByDefault = false; /** * Validate the plugin From 575090141a3bd0be68ec29fefcc2328b6dd43d9b Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Fri, 6 Jul 2012 11:48:43 +0200 Subject: [PATCH 278/311] Added DBA cache adapter --- src/Storage/Adapter/Dba.php | 533 +++++++++++++++++++++++ src/Storage/Adapter/DbaIterator.php | 211 +++++++++ src/Storage/Adapter/DbaOptions.php | 147 +++++++ test/Storage/Adapter/AbstractDbaTest.php | 81 ++++ test/Storage/Adapter/DbaDb2Test.php | 36 ++ test/Storage/Adapter/DbaDb3Test.php | 36 ++ test/Storage/Adapter/DbaDb4Test.php | 36 ++ test/Storage/Adapter/DbaFlatfileTest.php | 36 ++ test/Storage/Adapter/DbaGdbmTest.php | 36 ++ test/Storage/Adapter/DbaInifileTest.php | 36 ++ test/Storage/Adapter/DbaQdbmTest.php | 36 ++ 11 files changed, 1224 insertions(+) create mode 100644 src/Storage/Adapter/Dba.php create mode 100644 src/Storage/Adapter/DbaIterator.php create mode 100644 src/Storage/Adapter/DbaOptions.php create mode 100644 test/Storage/Adapter/AbstractDbaTest.php create mode 100644 test/Storage/Adapter/DbaDb2Test.php create mode 100644 test/Storage/Adapter/DbaDb3Test.php create mode 100644 test/Storage/Adapter/DbaDb4Test.php create mode 100644 test/Storage/Adapter/DbaFlatfileTest.php create mode 100644 test/Storage/Adapter/DbaGdbmTest.php create mode 100644 test/Storage/Adapter/DbaInifileTest.php create mode 100644 test/Storage/Adapter/DbaQdbmTest.php diff --git a/src/Storage/Adapter/Dba.php b/src/Storage/Adapter/Dba.php new file mode 100644 index 000000000..a404520c1 --- /dev/null +++ b/src/Storage/Adapter/Dba.php @@ -0,0 +1,533 @@ +_close(); + + parent::__destruct(); + } + + /* options */ + + /** + * Set options. + * + * @param array|Traversable|DbaOptions $options + * @return Apc + * @see getOptions() + */ + public function setOptions($options) + { + if (!$options instanceof DbaOptions) { + $options = new DbaOptions($options); + } + + return parent::setOptions($options); + } + + /** + * Get options. + * + * @return DbaOptions + * @see setOptions() + */ + public function getOptions() + { + if (!$this->options) { + $this->setOptions(new DbaOptions()); + } + return $this->options; + } + + /* TotalSpaceCapableInterface */ + + /** + * Get total space in bytes + * + * @return int|float + */ + public function getTotalSpace() + { + if ($this->totalSpace !== null) { + $pathname = $this->getOptions()->getPathname(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + ErrorHandler::start(); + $total = disk_total_space($pathname); + $error = ErrorHandler::stop(); + if ($total === false) { + throw new Exception\RuntimeException("Can't detect total space of '{$pathname}'", 0, $error); + } + + // clean total space buffer on change pathname + $events = $this->getEventManager(); + $handle = null; + $totalSpace = & $this->totalSpace; + $callback = function ($event) use (& $events, & $handle, & $totalSpace) { + $params = $event->getParams(); + if (isset($params['pathname'])) { + $totalSpace = null; + $events->detach($handle); + } + }; + $handle = $events->attach($callback); + } + + return $this->totalSpace; + } + + /* AvailableSpaceCapableInterface */ + + /** + * Get available space in bytes + * + * @return int|float + */ + public function getAvailableSpace() + { + $pathname = $this->getOptions()->getPathname(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + ErrorHandler::start(); + $avail = disk_free_space($pathname); + $error = ErrorHandler::stop(); + if ($avail === false) { + throw new Exception\RuntimeException("Can't detect free space of '{$pathname}'", 0, $error); + } + + return $avail; + } + + /* FlushableInterface */ + + /** + * Flush the whole storage + * + * @return boolean + */ + public function flush() + { + $pathname = $this->getOptions()->getPathname(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + if (file_exists($pathname)) { + + // close the dba file before delete + // and reopen (create) on next use + $this->_close(); + + ErrorHandler::start(); + $result = unlink($pathname); + $error = ErrorHandler::stop(); + if (!$result) { + throw new Exception\RuntimeException("unlink('{$pathname}') failed", 0, $error); + } + } + + return true; + } + + /* ClearByNamespaceInterface */ + + /** + * Remove items by given namespace + * + * @param string $prefix + * @return boolean + */ + public function clearByNamespace($namespace) + { + $prefix = $namespace . $this->getOptions()->getNamespaceSeparator(); + $prefixl = strlen($prefix); + $result = true; + + $this->_open(); + + do { // Workaround for PHP-Bug #62491 & #62492 + $recheck = false; + $internalKey = dba_firstkey($this->handle); + while ($internalKey !== false && $internalKey !== null) { + if (substr($internalKey, 0, $prefixl) === $prefix) { + $result = dba_delete($internalKey, $this->handle) && $result; + } + + $internalKey = dba_nextkey($this->handle); + } + } while ($recheck); + + return $result; + } + + /* ClearByPrefixInterface */ + + /** + * Remove items matching given prefix + * + * @param string $prefix + * @return boolean + */ + public function clearByPrefix($prefix) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator() . $prefix; + $prefixl = strlen($prefix); + $result = true; + + $this->_open(); + + do { // Workaround for PHP-Bug #62491 & #62492 + $recheck = false; + $internalKey = dba_firstkey($this->handle); + while ($internalKey !== false && $internalKey !== null) { + if (substr($internalKey, 0, $prefixl) === $prefix) { + $result = dba_delete($internalKey, $this->handle) && $result; + $recheck = true; + } + + $internalKey = dba_nextkey($this->handle); + } + } while ($recheck); + + return $result; + } + + /* IterableInterface */ + + /** + * Get the storage iterator + * + * @return ApcIterator + */ + public function getIterator() + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + + return new DbaIterator($this, $this->handle, $prefix); + } + + /* OptimizableInterface */ + + /** + * Optimize the storage + * + * @return boolean + * @return Exception\RuntimeException + */ + public function optimize() + { + $this->_open(); + if (!dba_optimize($this->handle)) { + throw new Exception\RuntimeException('dba_optimize failed'); + } + return true; + } + + /* reading */ + + /** + * Internal method to get an item. + * + * @param string $normalizedKey + * @param boolean $success + * @param mixed $casToken + * @return mixed Data on success, null on failure + * @throws Exception\ExceptionInterface + */ + protected function internalGetItem(& $normalizedKey, & $success = null, & $casToken = null) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + $value = dba_fetch($internalKey, $this->handle); + + if ($value === false) { + $success = false; + return null; + } + + $success = true; + $casToken = $value; + return $value; + } + + /** + * Internal method to test if an item exists. + * + * @param string $normalizedKey + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalHasItem(& $normalizedKey) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + return dba_exists($internalKey, $this->handle); + } + + /* writing */ + + /** + * Internal method to store an item. + * + * @param string $normalizedKey + * @param mixed $value + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalSetItem(& $normalizedKey, & $value) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + if (!dba_replace($internalKey, $value, $this->handle)) { + throw new Exception\RuntimeException("dba_replace('{$internalKey}', ...) failed"); + } + + return true; + } + + /** + * Add an item. + * + * @param string $normalizedKey + * @param mixed $value + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalAddItem(& $normalizedKey, & $value) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + + // Workaround for PHP-Bug #54242 & #62489 + if (dba_exists($internalKey, $this->handle)) { + return false; + } + + // Workaround for PHP-Bug #54242 & #62489 + // dba_insert returns true if key already exists + ErrorHandler::start(); + $result = dba_insert($internalKey, $value, $this->handle); + $error = ErrorHandler::stop(); + if (!$result || $error) { + return false; + } + + return true; + } + + /** + * Internal method to remove an item. + * + * @param string $normalizedKey + * @return boolean + * @throws Exception\ExceptionInterface + */ + protected function internalRemoveItem(& $normalizedKey) + { + $options = $this->getOptions(); + $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); + $internalKey = $prefix . $normalizedKey; + + $this->_open(); + + // Workaround for PHP-Bug #62490 + if (!dba_exists($internalKey, $this->handle)) { + return false; + } + + return dba_delete($internalKey, $this->handle); + } + + /* status */ + + /** + * Internal method to get capabilities of this adapter + * + * @return Capabilities + */ + protected function internalGetCapabilities() + { + if ($this->capabilities === null) { + $marker = new stdClass(); + $capabilities = new Capabilities( + $this, + $marker, + array( + 'supportedDatatypes' => array( + 'NULL' => 'string', + 'boolean' => 'string', + 'integer' => 'string', + 'double' => 'string', + 'string' => true, + 'array' => false, + 'object' => false, + 'resource' => false, + ), + 'supportedMetadata' => array(), + 'maxKeyLength' => 0, // TODO: maxKeyLength ???? + 'namespaceIsPrefix' => true, + 'namespaceSeparator' => $this->getOptions()->getNamespaceSeparator(), + ) + ); + + // update namespace separator on change option + $this->getEventManager()->attach('option', function ($event) use ($capabilities, $marker) { + $params = $event->getParams(); + + if (isset($params['namespace_separator'])) { + $capabilities->setNamespaceSeparator($marker, $params['namespace_separator']); + } + }); + + $this->capabilities = $capabilities; + $this->capabilityMarker = $marker; + } + + return $this->capabilities; + } + + /** + * Open the database if not already done. + * + * @return void + * @throws Exception\LogicException + * @throws Exception\RuntimeException + */ + protected function _open() + { + if (!$this->handle) { + $options = $this->getOptions(); + $pathname = $options->getPathname(); + $mode = $options->getMode(); + $handler = $options->getHandler(); + + if ($pathname === '') { + throw new Exception\LogicException('No pathname to database file'); + } + + ErrorHandler::start(); + $dba = dba_open($pathname, $mode, $handler); + $err = ErrorHandler::stop(); + if (!$dba) { + throw new Exception\RuntimeException( + "dba_open('{$pathname}', '{$mode}', '{$handler}') failed", 0, $err + ); + } + $this->handle = $dba; + } + } + + /** + * Close database file if opend + * + * @return void + */ + protected function _close() + { + if ($this->handle) { + @dba_close($this->handle); + $this->handle = null; + } + } +} diff --git a/src/Storage/Adapter/DbaIterator.php b/src/Storage/Adapter/DbaIterator.php new file mode 100644 index 000000000..807176503 --- /dev/null +++ b/src/Storage/Adapter/DbaIterator.php @@ -0,0 +1,211 @@ +storage = $storage; + $this->handle = $handle; + $this->prefixLength = strlen($prefix); + + $this->rewind(); + } + + /** + * Get storage instance + * + * @return Dba + */ + public function getStorage() + { + return $this->storage; + } + + /** + * Get iterator mode + * + * @return int Value of IteratorInterface::CURRENT_AS_* + */ + public function getMode() + { + return $this->mode; + } + + /** + * Set iterator mode + * + * @param int $mode + * @return ApcIterator Fluent interface + */ + public function setMode($mode) + { + $this->mode = (int) $mode; + return $this; + } + + /* Iterator */ + + /** + * Get current key, value or metadata. + * + * @return mixed + * @throws Exception\RuntimeException + */ + public function current() + { + if ($this->mode == IteratorInterface::CURRENT_AS_SELF) { + return $this; + } + + $key = $this->key(); + + if ($this->mode == IteratorInterface::CURRENT_AS_VALUE) { + return $this->storage->getItem($key); + } elseif ($this->mode == IteratorInterface::CURRENT_AS_METADATA) { + return $this->storage->getMetadata($key); + } + + return $key; + } + + /** + * Get current key + * + * @return string + * @throws Exception\RuntimeException + */ + public function key() + { + if ($this->currentInternalKey === false) { + throw new Exception\RuntimeException("Iterater is on an invalid state"); + } + + // remove namespace prefix + return substr($this->currentInternalKey, $this->prefixLength); + } + + /** + * Move forward to next element + * + * @return void + * @throws Exception\RuntimeException + */ + public function next() + { + if ($this->currentInternalKey === false) { + throw new Exception\RuntimeException("Iterater is on an invalid state"); + } + + $this->currentInternalKey = dba_nextkey($this->handle); + + // Workaround for PHP-Bug #62492 + if ($this->currentInternalKey === null) { + $this->currentInternalKey = false; + } + } + + /** + * Checks if current position is valid + * + * @return boolean + */ + public function valid() + { + return ($this->currentInternalKey !== false); + } + + /** + * Rewind the Iterator to the first element. + * + * @return void + * @throws Exception\RuntimeException + */ + public function rewind() + { + if ($this->currentInternalKey === false) { + throw new Exception\RuntimeException("Iterater is on an invalid state"); + } + + $this->currentInternalKey = dba_firstkey($this->handle); + + // Workaround for PHP-Bug #62492 + if ($this->currentInternalKey === null) { + $this->currentInternalKey = false; + } + } +} diff --git a/src/Storage/Adapter/DbaOptions.php b/src/Storage/Adapter/DbaOptions.php new file mode 100644 index 000000000..570317f82 --- /dev/null +++ b/src/Storage/Adapter/DbaOptions.php @@ -0,0 +1,147 @@ +triggerOptionEvent('namespace_separator', $separator); + $this->namespaceSeparator = $separator; + return $this; + } + + /** + * Get namespace separator + * + * @return string + */ + public function getNamespaceSeparator() + { + return $this->namespaceSeparator; + } + + /** + * Set pathname to database file + * + * @param string $pathname + * @return DbaOptions + */ + public function setPathname($pathname) + { + $this->pathname = (string) $pathname; + $this->triggerOptionEvent('pathname', $pathname); + return $this; + } + + /** + * Get pathname to database file + * + * @return string + */ + public function getPathname() + { + return $this->pathname; + } + + /** + * + * + * @param unknown_type $mode + * @return \Zend\Cache\Storage\Adapter\DbaOptions + */ + public function setMode($mode) + { + $this->mode = (string) $mode; + $this->triggerOptionEvent('mode', $mode); + return $this; + } + + public function getMode() + { + return $this->mode; + } + + public function setHandler($handler) + { + $handler = (string) $handler; + + if (!function_exists('dba_handlers') || !in_array($handler, dba_handlers())) { + throw new Exception\ExtensionNotLoadedException("DBA-Handler '{$handler}' not supported"); + } + + $this->triggerOptionEvent('handler', $handler); + $this->handler = $handler; + return $this; + } + + public function getHandler() + { + return $this->handler; + } +} diff --git a/test/Storage/Adapter/AbstractDbaTest.php b/test/Storage/Adapter/AbstractDbaTest.php new file mode 100644 index 000000000..e710d0704 --- /dev/null +++ b/test/Storage/Adapter/AbstractDbaTest.php @@ -0,0 +1,81 @@ +fail("Expected exception Zend\Cache\Exception\ExtensionNotLoadedException"); + } catch (Cache\Exception\ExtensionNotLoadedException $e) { + $this->markTestSkipped("Missing ext/dba"); + } + } + + if (!in_array($this->handler, dba_handlers())) { + try { + new Cache\Storage\Adapter\DbaOptions(array('handler' => $this->handler)); + $this->fail("Expected exception Zend\Cache\Exception\ExtensionNotLoadedException"); + } catch (Cache\Exception\ExtensionNotLoadedException $e) { + $this->markTestSkipped("Missing ext/dba handler '{$this->handler}'"); + } + } + + $this->temporaryDbaFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid('zfcache_dba_'); + $this->_options = new Cache\Storage\Adapter\DbaOptions(array( + 'pathname' => $this->temporaryDbaFile, + 'handler' => $this->handler, + )); + + $this->_storage = new Cache\Storage\Adapter\Dba(); + $this->_storage->setOptions($this->_options); + + parent::setUp(); + } + + public function tearDown() + { + $this->_storage = null; + + if (file_exists($this->temporaryDbaFile)) { + unlink($this->temporaryDbaFile); + } + + parent::tearDown(); + } +} diff --git a/test/Storage/Adapter/DbaDb2Test.php b/test/Storage/Adapter/DbaDb2Test.php new file mode 100644 index 000000000..9a0629493 --- /dev/null +++ b/test/Storage/Adapter/DbaDb2Test.php @@ -0,0 +1,36 @@ + Date: Fri, 6 Jul 2012 12:35:20 +0200 Subject: [PATCH 279/311] Use of capability minTtl instead of ExpirableInterface --- src/Storage/Adapter/Apc.php | 12 ++++--- src/Storage/Adapter/Dba.php | 1 + src/Storage/Adapter/Filesystem.php | 1 + src/Storage/Adapter/Memcached.php | 8 +++-- src/Storage/Adapter/Memory.php | 1 + src/Storage/Adapter/WinCache.php | 8 +++-- src/Storage/Capabilities.php | 38 +++++++++++++++++++++- src/Storage/ExpirableInterface.php | 24 -------------- test/Storage/Adapter/CommonAdapterTest.php | 36 +++++++++++--------- 9 files changed, 78 insertions(+), 51 deletions(-) delete mode 100644 src/Storage/ExpirableInterface.php diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 6a1228813..df5673803 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -41,10 +41,13 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Apc - extends AbstractAdapter - implements ClearByPrefixInterface, ClearByNamespaceInterface, FlushableInterface, IterableInterface, - AvailableSpaceCapableInterface, TotalSpaceCapableInterface +class Apc extends AbstractAdapter implements + ClearByPrefixInterface, + ClearByNamespaceInterface, + FlushableInterface, + IterableInterface, + AvailableSpaceCapableInterface, + TotalSpaceCapableInterface { /** * Buffered total space in bytes @@ -650,6 +653,7 @@ protected function internalGetCapabilities() 'atime', 'ctime', 'mtime', 'rtime', 'size', 'hits', 'ttl', ), + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => true, 'ttlPrecision' => 1, diff --git a/src/Storage/Adapter/Dba.php b/src/Storage/Adapter/Dba.php index a404520c1..75c323782 100644 --- a/src/Storage/Adapter/Dba.php +++ b/src/Storage/Adapter/Dba.php @@ -464,6 +464,7 @@ protected function internalGetCapabilities() 'object' => false, 'resource' => false, ), + 'minTtl' => 0, 'supportedMetadata' => array(), 'maxKeyLength' => 0, // TODO: maxKeyLength ???? 'namespaceIsPrefix' => true, diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index d7b1110ee..c5a932544 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1189,6 +1189,7 @@ protected function internalGetCapabilities() 'resource' => false, ), 'supportedMetadata' => $metadata, + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => false, 'ttlPrecision' => 1, diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index fddced168..8747516b1 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -41,9 +41,10 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class Memcached - extends AbstractAdapter - implements FlushableInterface, AvailableSpaceCapableInterface, TotalSpaceCapableInterface +class Memcached extends AbstractAdapter implements + FlushableInterface, + AvailableSpaceCapableInterface, + TotalSpaceCapableInterface { /** * Major version of ext/memcached @@ -569,6 +570,7 @@ protected function internalGetCapabilities() 'resource' => false, ), 'supportedMetadata' => array(), + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => true, 'ttlPrecision' => 1, diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 579cbe28d..7aaf3b537 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -723,6 +723,7 @@ protected function internalGetCapabilities() 'resource' => true, ), 'supportedMetadata' => array('mtime'), + 'minTtl' => 1, 'maxTtl' => PHP_INT_MAX, 'staticTtl' => false, 'ttlPrecision' => 0.05, diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index f947558fb..0cefddb9d 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -36,9 +36,10 @@ * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ -class WinCache - extends AbstractAdapter - implements FlushableInterface, AvailableSpaceCapableInterface, TotalSpaceCapableInterface +class WinCache extends AbstractAdapter implements + FlushableInterface, + AvailableSpaceCapableInterface, + TotalSpaceCapableInterface { /** @@ -472,6 +473,7 @@ protected function internalGetCapabilities() 'supportedMetadata' => array( 'internal_key', 'ttl', 'hits', 'size' ), + 'minTtl' => 1, 'maxTtl' => 0, 'staticTtl' => true, 'ttlPrecision' => 1, diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 7a23f0592..064d31fc1 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -76,6 +76,16 @@ class Capabilities */ protected $_maxKeyLength; + /** + * Min. TTL (0 means items never expire) + * + * If it's NULL the capability isn't set and the getter + * returns the base capability or the default value. + * + * @var null|int + */ + protected $_minTtl; + /** * Max. TTL (0 means infinite) * @@ -280,6 +290,32 @@ public function setSupportedMetadata(stdClass $marker, array $metadata) return $this->setCapability($marker, 'supportedMetadata', $metadata); } + /** + * Get minimum supported time-to-live + * + * @return int 0 means items never expire + */ + public function getMinTtl() + { + return $this->getCapability('minTtl', 0); + } + + /** + * Set minimum supported time-to-live + * + * @param stdClass $marker + * @param int $minTtl + * @return Capabilities Fluent interface + */ + public function setMinTtl(stdClass $marker, $minTtl) + { + $minTtl = (int) $minTtl; + if ($minTtl < 0) { + throw new Exception\InvalidArgumentException('$minTtl must be greater or equal 0'); + } + return $this->setCapability($marker, 'minTtl', $minTtl); + } + /** * Get maximum supported time-to-live * @@ -299,7 +335,7 @@ public function getMaxTtl() */ public function setMaxTtl(stdClass $marker, $maxTtl) { - $maxTtl = (int)$maxTtl; + $maxTtl = (int) $maxTtl; if ($maxTtl < 0) { throw new Exception\InvalidArgumentException('$maxTtl must be greater or equal 0'); } diff --git a/src/Storage/ExpirableInterface.php b/src/Storage/ExpirableInterface.php deleted file mode 100644 index 20ee35ebc..000000000 --- a/src/Storage/ExpirableInterface.php +++ /dev/null @@ -1,24 +0,0 @@ -_storage instanceof ExpirableInterface) { - $this->markTestSkipped("Adapter doesn't support TTL expiration"); + $capabilities = $this->_storage->getCapabilities(); + + if ($capabilities->getMinTtl() === 0) { + $this->markTestSkipped("Adapter doesn't support item expiration"); } - $capabilities = $this->_storage->getCapabilities(); $ttl = $capabilities->getTtlPrecision(); $this->_options->setTtl($ttl); @@ -301,11 +301,12 @@ public function testGetItemSetsSuccessFlag() public function testGetItemReturnsNullOnExpiredItem() { - if (!$this->_storage instanceof ExpirableInterface) { - $this->markTestSkipped("Adapter doesn't support TTL expiration"); + $capabilities = $this->_storage->getCapabilities(); + + if ($capabilities->getMinTtl() === 0) { + $this->markTestSkipped("Adapter doesn't support item expiration"); } - $capabilities = $this->_storage->getCapabilities(); if ($capabilities->getUseRequestTime()) { $this->markTestSkipped("Can't test get expired item if request time will be used"); } @@ -543,11 +544,12 @@ public function testSetGetHasAndRemoveItemsWithNamespace() public function testSetAndGetExpiredItem() { - if (!$this->_storage instanceof ExpirableInterface) { - $this->markTestSkipped("Adapter doesn't support TTL expiration"); + $capabilities = $this->_storage->getCapabilities(); + + if ($capabilities->getMinTtl() === 0) { + $this->markTestSkipped("Adapter doesn't support item expiration"); } - $capabilities = $this->_storage->getCapabilities(); $ttl = $capabilities->getTtlPrecision(); $this->_options->setTtl($ttl); @@ -573,11 +575,12 @@ public function testSetAndGetExpiredItem() public function testSetAndGetExpiredItems() { - if (!$this->_storage instanceof ExpirableInterface) { - $this->markTestSkipped("Adapter doesn't support TTL expiration"); + $capabilities = $this->_storage->getCapabilities(); + + if ($capabilities->getMinTtl() === 0) { + $this->markTestSkipped("Adapter doesn't support item expiration"); } - $capabilities = $this->_storage->getCapabilities(); $ttl = $capabilities->getTtlPrecision(); $this->_options->setTtl($ttl); @@ -825,11 +828,12 @@ public function testDecrementItemsReturnsEmptyArrayIfNonWritable() public function testTouchItem() { - if (!$this->_storage instanceof ExpirableInterface) { - $this->markTestSkipped("Adapter doesn't support TTL expiration"); + $capabilities = $this->_storage->getCapabilities(); + + if ($capabilities->getMinTtl() === 0) { + $this->markTestSkipped("Adapter doesn't support item expiration"); } - $capabilities = $this->_storage->getCapabilities(); $this->_options->setTtl(2 * $capabilities->getTtlPrecision()); $this->assertTrue($this->_storage->setItem('key', 'value')); From b7542e772c1f85312540cc6fd4ca6e7f352bd10b Mon Sep 17 00:00:00 2001 From: Maks3w Date: Mon, 9 Jul 2012 16:19:42 +0200 Subject: [PATCH 280/311] [CS][Library] Set File Header http://framework.zend.com/wiki/display/ZFDEV2/Coding+Standards#CodingStandards-Files The following script replaces the content between PHP open tag and namespace declaration. for COMPONENT in $(ls -d *) do for FILE in $(find $COMPONENT -name "*.php") do BLOCK="\/\*\*\n \* Zend Framework \(http:\/\/framework\.zend\.com\/\)\n \*\n \* \@link http:\/\/github\.com\/zendframework\/zf2 for the canonical source repository\n \* \@copyright Copyright \(c\) 2005-2012 Zend Technologies USA Inc\. \(http:\/\/www\.zend\.com\)\n \* \@license http:\/\/framework\.zend\.com\/license\/new-bsd New BSD License\n \* \@package Zend_$COMPONENT\n \*\/" perl -0777 -i -pe "s/(<\?php(\s*.*)*\nn)/ Date: Mon, 9 Jul 2012 16:34:21 +0200 Subject: [PATCH 281/311] [CS][test] Remove @copyright & @license for fl in $(find . -name "*.php"); do mv $fl $fl.old; sed '/@copyright/d' $fl.old > $fl; rm -f $fl.old; done; for fl in $(find . -name "*.php"); do mv $fl $fl.old; sed '/@license/d' $fl.old > $fl; rm -f $fl.old; done; --- test/Pattern/CallbackCacheTest.php | 4 ---- test/Pattern/CaptureCacheTest.php | 4 ---- test/Pattern/ClassCacheTest.php | 4 ---- test/Pattern/CommonPatternTest.php | 4 ---- test/Pattern/ObjectCacheTest.php | 4 ---- test/Pattern/OutputCacheTest.php | 4 ---- test/PatternFactoryTest.php | 4 ---- test/Storage/Adapter/AbstractAdapterTest.php | 4 ---- test/Storage/Adapter/AbstractDbaTest.php | 4 ---- test/Storage/Adapter/AbstractZendServerTest.php | 4 ---- test/Storage/Adapter/ApcTest.php | 4 ---- test/Storage/Adapter/CommonAdapterTest.php | 4 ---- test/Storage/Adapter/DbaDb2Test.php | 4 ---- test/Storage/Adapter/DbaDb3Test.php | 4 ---- test/Storage/Adapter/DbaDb4Test.php | 4 ---- test/Storage/Adapter/DbaFlatfileTest.php | 4 ---- test/Storage/Adapter/DbaGdbmTest.php | 4 ---- test/Storage/Adapter/DbaInifileTest.php | 4 ---- test/Storage/Adapter/DbaQdbmTest.php | 4 ---- test/Storage/Adapter/FilesystemTest.php | 4 ---- test/Storage/Adapter/MemcachedTest.php | 4 ---- test/Storage/Adapter/MemoryTest.php | 4 ---- test/Storage/Adapter/WinCacheTest.php | 4 ---- test/Storage/Adapter/ZendServerDiskTest.php | 4 ---- test/Storage/Adapter/ZendServerShmTest.php | 4 ---- test/Storage/CapabilitiesTest.php | 4 ---- test/Storage/Plugin/CommonPluginTest.php | 4 ---- test/Storage/Plugin/IgnoreUserAbortTest.php | 4 ---- test/Storage/Plugin/SerializerTest.php | 4 ---- test/StorageFactoryTest.php | 4 ---- 30 files changed, 120 deletions(-) diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index e9a64f606..7c485cd32 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Pattern; @@ -58,8 +56,6 @@ function bar () { * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class CallbackCacheTest extends CommonPatternTest diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php index 4c61aff39..a256228bb 100644 --- a/test/Pattern/CaptureCacheTest.php +++ b/test/Pattern/CaptureCacheTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Pattern; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class CaptureCacheTest extends CommonPatternTest diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 71cf36582..e65f68d21 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Pattern; @@ -49,8 +47,6 @@ public static function emptyMethod() {} * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class ClassCacheTest extends CommonPatternTest diff --git a/test/Pattern/CommonPatternTest.php b/test/Pattern/CommonPatternTest.php index 94aace4c1..4fb6a3a8a 100644 --- a/test/Pattern/CommonPatternTest.php +++ b/test/Pattern/CommonPatternTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Pattern; @@ -27,8 +25,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class CommonPatternTest extends \PHPUnit_Framework_TestCase diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index 34e5b871e..112cf611e 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Pattern; @@ -56,8 +54,6 @@ public function emptyMethod() {} * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class ObjectCacheTest extends CommonPatternTest diff --git a/test/Pattern/OutputCacheTest.php b/test/Pattern/OutputCacheTest.php index 3407197f3..af30e483b 100644 --- a/test/Pattern/OutputCacheTest.php +++ b/test/Pattern/OutputCacheTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Pattern; @@ -27,8 +25,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class OutputCacheTest extends CommonPatternTest diff --git a/test/PatternFactoryTest.php b/test/PatternFactoryTest.php index e0636d4f2..168a399c5 100644 --- a/test/PatternFactoryTest.php +++ b/test/PatternFactoryTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache; @@ -27,8 +25,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class PatternFactoryTest extends \PHPUnit_Framework_TestCase diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 9d3bc5cee..98032f730 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -28,8 +26,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class AbstractAdapterTest extends \PHPUnit_Framework_TestCase diff --git a/test/Storage/Adapter/AbstractDbaTest.php b/test/Storage/Adapter/AbstractDbaTest.php index e710d0704..71cbcf864 100644 --- a/test/Storage/Adapter/AbstractDbaTest.php +++ b/test/Storage/Adapter/AbstractDbaTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ abstract class AbstractDbaTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/AbstractZendServerTest.php b/test/Storage/Adapter/AbstractZendServerTest.php index 9a8f07997..9b17a5b47 100644 --- a/test/Storage/Adapter/AbstractZendServerTest.php +++ b/test/Storage/Adapter/AbstractZendServerTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -29,8 +27,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class AbstractZendServerTest extends \PHPUnit_Framework_TestCase diff --git a/test/Storage/Adapter/ApcTest.php b/test/Storage/Adapter/ApcTest.php index a2ded30df..497b7bd4c 100644 --- a/test/Storage/Adapter/ApcTest.php +++ b/test/Storage/Adapter/ApcTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class ApcTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 1462a6303..549cee6f5 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -43,8 +41,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ abstract class CommonAdapterTest extends \PHPUnit_Framework_TestCase diff --git a/test/Storage/Adapter/DbaDb2Test.php b/test/Storage/Adapter/DbaDb2Test.php index 9a0629493..06a76f765 100644 --- a/test/Storage/Adapter/DbaDb2Test.php +++ b/test/Storage/Adapter/DbaDb2Test.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaDb2Test extends AbstractDbaTest diff --git a/test/Storage/Adapter/DbaDb3Test.php b/test/Storage/Adapter/DbaDb3Test.php index 1a64350da..ebc478389 100644 --- a/test/Storage/Adapter/DbaDb3Test.php +++ b/test/Storage/Adapter/DbaDb3Test.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaDb3Test extends AbstractDbaTest diff --git a/test/Storage/Adapter/DbaDb4Test.php b/test/Storage/Adapter/DbaDb4Test.php index cb85e6087..edcdd1898 100644 --- a/test/Storage/Adapter/DbaDb4Test.php +++ b/test/Storage/Adapter/DbaDb4Test.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaDb4Test extends AbstractDbaTest diff --git a/test/Storage/Adapter/DbaFlatfileTest.php b/test/Storage/Adapter/DbaFlatfileTest.php index 4adc82763..c618a29ce 100644 --- a/test/Storage/Adapter/DbaFlatfileTest.php +++ b/test/Storage/Adapter/DbaFlatfileTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaFlatfileTest extends AbstractDbaTest diff --git a/test/Storage/Adapter/DbaGdbmTest.php b/test/Storage/Adapter/DbaGdbmTest.php index c2fd2f455..ee43bb735 100644 --- a/test/Storage/Adapter/DbaGdbmTest.php +++ b/test/Storage/Adapter/DbaGdbmTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaGdbmTest extends AbstractDbaTest diff --git a/test/Storage/Adapter/DbaInifileTest.php b/test/Storage/Adapter/DbaInifileTest.php index f87c2d68b..873c53e08 100644 --- a/test/Storage/Adapter/DbaInifileTest.php +++ b/test/Storage/Adapter/DbaInifileTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaInifileTest extends AbstractDbaTest diff --git a/test/Storage/Adapter/DbaQdbmTest.php b/test/Storage/Adapter/DbaQdbmTest.php index cf5c72625..d6650235c 100644 --- a/test/Storage/Adapter/DbaQdbmTest.php +++ b/test/Storage/Adapter/DbaQdbmTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class DbaQdbmTest extends AbstractDbaTest diff --git a/test/Storage/Adapter/FilesystemTest.php b/test/Storage/Adapter/FilesystemTest.php index 5ff4c78c4..e62abf0a0 100644 --- a/test/Storage/Adapter/FilesystemTest.php +++ b/test/Storage/Adapter/FilesystemTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -27,8 +25,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class FilesystemTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index 87949e260..41aefd5e3 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -28,8 +26,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class MemcachedTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index 81450cd84..33185d467 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -26,8 +24,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class MemoryTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/WinCacheTest.php b/test/Storage/Adapter/WinCacheTest.php index a3d5cbd53..41c6fe020 100644 --- a/test/Storage/Adapter/WinCacheTest.php +++ b/test/Storage/Adapter/WinCacheTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -27,8 +25,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class WinCacheTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php index 1e0dbb7b8..de9f70129 100644 --- a/test/Storage/Adapter/ZendServerDiskTest.php +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -28,8 +26,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class ZendServerDiskTest extends CommonAdapterTest diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index fbf90e654..032ee2ecc 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Adapter; @@ -28,8 +26,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class ZendServerShmTest extends CommonAdapterTest diff --git a/test/Storage/CapabilitiesTest.php b/test/Storage/CapabilitiesTest.php index bf976dfbc..90254b3b8 100644 --- a/test/Storage/CapabilitiesTest.php +++ b/test/Storage/CapabilitiesTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage; @@ -28,8 +26,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class CapabilitiesTest extends \PHPUnit_Framework_TestCase diff --git a/test/Storage/Plugin/CommonPluginTest.php b/test/Storage/Plugin/CommonPluginTest.php index 009cdca9a..fc0cc739a 100644 --- a/test/Storage/Plugin/CommonPluginTest.php +++ b/test/Storage/Plugin/CommonPluginTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Plugin; @@ -29,8 +27,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ abstract class CommonPluginTest extends \PHPUnit_Framework_TestCase diff --git a/test/Storage/Plugin/IgnoreUserAbortTest.php b/test/Storage/Plugin/IgnoreUserAbortTest.php index 861762f1e..ed4d5012d 100644 --- a/test/Storage/Plugin/IgnoreUserAbortTest.php +++ b/test/Storage/Plugin/IgnoreUserAbortTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Plugin; @@ -30,8 +28,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class IgnoreUserAbortTest extends CommonPluginTest diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index 1a67cff9b..7be387180 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache\Storage\Plugin; @@ -30,8 +28,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class SerializerTest extends CommonPluginTest diff --git a/test/StorageFactoryTest.php b/test/StorageFactoryTest.php index 8da4a0dbe..915b97bba 100644 --- a/test/StorageFactoryTest.php +++ b/test/StorageFactoryTest.php @@ -15,8 +15,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace ZendTest\Cache; @@ -27,8 +25,6 @@ * @category Zend * @package Zend_Cache * @subpackage UnitTests - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License * @group Zend_Cache */ class StorageFactoryTest extends \PHPUnit_Framework_TestCase From 21b48355df2d6de3c03a52aa587ddafce7942094 Mon Sep 17 00:00:00 2001 From: Maks3w Date: Mon, 9 Jul 2012 16:41:27 +0200 Subject: [PATCH 282/311] [CS][Tests] Set File Header http://framework.zend.com/wiki/display/ZFDEV2/Coding+Standards#CodingStandards-Files The following script replaces the content between PHP open tag and namespace declaration. for COMPONENT in $(ls -d *) do for FILE in $(find $COMPONENT -name "*.php") do BLOCK="\/\*\*\n \* Zend Framework \(http:\/\/framework\.zend\.com\/\)\n \*\n \* \@link http:\/\/github\.com\/zendframework\/zf2 for the canonical source repository\n \* \@copyright Copyright \(c\) 2005-2012 Zend Technologies USA Inc\. \(http:\/\/www\.zend\.com\)\n \* \@license http:\/\/framework\.zend\.com\/license\/new-bsd New BSD License\n \* \@package Zend_$COMPONENT\n \*\/" perl -0777 -i -pe "s/(<\?php(\s*.*)*\nn)/ Date: Mon, 9 Jul 2012 17:55:18 +0200 Subject: [PATCH 283/311] [CS][Library] Rest of files --- src/Storage/Plugin/PluginInterface.php | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/Storage/Plugin/PluginInterface.php b/src/Storage/Plugin/PluginInterface.php index 21a0cd6a2..17ab0d3cf 100644 --- a/src/Storage/Plugin/PluginInterface.php +++ b/src/Storage/Plugin/PluginInterface.php @@ -13,18 +13,6 @@ use Zend\EventManager\ListenerAggregateInterface; /** - * 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 Storage_Plugin From d67f0d9e8bc160c4c18f98281b51bfc1be05533c Mon Sep 17 00:00:00 2001 From: prolic Date: Thu, 28 Jun 2012 19:16:16 +0200 Subject: [PATCH 284/311] Fix use statements in Zend\Cache --- src/Pattern/AbstractPattern.php | 4 +-- src/Pattern/CallbackCache.php | 4 +-- src/Pattern/ClassCache.php | 4 +-- src/Pattern/OutputCache.php | 4 +-- src/Pattern/PatternOptions.php | 8 ++--- src/Storage/Adapter/AbstractAdapter.php | 26 +++++++------- src/Storage/Adapter/AbstractZendServer.php | 8 ++--- src/Storage/Adapter/AdapterOptions.php | 12 +++---- src/Storage/Adapter/Apc.php | 24 ++++++------- src/Storage/Adapter/ApcIterator.php | 6 ++-- src/Storage/Adapter/Filesystem.php | 36 +++++++++---------- src/Storage/Adapter/FilesystemIterator.php | 6 ++-- src/Storage/Adapter/KeyListIterator.php | 8 ++--- src/Storage/Adapter/Memcached.php | 24 ++++++------- src/Storage/Adapter/MemcachedOptions.php | 6 ++-- src/Storage/Adapter/Memory.php | 22 ++++++------ src/Storage/Adapter/WinCache.php | 14 ++++---- src/Storage/Adapter/ZendServerDisk.php | 14 ++++---- src/Storage/Adapter/ZendServerShm.php | 10 +++--- src/Storage/Capabilities.php | 8 ++--- src/Storage/Event.php | 4 +-- src/Storage/ExceptionEvent.php | 4 +-- src/Storage/Plugin/ClearExpiredByFactor.php | 12 +++---- src/Storage/Plugin/ExceptionHandler.php | 8 ++--- src/Storage/Plugin/IgnoreUserAbort.php | 6 ++-- src/Storage/Plugin/OptimizeByFactor.php | 10 +++--- src/Storage/Plugin/PluginOptions.php | 8 ++--- src/Storage/Plugin/Serializer.php | 14 ++++---- test/Storage/Adapter/AbstractAdapterTest.php | 4 +-- .../Adapter/AbstractZendServerTest.php | 6 ++-- test/Storage/Adapter/CommonAdapterTest.php | 14 ++++++++ test/Storage/Adapter/MemcachedTest.php | 4 +-- test/Storage/Adapter/WinCacheTest.php | 4 +-- test/Storage/Adapter/ZendServerDiskTest.php | 4 +-- test/Storage/Adapter/ZendServerShmTest.php | 4 +-- test/Storage/CapabilitiesTest.php | 4 +-- .../Plugin/ClearExpiredByFactorTest.php | 8 ++--- test/Storage/Plugin/ExceptionHandlerTest.php | 8 ++--- test/Storage/Plugin/IgnoreUserAbortTest.php | 10 +++--- test/Storage/Plugin/OptimizeByFactorTest.php | 8 ++--- test/Storage/Plugin/SerializerTest.php | 10 +++--- test/Storage/TestAsset/MockPlugin.php | 8 ++--- 42 files changed, 212 insertions(+), 198 deletions(-) diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index 810dc3f3e..c871c98bc 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Pattern; -use Zend\Cache\Exception, - Traversable; +use Zend\Cache\Exception; +use Traversable; /** * @category Zend diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index f0772dbbe..64254bd54 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Pattern; -use Zend\Cache\Exception, - Zend\Cache\StorageFactory; +use Zend\Cache\Exception; +use Zend\Cache\StorageFactory; /** * @category Zend diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index d8c914f97..3a399275a 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Pattern; -use Zend\Cache, - Zend\Cache\Exception; +use Zend\Cache; +use Zend\Cache\Exception; /** * @category Zend diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index e29a813f7..fcee1fa82 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Pattern; -use Zend\Cache\Exception, - Zend\Cache\StorageFactory; +use Zend\Cache\Exception; +use Zend\Cache\StorageFactory; /** * @category Zend diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index fcc871ab1..8ddd1e8e5 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -10,10 +10,10 @@ namespace Zend\Cache\Pattern; -use Zend\Cache\Exception, - Zend\Cache\StorageFactory, - Zend\Cache\Storage\StorageInterface as Storage, - Zend\Stdlib\AbstractOptions; +use Zend\Cache\Exception; +use Zend\Cache\StorageFactory; +use Zend\Cache\Storage\StorageInterface as Storage; +use Zend\Stdlib\AbstractOptions; /** * @category Zend diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 0720d9179..7d252a628 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -10,19 +10,19 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - SplObjectStorage, - stdClass, - Traversable, - Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\Event, - Zend\Cache\Storage\ExceptionEvent, - Zend\Cache\Storage\PostEvent, - Zend\Cache\Storage\Plugin, - Zend\Cache\Storage\StorageInterface, - Zend\EventManager\EventManager, - Zend\EventManager\EventsCapableInterface; +use ArrayObject; +use SplObjectStorage; +use stdClass; +use Traversable; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\ExceptionEvent; +use Zend\Cache\Storage\PostEvent; +use Zend\Cache\Storage\Plugin; +use Zend\Cache\Storage\StorageInterface; +use Zend\EventManager\EventManager; +use Zend\EventManager\EventsCapableInterface; /** * @category Zend diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index 4c615c1b9..ee98fd79d 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -10,10 +10,10 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - stdClass, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Exception; +use ArrayObject; +use stdClass; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Exception; /** * @category Zend diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 4ed811586..fabab5269 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -10,12 +10,12 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - Zend\Cache\Exception, - Zend\Cache\Storage\Event, - Zend\Cache\Storage\StorageInterface, - Zend\EventManager\EventsCapableInterface, - Zend\Stdlib\AbstractOptions; +use ArrayObject; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\StorageInterface; +use Zend\EventManager\EventsCapableInterface; +use Zend\Stdlib\AbstractOptions; /** * Unless otherwise marked, all options in this class affect all adapters. diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 99dee4ccd..5c18986eb 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -10,18 +10,18 @@ namespace Zend\Cache\Storage\Adapter; -use APCIterator as BaseApcIterator, - ArrayObject, - stdClass, - Traversable, - Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\ClearByPrefixInterface, - Zend\Cache\Storage\ClearByNamespaceInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface; +use APCIterator as BaseApcIterator; +use ArrayObject; +use stdClass; +use Traversable; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @package Zend_Cache diff --git a/src/Storage/Adapter/ApcIterator.php b/src/Storage/Adapter/ApcIterator.php index ff34e0f54..b53ab9a36 100644 --- a/src/Storage/Adapter/ApcIterator.php +++ b/src/Storage/Adapter/ApcIterator.php @@ -10,9 +10,9 @@ namespace Zend\Cache\Storage\Adapter; -use APCIterator as BaseApcIterator, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\IteratorInterface; +use APCIterator as BaseApcIterator; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\IteratorInterface; /** * @category Zend diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index eb476edf0..c563ab2e8 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -10,24 +10,24 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - GlobIterator, - stdClass, - Exception as BaseException, - Zend\Cache\Exception, - Zend\Cache\Storage, - Zend\Cache\Storage\StorageInterface, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\ClearExpiredInterface, - Zend\Cache\Storage\ClearByNamespaceInterface, - Zend\Cache\Storage\ClearByPrefixInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\OptimizableInterface, - Zend\Cache\Storage\TaggableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface, - Zend\Stdlib\ErrorHandler; +use ArrayObject; +use GlobIterator; +use stdClass; +use Exception as BaseException; +use Zend\Cache\Exception; +use Zend\Cache\Storage; +use Zend\Cache\Storage\StorageInterface; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\ClearExpiredInterface; +use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\OptimizableInterface; +use Zend\Cache\Storage\TaggableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; +use Zend\Stdlib\ErrorHandler; /** * @category Zend diff --git a/src/Storage/Adapter/FilesystemIterator.php b/src/Storage/Adapter/FilesystemIterator.php index 1097792b9..f2ffee813 100644 --- a/src/Storage/Adapter/FilesystemIterator.php +++ b/src/Storage/Adapter/FilesystemIterator.php @@ -10,9 +10,9 @@ namespace Zend\Cache\Storage\Adapter; -use GlobIterator, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\IteratorInterface; +use GlobIterator; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\IteratorInterface; /** * @category Zend diff --git a/src/Storage/Adapter/KeyListIterator.php b/src/Storage/Adapter/KeyListIterator.php index 173d05b4f..6a78dd5a0 100644 --- a/src/Storage/Adapter/KeyListIterator.php +++ b/src/Storage/Adapter/KeyListIterator.php @@ -10,10 +10,10 @@ namespace Zend\Cache\Storage\Adapter; -use Countable, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\IteratorInterface, - Zend\Cache\Storage\StorageInterface; +use Countable; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\IteratorInterface; +use Zend\Cache\Storage\StorageInterface; /** * @category Zend diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index c63be2673..3b4ab6bd5 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -10,18 +10,18 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - Memcached as MemcachedResource, - MemcachedException, - stdClass, - Traversable, - Zend\Cache\Exception, - Zend\Cache\Storage\Event, - Zend\Cache\Storage\CallbackEvent, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface; +use ArrayObject; +use Memcached as MemcachedResource; +use MemcachedException; +use stdClass; +use Traversable; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\CallbackEvent; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @package Zend_Cache diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index 2b75186ee..89c627786 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -10,9 +10,9 @@ namespace Zend\Cache\Storage\Adapter; -use Memcached as MemcachedResource, - Zend\Cache\Exception, - Zend\Validator\Hostname; +use Memcached as MemcachedResource; +use Zend\Cache\Exception; +use Zend\Validator\Hostname; /** * These are options specific to the APC adapter diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index c8506d0a7..33857cbc0 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -10,17 +10,17 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - stdClass, - Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\ClearExpiredInterface, - Zend\Cache\Storage\ClearByPrefixInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\TaggableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface; +use ArrayObject; +use stdClass; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\ClearExpiredInterface; +use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\TaggableInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @category Zend diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 33f774f9b..7f0a77bd4 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -10,13 +10,13 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - stdClass, - Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface; +use ArrayObject; +use stdClass; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @package Zend_Cache diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index 4e0bced36..fd47f5ae8 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -10,13 +10,13 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - Zend\Cache\Exception, - Zend\Cache\Storage\ClearByNamespaceInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface, - Zend\Stdlib\ErrorHandler; +use ArrayObject; +use Zend\Cache\Exception; +use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; +use Zend\Stdlib\ErrorHandler; /** * @category Zend diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 52012f4f8..d2a6f8e2e 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -10,11 +10,11 @@ namespace Zend\Cache\Storage\Adapter; -use ArrayObject, - Zend\Cache\Exception, - Zend\Cache\Storage\ClearByNamespaceInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface; +use ArrayObject; +use Zend\Cache\Exception; +use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; /** * @category Zend diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index c31d9fa3a..e96dd43f6 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -10,10 +10,10 @@ namespace Zend\Cache\Storage; -use ArrayObject, - stdClass, - Zend\Cache\Exception, - Zend\EventManager\EventsCapableInterface; +use ArrayObject; +use stdClass; +use Zend\Cache\Exception; +use Zend\EventManager\EventsCapableInterface; /** * @category Zend diff --git a/src/Storage/Event.php b/src/Storage/Event.php index 5de6a9623..bf55b2cf6 100644 --- a/src/Storage/Event.php +++ b/src/Storage/Event.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Storage; -use ArrayObject, - Zend\EventManager\Event as BaseEvent; +use ArrayObject; +use Zend\EventManager\Event as BaseEvent; /** * @category Zend diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index f646f451a..525ebd597 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Storage; -use ArrayObject, - Exception; +use ArrayObject; +use Exception; /** * @category Zend diff --git a/src/Storage/Plugin/ClearExpiredByFactor.php b/src/Storage/Plugin/ClearExpiredByFactor.php index d5d4da09a..98213aa89 100644 --- a/src/Storage/Plugin/ClearExpiredByFactor.php +++ b/src/Storage/Plugin/ClearExpiredByFactor.php @@ -10,12 +10,12 @@ namespace Zend\Cache\Storage\Plugin; -use Traversable, - Zend\EventManager\EventManagerInterface, - Zend\Cache\Exception, - Zend\Cache\Storage\ClearExpiredInterface, - Zend\Cache\Storage\StorageInterface, - Zend\Cache\Storage\PostEvent; +use Traversable; +use Zend\EventManager\EventManagerInterface; +use Zend\Cache\Exception; +use Zend\Cache\Storage\ClearExpiredInterface; +use Zend\Cache\Storage\StorageInterface; +use Zend\Cache\Storage\PostEvent; /** * @category Zend diff --git a/src/Storage/Plugin/ExceptionHandler.php b/src/Storage/Plugin/ExceptionHandler.php index 9a5082860..b70fdd85c 100644 --- a/src/Storage/Plugin/ExceptionHandler.php +++ b/src/Storage/Plugin/ExceptionHandler.php @@ -10,10 +10,10 @@ namespace Zend\Cache\Storage\Plugin; -use Traversable, - Zend\Cache\Exception, - Zend\Cache\Storage\ExceptionEvent, - Zend\EventManager\EventManagerInterface; +use Traversable; +use Zend\Cache\Exception; +use Zend\Cache\Storage\ExceptionEvent; +use Zend\EventManager\EventManagerInterface; /** * @category Zend diff --git a/src/Storage/Plugin/IgnoreUserAbort.php b/src/Storage/Plugin/IgnoreUserAbort.php index c1de893fa..23a69e4fd 100644 --- a/src/Storage/Plugin/IgnoreUserAbort.php +++ b/src/Storage/Plugin/IgnoreUserAbort.php @@ -10,9 +10,9 @@ namespace Zend\Cache\Storage\Plugin; -use Zend\Cache\Exception, - Zend\Cache\Storage\Event, - Zend\EventManager\EventManagerInterface; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Event; +use Zend\EventManager\EventManagerInterface; /** * @category Zend diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index 886b80b79..0197c7868 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -10,11 +10,11 @@ namespace Zend\Cache\Storage\Plugin; -use Traversable, - Zend\Cache\Exception, - Zend\Cache\Storage\OptimizableInterface, - Zend\Cache\Storage\PostEvent, - Zend\EventManager\EventManagerInterface; +use Traversable; +use Zend\Cache\Exception; +use Zend\Cache\Storage\OptimizableInterface; +use Zend\Cache\Storage\PostEvent; +use Zend\EventManager\EventManagerInterface; /** * @category Zend diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index 820c87510..f0ddf8028 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -10,10 +10,10 @@ namespace Zend\Cache\Storage\Plugin; -use Zend\Cache\Exception, - Zend\Serializer\Adapter\AdapterInterface as SerializerAdapter, - Zend\Serializer\Serializer as SerializerFactory, - Zend\Stdlib\AbstractOptions; +use Zend\Cache\Exception; +use Zend\Serializer\Adapter\AdapterInterface as SerializerAdapter; +use Zend\Serializer\Serializer as SerializerFactory; +use Zend\Stdlib\AbstractOptions; /** * @category Zend diff --git a/src/Storage/Plugin/Serializer.php b/src/Storage/Plugin/Serializer.php index 6ce0fd7cd..ec8c46ba8 100644 --- a/src/Storage/Plugin/Serializer.php +++ b/src/Storage/Plugin/Serializer.php @@ -10,13 +10,13 @@ namespace Zend\Cache\Storage\Plugin; -use stdClass, - Traversable, - Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\Event, - Zend\Cache\Storage\PostEvent, - Zend\EventManager\EventManagerInterface; +use stdClass; +use Traversable; +use Zend\Cache\Exception; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\PostEvent; +use Zend\EventManager\EventManagerInterface; /** * @category Zend diff --git a/test/Storage/Adapter/AbstractAdapterTest.php b/test/Storage/Adapter/AbstractAdapterTest.php index 5e328716a..dd3b902d3 100644 --- a/test/Storage/Adapter/AbstractAdapterTest.php +++ b/test/Storage/Adapter/AbstractAdapterTest.php @@ -10,8 +10,8 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache, - Zend\Cache\Exception; +use Zend\Cache; +use Zend\Cache\Exception; /** * @category Zend diff --git a/test/Storage/Adapter/AbstractZendServerTest.php b/test/Storage/Adapter/AbstractZendServerTest.php index f1a89e412..51645dd2b 100644 --- a/test/Storage/Adapter/AbstractZendServerTest.php +++ b/test/Storage/Adapter/AbstractZendServerTest.php @@ -10,9 +10,9 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache\Storage\StorageInterface, - Zend\Cache\Storage\Adapter\AdapterOptions, - Zend\Cache\Storage\Adapter\AbstractZendServer; +use Zend\Cache\Storage\StorageInterface; +use Zend\Cache\Storage\Adapter\AdapterOptions; +use Zend\Cache\Storage\Adapter\AbstractZendServer; /** * @category Zend diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index ceaec64fc..654400064 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -10,6 +10,7 @@ namespace ZendTest\Cache\Storage\Adapter; +<<<<<<< HEAD use Zend\Http\Header\Expires; use Zend\Cache\Storage\IterableInterface, @@ -23,6 +24,19 @@ Zend\Cache\Storage\TagableInterface, Zend\Cache, Zend\Stdlib\ErrorHandler; +======= +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\IteratorInterface; +use Zend\Cache\Storage\StorageInterface; +use Zend\Cache\Storage\ClearExpiredInterface; +use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\OptimizableInterface; +use Zend\Cache\Storage\TagableInterface; +use Zend\Cache; +use Zend\Stdlib\ErrorHandler; +>>>>>>> aeee67a... Fix use statements in Zend\Cache /** * PHPUnit test case diff --git a/test/Storage/Adapter/MemcachedTest.php b/test/Storage/Adapter/MemcachedTest.php index d589e7ce0..ecdac3ecc 100644 --- a/test/Storage/Adapter/MemcachedTest.php +++ b/test/Storage/Adapter/MemcachedTest.php @@ -10,8 +10,8 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache, - Zend\Cache\Exception; +use Zend\Cache; +use Zend\Cache\Exception; /** * @category Zend diff --git a/test/Storage/Adapter/WinCacheTest.php b/test/Storage/Adapter/WinCacheTest.php index 724ee659b..cd789c4de 100644 --- a/test/Storage/Adapter/WinCacheTest.php +++ b/test/Storage/Adapter/WinCacheTest.php @@ -9,8 +9,8 @@ */ namespace ZendTest\Cache\Storage\Adapter; -use \Zend\Cache, - \Zend\Cache\Exception; +use \Zend\Cache; +use \Zend\Cache\Exception; /** * @category Zend diff --git a/test/Storage/Adapter/ZendServerDiskTest.php b/test/Storage/Adapter/ZendServerDiskTest.php index e2666301a..ff32b5148 100644 --- a/test/Storage/Adapter/ZendServerDiskTest.php +++ b/test/Storage/Adapter/ZendServerDiskTest.php @@ -10,8 +10,8 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache, - Zend\Cache\Exception; +use Zend\Cache; +use Zend\Cache\Exception; /** * @category Zend diff --git a/test/Storage/Adapter/ZendServerShmTest.php b/test/Storage/Adapter/ZendServerShmTest.php index 8a65d8402..32cb1e358 100644 --- a/test/Storage/Adapter/ZendServerShmTest.php +++ b/test/Storage/Adapter/ZendServerShmTest.php @@ -10,8 +10,8 @@ namespace ZendTest\Cache\Storage\Adapter; -use Zend\Cache, - Zend\Cache\Exception; +use Zend\Cache; +use Zend\Cache\Exception; /** * @category Zend diff --git a/test/Storage/CapabilitiesTest.php b/test/Storage/CapabilitiesTest.php index 02745777f..7ed5f5eb7 100644 --- a/test/Storage/CapabilitiesTest.php +++ b/test/Storage/CapabilitiesTest.php @@ -10,8 +10,8 @@ namespace ZendTest\Cache\Storage; -use Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\Adapter\Memory as MemoryAdapter; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\Adapter\Memory as MemoryAdapter; /** * @category Zend diff --git a/test/Storage/Plugin/ClearExpiredByFactorTest.php b/test/Storage/Plugin/ClearExpiredByFactorTest.php index 0bf5311e1..c37293b04 100644 --- a/test/Storage/Plugin/ClearExpiredByFactorTest.php +++ b/test/Storage/Plugin/ClearExpiredByFactorTest.php @@ -9,10 +9,10 @@ */ namespace ZendTest\Cache\Storage\Plugin; -use Zend\Cache, - Zend\Cache\Storage\PostEvent, - ZendTest\Cache\Storage\TestAsset\ClearExpiredMockAdapter, - ArrayObject; +use Zend\Cache; +use Zend\Cache\Storage\PostEvent; +use ZendTest\Cache\Storage\TestAsset\ClearExpiredMockAdapter; +use ArrayObject; class ClearExpiredByFactorTest extends CommonPluginTest { diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php index f281a6704..050f33665 100644 --- a/test/Storage/Plugin/ExceptionHandlerTest.php +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -9,10 +9,10 @@ */ namespace ZendTest\Cache\Storage\Plugin; -use Zend\Cache, - Zend\Cache\Storage\ExceptionEvent, - ZendTest\Cache\Storage\TestAsset\MockAdapter, - ArrayObject; +use Zend\Cache; +use Zend\Cache\Storage\ExceptionEvent; +use ZendTest\Cache\Storage\TestAsset\MockAdapter; +use ArrayObject; class ExceptionHandlerTest extends CommonPluginTest { diff --git a/test/Storage/Plugin/IgnoreUserAbortTest.php b/test/Storage/Plugin/IgnoreUserAbortTest.php index b7ec6252c..c5503659a 100644 --- a/test/Storage/Plugin/IgnoreUserAbortTest.php +++ b/test/Storage/Plugin/IgnoreUserAbortTest.php @@ -9,11 +9,11 @@ */ namespace ZendTest\Cache\Storage\Plugin; -use Zend\Cache, - Zend\Cache\Storage\Event, - Zend\Cache\Storage\PostEvent, - Zend\Serializer, - ArrayObject; +use Zend\Cache; +use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\PostEvent; +use Zend\Serializer; +use ArrayObject; /** * @category Zend diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index 727fe3828..6a74a5f27 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -9,10 +9,10 @@ */ namespace ZendTest\Cache\Storage\Plugin; -use Zend\Cache, - Zend\Cache\Storage\PostEvent, - ZendTest\Cache\Storage\TestAsset\OptimizableMockAdapter, - ArrayObject; +use Zend\Cache; +use Zend\Cache\Storage\PostEvent; +use ZendTest\Cache\Storage\TestAsset\OptimizableMockAdapter; +use ArrayObject; class OptimizeByFactorTest extends CommonPluginTest { diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index a98874450..ebf0aca43 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -9,11 +9,11 @@ */ namespace ZendTest\Cache\Storage\Plugin; -use Zend\Cache, - Zend\Cache\Storage\Event, - Zend\Cache\Storage\PostEvent, - Zend\Serializer, - ArrayObject; +use Zend\Cache; +use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\PostEvent; +use Zend\Serializer; +use ArrayObject; /** * @category Zend diff --git a/test/Storage/TestAsset/MockPlugin.php b/test/Storage/TestAsset/MockPlugin.php index 7b26c6f33..278d6a718 100644 --- a/test/Storage/TestAsset/MockPlugin.php +++ b/test/Storage/TestAsset/MockPlugin.php @@ -10,10 +10,10 @@ namespace ZendTest\Cache\Storage\TestAsset; -use Zend\Cache\Storage\Plugin, - Zend\Cache\Storage\Plugin\AbstractPlugin, - Zend\EventManager\EventManagerInterface, - Zend\EventManager\Event; +use Zend\Cache\Storage\Plugin; +use Zend\Cache\Storage\Plugin\AbstractPlugin; +use Zend\EventManager\EventManagerInterface; +use Zend\EventManager\Event; class MockPlugin extends AbstractPlugin { From d5857c5559c8faa526589439e6a6b3b3bad0f4b4 Mon Sep 17 00:00:00 2001 From: prolic Date: Sun, 8 Jul 2012 15:02:20 +0200 Subject: [PATCH 285/311] fix CommonAdapterTest --- test/Storage/Adapter/CommonAdapterTest.php | 24 ++++------------------ 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index 654400064..255f217d0 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -10,21 +10,6 @@ namespace ZendTest\Cache\Storage\Adapter; -<<<<<<< HEAD -use Zend\Http\Header\Expires; - -use Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\IteratorInterface, - Zend\Cache\Storage\StorageInterface, - Zend\Cache\Storage\ClearExpiredInterface, - Zend\Cache\Storage\ClearByNamespaceInterface, - Zend\Cache\Storage\ClearByPrefixInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\OptimizableInterface, - Zend\Cache\Storage\TagableInterface, - Zend\Cache, - Zend\Stdlib\ErrorHandler; -======= use Zend\Cache\Storage\IterableInterface; use Zend\Cache\Storage\IteratorInterface; use Zend\Cache\Storage\StorageInterface; @@ -33,10 +18,9 @@ use Zend\Cache\Storage\ClearByPrefixInterface; use Zend\Cache\Storage\FlushableInterface; use Zend\Cache\Storage\OptimizableInterface; -use Zend\Cache\Storage\TagableInterface; -use Zend\Cache; +use Zend\Cache\Storage\TaggableInterface; +use Zend\Http\Header\Expires; use Zend\Stdlib\ErrorHandler; ->>>>>>> aeee67a... Fix use statements in Zend\Cache /** * PHPUnit test case @@ -1010,8 +994,8 @@ public function testClearExpired() public function testTagable() { - if ( !($this->_storage instanceof TagableInterface) ) { - $this->markTestSkipped("Storage doesn't implement TagableInterface"); + if ( !($this->_storage instanceof TaggableInterface) ) { + $this->markTestSkipped("Storage doesn't implement TaggableInterface"); } $this->assertSame(array(), $this->_storage->setItems(array( From c2b67caffc08cb4207790337891c29d516f0912b Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 9 Jul 2012 11:32:16 -0500 Subject: [PATCH 286/311] [zen-49] Sort import statements - Import statements should be sorted alphabetically - "implements" lists should as well --- src/Pattern/AbstractPattern.php | 2 +- src/Storage/Adapter/AbstractAdapter.php | 2 +- src/Storage/Adapter/AbstractZendServer.php | 2 +- src/Storage/Adapter/Apc.php | 6 ++--- src/Storage/Adapter/ApcIterator.php | 1 - src/Storage/Adapter/Dba.php | 28 ++++++++++----------- src/Storage/Adapter/DbaIterator.php | 5 ++-- src/Storage/Adapter/Filesystem.php | 8 +++--- src/Storage/Adapter/FilesystemIterator.php | 1 - src/Storage/Adapter/KeyListIterator.php | 1 - src/Storage/Adapter/Memcached.php | 6 ++--- src/Storage/Adapter/Memory.php | 4 +-- src/Storage/Adapter/WinCache.php | 4 +-- src/Storage/Adapter/ZendServerDisk.php | 11 ++++---- src/Storage/Adapter/ZendServerShm.php | 7 +++--- src/Storage/IterableInterface.php | 4 ++- src/Storage/IteratorInterface.php | 4 ++- src/Storage/Plugin/ClearExpiredByFactor.php | 2 +- 18 files changed, 50 insertions(+), 48 deletions(-) diff --git a/src/Pattern/AbstractPattern.php b/src/Pattern/AbstractPattern.php index c871c98bc..c96831776 100644 --- a/src/Pattern/AbstractPattern.php +++ b/src/Pattern/AbstractPattern.php @@ -10,8 +10,8 @@ namespace Zend\Cache\Pattern; -use Zend\Cache\Exception; use Traversable; +use Zend\Cache\Exception; /** * @category Zend diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 7d252a628..153fce6c0 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -18,8 +18,8 @@ use Zend\Cache\Storage\Capabilities; use Zend\Cache\Storage\Event; use Zend\Cache\Storage\ExceptionEvent; -use Zend\Cache\Storage\PostEvent; use Zend\Cache\Storage\Plugin; +use Zend\Cache\Storage\PostEvent; use Zend\Cache\Storage\StorageInterface; use Zend\EventManager\EventManager; use Zend\EventManager\EventsCapableInterface; diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index ee98fd79d..b18991add 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -12,8 +12,8 @@ use ArrayObject; use stdClass; -use Zend\Cache\Storage\Capabilities; use Zend\Cache\Exception; +use Zend\Cache\Storage\Capabilities; /** * @category Zend diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 5c18986eb..00447fcf9 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -15,12 +15,12 @@ use stdClass; use Traversable; use Zend\Cache\Exception; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; use Zend\Cache\Storage\ClearByPrefixInterface; use Zend\Cache\Storage\ClearByNamespaceInterface; use Zend\Cache\Storage\FlushableInterface; use Zend\Cache\Storage\IterableInterface; -use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; /** @@ -29,11 +29,11 @@ * @subpackage Storage */ class Apc extends AbstractAdapter implements - ClearByPrefixInterface, + AvailableSpaceCapableInterface, ClearByNamespaceInterface, + ClearByPrefixInterface, FlushableInterface, IterableInterface, - AvailableSpaceCapableInterface, TotalSpaceCapableInterface { /** diff --git a/src/Storage/Adapter/ApcIterator.php b/src/Storage/Adapter/ApcIterator.php index b53ab9a36..80f2576c1 100644 --- a/src/Storage/Adapter/ApcIterator.php +++ b/src/Storage/Adapter/ApcIterator.php @@ -11,7 +11,6 @@ namespace Zend\Cache\Storage\Adapter; use APCIterator as BaseApcIterator; -use Zend\Cache\Storage\IterableInterface; use Zend\Cache\Storage\IteratorInterface; /** diff --git a/src/Storage/Adapter/Dba.php b/src/Storage/Adapter/Dba.php index 86b50152e..9dbb5845c 100644 --- a/src/Storage/Adapter/Dba.php +++ b/src/Storage/Adapter/Dba.php @@ -10,26 +10,26 @@ namespace Zend\Cache\Storage\Adapter; -use stdClass, - Zend\Cache\Exception, - Zend\Cache\Storage\Capabilities, - Zend\Cache\Storage\ClearByPrefixInterface, - Zend\Cache\Storage\ClearByNamespaceInterface, - Zend\Cache\Storage\FlushableInterface, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\AvailableSpaceCapableInterface, - Zend\Cache\Storage\TotalSpaceCapableInterface, - Zend\Cache\Storage\OptimizableInterface, - Zend\Stdlib\ErrorHandler; +use stdClass; +use Zend\Cache\Exception; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; +use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\FlushableInterface; +use Zend\Cache\Storage\IterableInterface; +use Zend\Cache\Storage\OptimizableInterface; +use Zend\Cache\Storage\TotalSpaceCapableInterface; +use Zend\Stdlib\ErrorHandler; class Dba extends AbstractAdapter implements - TotalSpaceCapableInterface, AvailableSpaceCapableInterface, - FlushableInterface, ClearByNamespaceInterface, ClearByPrefixInterface, + FlushableInterface, + IterableInterface, OptimizableInterface, - IterableInterface + TotalSpaceCapableInterface { /** * The DBA resource handle diff --git a/src/Storage/Adapter/DbaIterator.php b/src/Storage/Adapter/DbaIterator.php index 907295e30..67e0cfe9d 100644 --- a/src/Storage/Adapter/DbaIterator.php +++ b/src/Storage/Adapter/DbaIterator.php @@ -10,9 +10,8 @@ namespace Zend\Cache\Storage\Adapter; -use Zend\Cache\Exception, - Zend\Cache\Storage\IterableInterface, - Zend\Cache\Storage\IteratorInterface; +use Zend\Cache\Exception; +use Zend\Cache\Storage\IteratorInterface; /** * @category Zend diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index c563ab2e8..30fa80173 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -11,20 +11,20 @@ namespace Zend\Cache\Storage\Adapter; use ArrayObject; +use Exception as BaseException; use GlobIterator; use stdClass; -use Exception as BaseException; use Zend\Cache\Exception; use Zend\Cache\Storage; -use Zend\Cache\Storage\StorageInterface; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; -use Zend\Cache\Storage\ClearExpiredInterface; use Zend\Cache\Storage\ClearByNamespaceInterface; use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\ClearExpiredInterface; use Zend\Cache\Storage\FlushableInterface; use Zend\Cache\Storage\IterableInterface; -use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\OptimizableInterface; +use Zend\Cache\Storage\StorageInterface; use Zend\Cache\Storage\TaggableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; use Zend\Stdlib\ErrorHandler; diff --git a/src/Storage/Adapter/FilesystemIterator.php b/src/Storage/Adapter/FilesystemIterator.php index f2ffee813..c745ac033 100644 --- a/src/Storage/Adapter/FilesystemIterator.php +++ b/src/Storage/Adapter/FilesystemIterator.php @@ -11,7 +11,6 @@ namespace Zend\Cache\Storage\Adapter; use GlobIterator; -use Zend\Cache\Storage\IterableInterface; use Zend\Cache\Storage\IteratorInterface; /** diff --git a/src/Storage/Adapter/KeyListIterator.php b/src/Storage/Adapter/KeyListIterator.php index 6a78dd5a0..800089f18 100644 --- a/src/Storage/Adapter/KeyListIterator.php +++ b/src/Storage/Adapter/KeyListIterator.php @@ -11,7 +11,6 @@ namespace Zend\Cache\Storage\Adapter; use Countable; -use Zend\Cache\Storage\IterableInterface; use Zend\Cache\Storage\IteratorInterface; use Zend\Cache\Storage\StorageInterface; diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 3b4ab6bd5..732192d41 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -16,11 +16,11 @@ use stdClass; use Traversable; use Zend\Cache\Exception; -use Zend\Cache\Storage\Event; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\CallbackEvent; use Zend\Cache\Storage\Capabilities; +use Zend\Cache\Storage\Event; use Zend\Cache\Storage\FlushableInterface; -use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; /** @@ -29,8 +29,8 @@ * @subpackage Storage */ class Memcached extends AbstractAdapter implements - FlushableInterface, AvailableSpaceCapableInterface, + FlushableInterface, TotalSpaceCapableInterface { /** diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index 33857cbc0..a779f735e 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -13,13 +13,13 @@ use ArrayObject; use stdClass; use Zend\Cache\Exception; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; -use Zend\Cache\Storage\ClearExpiredInterface; use Zend\Cache\Storage\ClearByPrefixInterface; +use Zend\Cache\Storage\ClearExpiredInterface; use Zend\Cache\Storage\FlushableInterface; use Zend\Cache\Storage\IterableInterface; use Zend\Cache\Storage\TaggableInterface; -use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; /** diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 7f0a77bd4..1f638ce90 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -13,9 +13,9 @@ use ArrayObject; use stdClass; use Zend\Cache\Exception; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; use Zend\Cache\Storage\FlushableInterface; -use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; /** @@ -24,8 +24,8 @@ * @subpackage Storage */ class WinCache extends AbstractAdapter implements - FlushableInterface, AvailableSpaceCapableInterface, + FlushableInterface, TotalSpaceCapableInterface { diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index fd47f5ae8..b8c8d28aa 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -12,9 +12,9 @@ use ArrayObject; use Zend\Cache\Exception; +use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\ClearByNamespaceInterface; use Zend\Cache\Storage\FlushableInterface; -use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; use Zend\Stdlib\ErrorHandler; @@ -23,10 +23,11 @@ * @package Zend_Cache * @subpackage Storage */ -class ZendServerDisk - extends AbstractZendServer - implements FlushableInterface, ClearByNamespaceInterface, - AvailableSpaceCapableInterface, TotalSpaceCapableInterface +class ZendServerDisk extends AbstractZendServer implements + AvailableSpaceCapableInterface, + ClearByNamespaceInterface, + FlushableInterface, + TotalSpaceCapableInterface { /** diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index d2a6f8e2e..9d2ebba9c 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -21,9 +21,10 @@ * @package Zend_Cache * @subpackage Storage */ -class ZendServerShm - extends AbstractZendServer - implements FlushableInterface, ClearByNamespaceInterface, TotalSpaceCapableInterface +class ZendServerShm extends AbstractZendServer implements + ClearByNamespaceInterface, + FlushableInterface, + TotalSpaceCapableInterface { /** diff --git a/src/Storage/IterableInterface.php b/src/Storage/IterableInterface.php index 0118845b5..9c9292b18 100644 --- a/src/Storage/IterableInterface.php +++ b/src/Storage/IterableInterface.php @@ -10,6 +10,8 @@ namespace Zend\Cache\Storage; +use IteratorAggregate; + /** * @category Zend * @package Zend_Cache @@ -17,6 +19,6 @@ * * @method IteratorInterface getIterator() Get the storage iterator */ -interface IterableInterface extends \IteratorAggregate +interface IterableInterface extends IteratorAggregate { } diff --git a/src/Storage/IteratorInterface.php b/src/Storage/IteratorInterface.php index 81405fec9..1cfea48cd 100644 --- a/src/Storage/IteratorInterface.php +++ b/src/Storage/IteratorInterface.php @@ -10,12 +10,14 @@ namespace Zend\Cache\Storage; +use Iterator; + /** * @category Zend * @package Zend_Cache * @subpackage Storage */ -interface IteratorInterface extends \Iterator +interface IteratorInterface extends Iterator { const CURRENT_AS_SELF = 0; diff --git a/src/Storage/Plugin/ClearExpiredByFactor.php b/src/Storage/Plugin/ClearExpiredByFactor.php index 98213aa89..e7713e54c 100644 --- a/src/Storage/Plugin/ClearExpiredByFactor.php +++ b/src/Storage/Plugin/ClearExpiredByFactor.php @@ -11,11 +11,11 @@ namespace Zend\Cache\Storage\Plugin; use Traversable; -use Zend\EventManager\EventManagerInterface; use Zend\Cache\Exception; use Zend\Cache\Storage\ClearExpiredInterface; use Zend\Cache\Storage\StorageInterface; use Zend\Cache\Storage\PostEvent; +use Zend\EventManager\EventManagerInterface; /** * @category Zend From bd99c5ccb32bf19a0582c0a4169013ea2af9fc58 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Mon, 9 Jul 2012 16:46:59 -0500 Subject: [PATCH 287/311] [zen-49] Correct import statements across framework - Ran a script that would create multiple import statements out of multi-line import statements, and which would sort all import statements in alphabetic order. Script is at https://gist.github.com/3079222 and was run by dropping into the library/Zend folder and typing (in zsh) "for file in **/*.php;do php /path/to/replace-uses.php $file; done" --- src/Storage/Adapter/Apc.php | 2 +- src/Storage/Plugin/ClearExpiredByFactor.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index 00447fcf9..de5bd9c27 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -17,8 +17,8 @@ use Zend\Cache\Exception; use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; -use Zend\Cache\Storage\ClearByPrefixInterface; use Zend\Cache\Storage\ClearByNamespaceInterface; +use Zend\Cache\Storage\ClearByPrefixInterface; use Zend\Cache\Storage\FlushableInterface; use Zend\Cache\Storage\IterableInterface; use Zend\Cache\Storage\TotalSpaceCapableInterface; diff --git a/src/Storage/Plugin/ClearExpiredByFactor.php b/src/Storage/Plugin/ClearExpiredByFactor.php index e7713e54c..14bd591f9 100644 --- a/src/Storage/Plugin/ClearExpiredByFactor.php +++ b/src/Storage/Plugin/ClearExpiredByFactor.php @@ -13,8 +13,8 @@ use Traversable; use Zend\Cache\Exception; use Zend\Cache\Storage\ClearExpiredInterface; -use Zend\Cache\Storage\StorageInterface; use Zend\Cache\Storage\PostEvent; +use Zend\Cache\Storage\StorageInterface; use Zend\EventManager\EventManagerInterface; /** From 18812d8a562772d70e760310ce8b2f09e9fffd30 Mon Sep 17 00:00:00 2001 From: Maks3w Date: Wed, 11 Jul 2012 22:20:59 +0200 Subject: [PATCH 288/311] Add blank lines around the use block --- test/Pattern/CaptureCacheTest.php | 1 + test/Pattern/ClassCacheTest.php | 1 + test/Pattern/ObjectCacheTest.php | 1 + test/Storage/Adapter/AbstractDbaTest.php | 1 + test/Storage/Adapter/ApcTest.php | 1 + test/Storage/Adapter/DbaDb2Test.php | 1 + test/Storage/Adapter/DbaDb3Test.php | 1 + test/Storage/Adapter/DbaDb4Test.php | 1 + test/Storage/Adapter/DbaFlatfileTest.php | 1 + test/Storage/Adapter/DbaGdbmTest.php | 1 + test/Storage/Adapter/DbaInifileTest.php | 1 + test/Storage/Adapter/DbaQdbmTest.php | 1 + test/Storage/Adapter/MemoryTest.php | 1 + test/Storage/Adapter/WinCacheTest.php | 1 + test/Storage/Plugin/ClearExpiredByFactorTest.php | 1 + test/Storage/Plugin/ExceptionHandlerTest.php | 1 + test/Storage/Plugin/IgnoreUserAbortTest.php | 1 + test/Storage/Plugin/OptimizeByFactorTest.php | 1 + test/Storage/Plugin/SerializerTest.php | 1 + test/Storage/TestAsset/MockAdapter.php | 1 + test/TestAsset/DummyPattern.php | 1 + test/TestAsset/DummyStorageAdapter.php | 1 + test/TestAsset/DummyStoragePlugin.php | 1 + 23 files changed, 23 insertions(+) diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php index 104e00128..36cc3d863 100644 --- a/test/Pattern/CaptureCacheTest.php +++ b/test/Pattern/CaptureCacheTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Pattern; + use Zend\Cache; /** diff --git a/test/Pattern/ClassCacheTest.php b/test/Pattern/ClassCacheTest.php index 1de4308bf..bf70833ec 100644 --- a/test/Pattern/ClassCacheTest.php +++ b/test/Pattern/ClassCacheTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Pattern; + use Zend\Cache; /** diff --git a/test/Pattern/ObjectCacheTest.php b/test/Pattern/ObjectCacheTest.php index f88623186..ca07bb976 100644 --- a/test/Pattern/ObjectCacheTest.php +++ b/test/Pattern/ObjectCacheTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Pattern; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/AbstractDbaTest.php b/test/Storage/Adapter/AbstractDbaTest.php index 121450f2c..1dae323f3 100644 --- a/test/Storage/Adapter/AbstractDbaTest.php +++ b/test/Storage/Adapter/AbstractDbaTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/ApcTest.php b/test/Storage/Adapter/ApcTest.php index 1fd89dcdf..25621604a 100644 --- a/test/Storage/Adapter/ApcTest.php +++ b/test/Storage/Adapter/ApcTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaDb2Test.php b/test/Storage/Adapter/DbaDb2Test.php index 45442251f..d137785b7 100644 --- a/test/Storage/Adapter/DbaDb2Test.php +++ b/test/Storage/Adapter/DbaDb2Test.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaDb3Test.php b/test/Storage/Adapter/DbaDb3Test.php index c260eda32..f10efc06b 100644 --- a/test/Storage/Adapter/DbaDb3Test.php +++ b/test/Storage/Adapter/DbaDb3Test.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaDb4Test.php b/test/Storage/Adapter/DbaDb4Test.php index 6eecc8e39..f82b2768c 100644 --- a/test/Storage/Adapter/DbaDb4Test.php +++ b/test/Storage/Adapter/DbaDb4Test.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaFlatfileTest.php b/test/Storage/Adapter/DbaFlatfileTest.php index 68732b8da..c56df792f 100644 --- a/test/Storage/Adapter/DbaFlatfileTest.php +++ b/test/Storage/Adapter/DbaFlatfileTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaGdbmTest.php b/test/Storage/Adapter/DbaGdbmTest.php index 13fa79a92..65967d996 100644 --- a/test/Storage/Adapter/DbaGdbmTest.php +++ b/test/Storage/Adapter/DbaGdbmTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaInifileTest.php b/test/Storage/Adapter/DbaInifileTest.php index ec4c74d96..2b33a2c6a 100644 --- a/test/Storage/Adapter/DbaInifileTest.php +++ b/test/Storage/Adapter/DbaInifileTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/DbaQdbmTest.php b/test/Storage/Adapter/DbaQdbmTest.php index 172a5bc80..66d08ecb4 100644 --- a/test/Storage/Adapter/DbaQdbmTest.php +++ b/test/Storage/Adapter/DbaQdbmTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/MemoryTest.php b/test/Storage/Adapter/MemoryTest.php index 5b0ddc461..e404080b9 100644 --- a/test/Storage/Adapter/MemoryTest.php +++ b/test/Storage/Adapter/MemoryTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; /** diff --git a/test/Storage/Adapter/WinCacheTest.php b/test/Storage/Adapter/WinCacheTest.php index 55384a087..8d3fd39c8 100644 --- a/test/Storage/Adapter/WinCacheTest.php +++ b/test/Storage/Adapter/WinCacheTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Adapter; + use Zend\Cache; use Zend\Cache\Exception; diff --git a/test/Storage/Plugin/ClearExpiredByFactorTest.php b/test/Storage/Plugin/ClearExpiredByFactorTest.php index c37293b04..cad736fa8 100644 --- a/test/Storage/Plugin/ClearExpiredByFactorTest.php +++ b/test/Storage/Plugin/ClearExpiredByFactorTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Plugin; + use Zend\Cache; use Zend\Cache\Storage\PostEvent; use ZendTest\Cache\Storage\TestAsset\ClearExpiredMockAdapter; diff --git a/test/Storage/Plugin/ExceptionHandlerTest.php b/test/Storage/Plugin/ExceptionHandlerTest.php index 050f33665..16e414ec4 100644 --- a/test/Storage/Plugin/ExceptionHandlerTest.php +++ b/test/Storage/Plugin/ExceptionHandlerTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Plugin; + use Zend\Cache; use Zend\Cache\Storage\ExceptionEvent; use ZendTest\Cache\Storage\TestAsset\MockAdapter; diff --git a/test/Storage/Plugin/IgnoreUserAbortTest.php b/test/Storage/Plugin/IgnoreUserAbortTest.php index c5503659a..e97d687c2 100644 --- a/test/Storage/Plugin/IgnoreUserAbortTest.php +++ b/test/Storage/Plugin/IgnoreUserAbortTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Plugin; + use Zend\Cache; use Zend\Cache\Storage\Event; use Zend\Cache\Storage\PostEvent; diff --git a/test/Storage/Plugin/OptimizeByFactorTest.php b/test/Storage/Plugin/OptimizeByFactorTest.php index 6a74a5f27..99563d80c 100644 --- a/test/Storage/Plugin/OptimizeByFactorTest.php +++ b/test/Storage/Plugin/OptimizeByFactorTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Plugin; + use Zend\Cache; use Zend\Cache\Storage\PostEvent; use ZendTest\Cache\Storage\TestAsset\OptimizableMockAdapter; diff --git a/test/Storage/Plugin/SerializerTest.php b/test/Storage/Plugin/SerializerTest.php index ebf0aca43..c089b07c0 100644 --- a/test/Storage/Plugin/SerializerTest.php +++ b/test/Storage/Plugin/SerializerTest.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\Plugin; + use Zend\Cache; use Zend\Cache\Storage\Event; use Zend\Cache\Storage\PostEvent; diff --git a/test/Storage/TestAsset/MockAdapter.php b/test/Storage/TestAsset/MockAdapter.php index 4d6227b5b..7642334d6 100644 --- a/test/Storage/TestAsset/MockAdapter.php +++ b/test/Storage/TestAsset/MockAdapter.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\Storage\TestAsset; + use Zend\Cache\Storage\Adapter\AbstractAdapter; class MockAdapter extends AbstractAdapter diff --git a/test/TestAsset/DummyPattern.php b/test/TestAsset/DummyPattern.php index 4b98c47ae..7cc461e73 100644 --- a/test/TestAsset/DummyPattern.php +++ b/test/TestAsset/DummyPattern.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\TestAsset; + use Zend\Cache; class DummyPattern extends Cache\Pattern\AbstractPattern diff --git a/test/TestAsset/DummyStorageAdapter.php b/test/TestAsset/DummyStorageAdapter.php index f3ea7707f..f8e333fcd 100644 --- a/test/TestAsset/DummyStorageAdapter.php +++ b/test/TestAsset/DummyStorageAdapter.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\TestAsset; + use Zend\Cache\Storage\Adapter\AbstractAdapter; class DummyStorageAdapter extends AbstractAdapter diff --git a/test/TestAsset/DummyStoragePlugin.php b/test/TestAsset/DummyStoragePlugin.php index 397a2fbb9..8c7e27391 100644 --- a/test/TestAsset/DummyStoragePlugin.php +++ b/test/TestAsset/DummyStoragePlugin.php @@ -9,6 +9,7 @@ */ namespace ZendTest\Cache\TestAsset; + use Zend\Cache\Storage\Plugin\AbstractPlugin; class DummyStoragePlugin extends AbstractPlugin From 073b1263ee0340941452fa186c10061c5b6c92f5 Mon Sep 17 00:00:00 2001 From: Maks3w Date: Thu, 12 Jul 2012 21:11:36 +0200 Subject: [PATCH 289/311] [PSR-2] fixers=braces,elseif,short_tag,php_closing_tag,trailing_spaces,linefeed Applied php-cs-fixer --fixers=braces,elseif,short_tag,php_closing_tag,trailing_spaces,linefeed --- src/Exception/BadMethodCallException.php | 2 +- src/Exception/InvalidArgumentException.php | 2 +- src/Exception/UnexpectedValueException.php | 2 +- src/Exception/UnsupportedMethodCallException.php | 2 +- src/PatternPluginManager.php | 10 +++++----- src/Storage/Adapter/ZendServerDisk.php | 6 +++--- src/Storage/Adapter/ZendServerShm.php | 2 +- src/Storage/AdapterPluginManager.php | 10 +++++----- src/Storage/PluginManager.php | 10 +++++----- test/Pattern/CallbackCacheTest.php | 3 ++- 10 files changed, 25 insertions(+), 24 deletions(-) diff --git a/src/Exception/BadMethodCallException.php b/src/Exception/BadMethodCallException.php index 50602b634..b29a56e91 100644 --- a/src/Exception/BadMethodCallException.php +++ b/src/Exception/BadMethodCallException.php @@ -14,7 +14,7 @@ * @category Zend * @package Zend_Cache */ -class BadMethodCallException extends \BadMethodCallException implements +class BadMethodCallException extends \BadMethodCallException implements ExceptionInterface { } diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index f479a856a..0d70ca359 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -14,7 +14,7 @@ * @category Zend * @package Zend_Cache */ -class InvalidArgumentException extends \InvalidArgumentException implements +class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { } diff --git a/src/Exception/UnexpectedValueException.php b/src/Exception/UnexpectedValueException.php index 9c8d428d7..de4f5f9f1 100644 --- a/src/Exception/UnexpectedValueException.php +++ b/src/Exception/UnexpectedValueException.php @@ -14,7 +14,7 @@ * @category Zend * @package Zend_Cache */ -class UnexpectedValueException extends \UnexpectedValueException implements +class UnexpectedValueException extends \UnexpectedValueException implements ExceptionInterface { } diff --git a/src/Exception/UnsupportedMethodCallException.php b/src/Exception/UnsupportedMethodCallException.php index a1bc111dd..29d773993 100644 --- a/src/Exception/UnsupportedMethodCallException.php +++ b/src/Exception/UnsupportedMethodCallException.php @@ -14,7 +14,7 @@ * @category Zend * @package Zend_Cache */ -class UnsupportedMethodCallException extends \BadMethodCallException implements +class UnsupportedMethodCallException extends \BadMethodCallException implements ExceptionInterface { } diff --git a/src/PatternPluginManager.php b/src/PatternPluginManager.php index f3d267b05..70cba3e54 100644 --- a/src/PatternPluginManager.php +++ b/src/PatternPluginManager.php @@ -16,7 +16,7 @@ * Plugin manager implementation for cache pattern adapters * * Enforces that adatpers retrieved are instances of - * Pattern\PatternInterface. Additionally, it registers a number of default + * Pattern\PatternInterface. Additionally, it registers a number of default * patterns available. * * @category Zend @@ -26,7 +26,7 @@ class PatternPluginManager extends AbstractPluginManager { /** * Default set of adapters - * + * * @var array */ protected $invokableClasses = array( @@ -40,7 +40,7 @@ class PatternPluginManager extends AbstractPluginManager /** * Don't share by default - * + * * @var array */ protected $shareByDefault = false; @@ -49,8 +49,8 @@ class PatternPluginManager extends AbstractPluginManager * Validate the plugin * * Checks that the pattern adapter loaded is an instance of Pattern\PatternInterface. - * - * @param mixed $plugin + * + * @param mixed $plugin * @return void * @throws Exception\RuntimeException if invalid */ diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index b8c8d28aa..6669f9151 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -23,10 +23,10 @@ * @package Zend_Cache * @subpackage Storage */ -class ZendServerDisk extends AbstractZendServer implements - AvailableSpaceCapableInterface, +class ZendServerDisk extends AbstractZendServer implements + AvailableSpaceCapableInterface, ClearByNamespaceInterface, - FlushableInterface, + FlushableInterface, TotalSpaceCapableInterface { diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 9d2ebba9c..5b9c3bbd6 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -21,7 +21,7 @@ * @package Zend_Cache * @subpackage Storage */ -class ZendServerShm extends AbstractZendServer implements +class ZendServerShm extends AbstractZendServer implements ClearByNamespaceInterface, FlushableInterface, TotalSpaceCapableInterface diff --git a/src/Storage/AdapterPluginManager.php b/src/Storage/AdapterPluginManager.php index 5cb8fa1b2..c10305dd8 100644 --- a/src/Storage/AdapterPluginManager.php +++ b/src/Storage/AdapterPluginManager.php @@ -17,7 +17,7 @@ * Plugin manager implementation for cache storage adapters * * Enforces that adapters retrieved are instances of - * StorageInterface. Additionally, it registers a number of default + * StorageInterface. Additionally, it registers a number of default * adapters available. * * @category Zend @@ -28,7 +28,7 @@ class AdapterPluginManager extends AbstractPluginManager { /** * Default set of adapters - * + * * @var array */ protected $invokableClasses = array( @@ -48,7 +48,7 @@ class AdapterPluginManager extends AbstractPluginManager /** * Do not share by default - * + * * @var array */ protected $shareByDefault = false; @@ -57,8 +57,8 @@ class AdapterPluginManager extends AbstractPluginManager * Validate the plugin * * Checks that the adapter loaded is an instance of StorageInterface. - * - * @param mixed $plugin + * + * @param mixed $plugin * @return void * @throws Exception\RuntimeException if invalid */ diff --git a/src/Storage/PluginManager.php b/src/Storage/PluginManager.php index 9499dfc04..d7746383c 100644 --- a/src/Storage/PluginManager.php +++ b/src/Storage/PluginManager.php @@ -17,7 +17,7 @@ * Plugin manager implementation for cache plugins * * Enforces that plugins retrieved are instances of - * Plugin\PluginInterface. Additionally, it registers a number of default + * Plugin\PluginInterface. Additionally, it registers a number of default * plugins available. * * @category Zend @@ -28,7 +28,7 @@ class PluginManager extends AbstractPluginManager { /** * Default set of plugins - * + * * @var array */ protected $invokableClasses = array( @@ -41,7 +41,7 @@ class PluginManager extends AbstractPluginManager /** * Do not share by default - * + * * @var array */ protected $shareByDefault = false; @@ -50,8 +50,8 @@ class PluginManager extends AbstractPluginManager * Validate the plugin * * Checks that the plugin loaded is an instance of Plugin\PluginInterface. - * - * @param mixed $plugin + * + * @param mixed $plugin * @return void * @throws Exception\RuntimeException if invalid */ diff --git a/test/Pattern/CallbackCacheTest.php b/test/Pattern/CallbackCacheTest.php index 487e05055..7cd8fbf81 100644 --- a/test/Pattern/CallbackCacheTest.php +++ b/test/Pattern/CallbackCacheTest.php @@ -39,7 +39,8 @@ public static function emptyMethod() {} * Test function * @see ZendTest\Cache\Pattern\Foo::bar */ -function bar () { +function bar () +{ return call_user_func_array(__NAMESPACE__ . '\TestCallbackCache::bar', func_get_args()); } From f35461c317d43cc3d98e3806092bef82f8cc948d Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Jul 2012 23:37:02 +0200 Subject: [PATCH 290/311] CaptureCache: removed tagging support because of clearing not implemented yet --- src/Pattern/CaptureCache.php | 46 +++------------ src/Pattern/PatternOptions.php | 103 --------------------------------- 2 files changed, 8 insertions(+), 141 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 75dc5d467..ef1a06034 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -40,17 +40,6 @@ public function start($pageId = null, array $options = array()) throw new Exception\RuntimeException("Capturing already stated with page id '{$this->pageId}'"); } - $classOptions = $this->getOptions(); - - if (isset($options['tags'])) { - $classOptions->setTags($options['tags']); - unset($options['tags']); - } - - if ($classOptions->getTags() && !$classOptions->getTagStorage()) { - throw new Exception\RuntimeException('Tags are defined but missing a tag storage'); - } - if (($pageId = (string) $pageId) === '') { $pageId = $this->detectPageId(); } @@ -77,8 +66,8 @@ public function get($pageId = null, array $options = array()) } $file = $this->getOptions()->getPublicDir() - . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { ErrorHandler::start(E_WARNING); @@ -108,8 +97,8 @@ public function exists($pageId = null, array $options = array()) } $file = $this->getOptions()->getPublicDir() - . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); return file_exists($file); } @@ -129,8 +118,8 @@ public function remove($pageId = null, array $options = array()) } $file = $this->getOptions()->getPublicDir() - . DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { if (!@unlink($file)) { @@ -186,8 +175,8 @@ protected function pageId2Path($pageId) $path = rtrim(dirname($pageId), '/'); // convert requested "/" to the valid local directory separator - if ('/' != DIRECTORY_SEPARATOR) { - $path = str_replace('/', DIRECTORY_SEPARATOR, $path); + if ('/' != \DIRECTORY_SEPARATOR) { + $path = str_replace('/', \DIRECTORY_SEPARATOR, $path); } return $path; @@ -223,25 +212,6 @@ protected function save($output) $this->createDirectoryStructure($publicDir . \DIRECTORY_SEPARATOR . $path); $this->putFileContent($publicDir . \DIRECTORY_SEPARATOR . $file, $output); - - $tagStorage = $options->getTagStorage(); - if ($tagStorage) { - $tagKey = $options->getTagKey(); - $tagIndex = $tagStorage->getTagStorage()->getItem($tagKey); - if (!$tagIndex) { - $tagIndex = null; - } - - if ($this->tags) { - $tagIndex[$file] = &$this->tags; - } elseif ($tagIndex) { - unset($tagIndex[$file]); - } - - if ($tagIndex !== null) { - $tagStorage->setItem($tagKey, $tagIndex); - } - } } /** diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index e5b32e522..0ec172946 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -147,27 +147,6 @@ class PatternOptions extends AbstractOptions */ protected $storage; - /** - * Used by: - * - CaptureCache - * @var string - */ - protected $tagKey = 'ZendCachePatternCaptureCache_Tags'; - - /** - * Used by: - * - CaptureCache - * @var array - */ - protected $tags = array(); - - /** - * Used by: - * - CaptureCache - * @var null|Storage - */ - protected $tagStorage; - /** * Constructor * @@ -709,88 +688,6 @@ public function getStorage() return $this->storage; } - /** - * Set tag key - * - * @param string $tagKey - * @return PatternOptions - */ - public function setTagKey($tagKey) - { - if (($tagKey = (string)$tagKey) === '') { - throw new Exception\InvalidArgumentException("Missing tag key '{$tagKey}'"); - } - - $this->tagKey = $tagKey; - return $this; - } - - /** - * Get tag key - * - * @return string - */ - public function getTagKey() - { - return $this->tagKey; - } - - /** - * Set tags - * - * Used by: - * - CaptureCache - * - * @param array $tags - * @return PatternOptions - */ - public function setTags(array $tags) - { - $this->tags = $tags; - return $this; - } - - /** - * Get tags - * - * Used by: - * - CaptureCache - * - * @return array - */ - public function getTags() - { - return $this->tags; - } - - /** - * Set storage adapter for tags - * - * Used by: - * - CaptureCache - * - * @param string|array|Storage $tagStorage - * @return PatternOptions - */ - public function setTagStorage($tagStorage) - { - $this->tagStorage = $this->storageFactory($tagStorage); - return $this; - } - - /** - * Get storage adapter for tags - * - * Used by: - * - CaptureCache - * - * @return null|Storage - */ - public function getTagStorage() - { - return $this->tagStorage; - } - /** * Recursively apply strtolower on all values of an array, and return as a * list of unique values From 88ce4b621b0dafca8001e2b13440aa55f2adcc39 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Jul 2012 23:39:41 +0200 Subject: [PATCH 291/311] no need to create a closure to locase case all elements of an array --- src/Pattern/PatternOptions.php | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 0ec172946..3bd232e97 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -697,9 +697,7 @@ public function getStorage() */ protected function recursiveStrtolower(array $array) { - return array_values(array_unique(array_map(function($value) { - return strtolower($value); - }, $array))); + return array_values(array_unique(array_map('strtolower', $array))); } /** From a9da1cb23ba7c64c0814c2b8edc45375b0802ca3 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Jul 2012 23:41:14 +0200 Subject: [PATCH 292/311] removed unused method Zend\Cache\PatternOptions::normalizeUmask --- src/Pattern/PatternOptions.php | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 3bd232e97..e3d8d9c5f 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -722,30 +722,6 @@ protected function normalizeObjectMethods(array $methods) return $methods; } - /** - * Normalize a umask - * - * Allows specifying a umask as either an octal or integer. If the umask - * fails required permissions, raises an exception. - * - * @param int|string $umask - * @param callable $comparison Callback used to verify the umask is acceptable for the given purpose - * @return int - * @throws Exception\InvalidArgumentException - */ - protected function normalizeUmask($umask, $comparison) - { - if (is_string($umask)) { - $umask = octdec($umask); - } else { - $umask = (int)$umask; - } - - $comparison($umask); - - return $umask; - } - /** * Create a storage object from a given specification * From 610ae07337815852a171c48e4657bc59775065b5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Jul 2012 23:43:58 +0200 Subject: [PATCH 293/311] CaptureCache: removed unused arguments 'array ' --- src/Pattern/CaptureCache.php | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index ef1a06034..1412e24d8 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -31,10 +31,9 @@ class CaptureCache extends AbstractPattern * Start the cache * * @param string $pageId Page identifier - * @param array $options Options * @return boolean false */ - public function start($pageId = null, array $options = array()) + public function start($pageId = null) { if ($this->pageId !== null) { throw new Exception\RuntimeException("Capturing already stated with page id '{$this->pageId}'"); @@ -55,11 +54,10 @@ public function start($pageId = null, array $options = array()) * Get from cache * * @param null|string $pageId - * @param array $options * @return bool|string * @throws Exception\RuntimeException */ - public function get($pageId = null, array $options = array()) + public function get($pageId = null) { if (($pageId = (string) $pageId) === '') { $pageId = $this->detectPageId(); @@ -87,10 +85,9 @@ public function get($pageId = null, array $options = array()) * Checks if a cache with given id exists * * @param null|string $pageId - * @param array $options * @return bool */ - public function exists($pageId = null, array $options = array()) + public function exists($pageId = null) { if (($pageId = (string) $pageId) === '') { $pageId = $this->detectPageId(); @@ -107,11 +104,10 @@ public function exists($pageId = null, array $options = array()) * Remove from cache * * @param null|string $pageId - * @param array $options * @throws Exception\RuntimeException * @return void */ - public function remove($pageId = null, array $options = array()) + public function remove($pageId = null) { if (($pageId = (string)$pageId) === '') { $pageId = $this->detectPageId(); From d8e0b7f44c0dc0c07efa662cd39eceed0b357fd5 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Tue, 17 Jul 2012 23:49:42 +0200 Subject: [PATCH 294/311] CaptureCache: fixed use of ErrorHandler --- src/Pattern/CaptureCache.php | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 1412e24d8..0ee24b69a 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -68,12 +68,13 @@ public function get($pageId = null) . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { - ErrorHandler::start(E_WARNING); + ErrorHandler::start(); $content = file_get_contents($file); - ErrorHandler::stop(); + $error = ErrorHandler::stop(); if ($content === false) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException("Failed to read cached pageId '{$pageId}': {$lastErr['message']}"); + throw new Exception\RuntimeException( + "Failed to read cached pageId '{$pageId}'", 0, $error + ); } return $content; } @@ -118,9 +119,13 @@ public function remove($pageId = null) . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { - if (!@unlink($file)) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException("Failed to remove cached pageId '{$pageId}': {$lastErr['message']}"); + ErrorHandler::start(); + $res = unlink($file); + $err = ErrorHandler::stop(); + if (!$res) { + throw new Exception\RuntimeException( + "Failed to remove cached pageId '{$pageId}'", 0, $err + ); } } } From 4f7b613c1ccfe5bda22336abc3ac1eb54999ca8c Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 18 Jul 2012 00:01:59 +0200 Subject: [PATCH 295/311] CaptureCache: - protected save($output) -> public set($content, $pageId = null) - exists($pageId) -> has($pageId = null) - replaced protected method flush with an closure - no longer return false on method start - return boolean on method remove --- src/Pattern/CaptureCache.php | 95 +++++++++++++++--------------------- 1 file changed, 40 insertions(+), 55 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 0ee24b69a..4cf5c5dbf 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -20,34 +20,50 @@ */ class CaptureCache extends AbstractPattern { - /** - * Page identifier - * - * @var null|string - */ - protected $pageId = null; - /** * Start the cache * * @param string $pageId Page identifier - * @return boolean false + * @return void */ public function start($pageId = null) { - if ($this->pageId !== null) { - throw new Exception\RuntimeException("Capturing already stated with page id '{$this->pageId}'"); + if ($pageId === null) { + $pageId = $this->detectPageId(); } - if (($pageId = (string) $pageId) === '') { + $that = $this; + ob_start(function ($content) use ($that, $pageId) { + $that->set($content, $pageId); + + // http://php.net/manual/function.ob-start.php + // -> If output_callback returns FALSE original input is sent to the browser. + return false; + }); + + ob_implicit_flush(false); + } + + /** + * Write content to page identity + * + * @param string $content + * @param null|string $pageId + * @throws Exception\RuntimeException + */ + public function set($content, $pageId = null) + { + if ($pageId === null) { $pageId = $this->detectPageId(); } - ob_start(array($this, 'flush')); - ob_implicit_flush(false); - $this->pageId = $pageId; + $options = $this->getOptions(); + $publicDir = $options->getPublicDir(); + $path = $this->pageId2Path($pageId); + $file = $path . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); - return false; + $this->createDirectoryStructure($publicDir . \DIRECTORY_SEPARATOR . $path); + $this->putFileContent($publicDir . \DIRECTORY_SEPARATOR . $file, $content); } /** @@ -59,7 +75,7 @@ public function start($pageId = null) */ public function get($pageId = null) { - if (($pageId = (string) $pageId) === '') { + if ($pageId === null) { $pageId = $this->detectPageId(); } @@ -78,19 +94,17 @@ public function get($pageId = null) } return $content; } - - return false; } /** * Checks if a cache with given id exists * * @param null|string $pageId - * @return bool + * @return boolean */ - public function exists($pageId = null) + public function has($pageId = null) { - if (($pageId = (string) $pageId) === '') { + if ($pageId === null) { $pageId = $this->detectPageId(); } @@ -106,11 +120,11 @@ public function exists($pageId = null) * * @param null|string $pageId * @throws Exception\RuntimeException - * @return void + * @return boolean */ public function remove($pageId = null) { - if (($pageId = (string)$pageId) === '') { + if ($pageId === null) { $pageId = $this->detectPageId(); } @@ -127,7 +141,10 @@ public function remove($pageId = null) "Failed to remove cached pageId '{$pageId}'", 0, $err ); } + return true; } + + return false; } /** @@ -183,38 +200,6 @@ protected function pageId2Path($pageId) return $path; } - /** - * callback for output buffering - * - * @param string $output Buffered output - * @return boolean FALSE means original input is sent to the browser. - */ - protected function flush($output) - { - $this->save($output); - - // http://php.net/manual/function.ob-start.php - // -> If output_callback returns FALSE original input is sent to the browser. - return false; - } - - /** - * Save the cache - * - * @param $output - * @throws Exception\RuntimeException - */ - protected function save($output) - { - $options = $this->getOptions(); - $publicDir = $options->getPublicDir(); - $path = $this->pageId2Path($this->pageId); - $file = $path . \DIRECTORY_SEPARATOR . $this->pageId2Filename($this->pageId); - - $this->createDirectoryStructure($publicDir . \DIRECTORY_SEPARATOR . $path); - $this->putFileContent($publicDir . \DIRECTORY_SEPARATOR . $file, $output); - } - /** * Write content to a file * From 9f1eb5415cd9e977394907db09498e6c02e710c6 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 18 Jul 2012 00:38:14 +0200 Subject: [PATCH 296/311] CaptureCache: validate public_dir + implemented clearByGlob --- src/Pattern/CaptureCache.php | 65 +++++++++++++++++++++++++--------- src/Pattern/PatternOptions.php | 18 +++++++++- 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index 4cf5c5dbf..d9283ebd0 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -53,14 +53,17 @@ public function start($pageId = null) */ public function set($content, $pageId = null) { + $publicDir = $this->getOptions()->getPublicDir(); + if ($publicDir === null) { + throw new Exception\LogicException("Option 'public_dir' no set"); + } + if ($pageId === null) { $pageId = $this->detectPageId(); } - $options = $this->getOptions(); - $publicDir = $options->getPublicDir(); - $path = $this->pageId2Path($pageId); - $file = $path . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + $path = $this->pageId2Path($pageId); + $file = $path . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); $this->createDirectoryStructure($publicDir . \DIRECTORY_SEPARATOR . $path); $this->putFileContent($publicDir . \DIRECTORY_SEPARATOR . $file, $content); @@ -75,13 +78,18 @@ public function set($content, $pageId = null) */ public function get($pageId = null) { + $publicDir = $this->getOptions()->getPublicDir(); + if ($publicDir === null) { + throw new Exception\LogicException("Option 'public_dir' no set"); + } + if ($pageId === null) { $pageId = $this->detectPageId(); } - $file = $this->getOptions()->getPublicDir() - . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + $file = $publicDir + . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { ErrorHandler::start(); @@ -104,13 +112,18 @@ public function get($pageId = null) */ public function has($pageId = null) { + $publicDir = $this->getOptions()->getPublicDir(); + if ($publicDir === null) { + throw new Exception\LogicException("Option 'public_dir' no set"); + } + if ($pageId === null) { $pageId = $this->detectPageId(); } - $file = $this->getOptions()->getPublicDir() - . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + $file = $publicDir + . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); return file_exists($file); } @@ -124,13 +137,18 @@ public function has($pageId = null) */ public function remove($pageId = null) { + $publicDir = $this->getOptions()->getPublicDir(); + if ($publicDir === null) { + throw new Exception\LogicException("Option 'public_dir' no set"); + } + if ($pageId === null) { $pageId = $this->detectPageId(); } - $file = $this->getOptions()->getPublicDir() - . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) - . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); + $file = $publicDir + . \DIRECTORY_SEPARATOR . $this->pageId2Path($pageId) + . \DIRECTORY_SEPARATOR . $this->pageId2Filename($pageId); if (file_exists($file)) { ErrorHandler::start(); @@ -148,11 +166,26 @@ public function remove($pageId = null) } /** - * Clear cache + * Clear cached pages matching glob pattern + * + * @param string $pattern */ - public function clear(/*TODO*/) + public function clearByGlob($pattern = '**') { - // TODO + $publicDir = $this->getOptions()->getPublicDir(); + if ($publicDir === null) { + throw new Exception\LogicException("Option 'public_dir' no set"); + } + + $it = new \GlobIterator( + $publicDir . '/' . $pattern, + \GlobIterator::CURRENT_AS_SELF | \GlobIterator::SKIP_DOTS | \GlobIterator::UNIX_PATHS + ); + foreach ($it as $pathname => $entry) { + if ($entry->isFile()) { + unlink($pathname); + } + } } /** diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index e3d8d9c5f..4134d73cb 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -637,7 +637,23 @@ public function getObjectNonCacheMethods() */ public function setPublicDir($publicDir) { - $this->publicDir = (string) $publicDir; + $publicDir = (string) $publicDir; + + if (!is_dir($publicDir)) { + throw new Exception\InvalidArgumentException( + "Public directory '{$publicDir}' not found or not a directoy" + ); + } elseif (!is_writable($publicDir)) { + throw new Exception\InvalidArgumentException( + "Public directory '{$publicDir}' not writable" + ); + } elseif (!is_readable($publicDir)) { + throw new Exception\InvalidArgumentException( + "Public directory '{$publicDir}' not readable" + ); + } + + $this->publicDir = rtrim(realpath($publicDir), \DIRECTORY_SEPARATOR); return $this; } From 233907ea8ca22f271fbbb90f7ea71e08251db187 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 18 Jul 2012 01:01:03 +0200 Subject: [PATCH 297/311] CaptureCache: fixed and tested pageId detection and output filename generation --- src/Pattern/CaptureCache.php | 18 ++++-- test/Pattern/CaptureCacheTest.php | 96 ++++++++++++++++++++++++++++++- 2 files changed, 106 insertions(+), 8 deletions(-) diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index d9283ebd0..d2d7657b8 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -195,6 +195,10 @@ public function clearByGlob($pattern = '**') */ protected function detectPageId() { + if (!isset($_SERVER['REQUEST_URI'])) { + throw new Exception\RuntimeException("Can't auto-detect current page identity"); + } + return $_SERVER['REQUEST_URI']; } @@ -206,13 +210,11 @@ protected function detectPageId() */ protected function pageId2Filename($pageId) { - $filename = basename($pageId); - - if ($filename === '') { - $filename = $this->getOptions()->getIndexFilename(); + if (substr($pageId, -1) === '/') { + return $this->getOptions()->getIndexFilename(); } - return $filename; + return basename($pageId); } /** @@ -223,7 +225,11 @@ protected function pageId2Filename($pageId) */ protected function pageId2Path($pageId) { - $path = rtrim(dirname($pageId), '/'); + if (substr($pageId, -1) == '/') { + $path = rtrim($pageId, '/'); + } else { + $path = dirname($pageId); + } // convert requested "/" to the valid local directory separator if ('/' != \DIRECTORY_SEPARATOR) { diff --git a/test/Pattern/CaptureCacheTest.php b/test/Pattern/CaptureCacheTest.php index 36cc3d863..994f54de2 100644 --- a/test/Pattern/CaptureCacheTest.php +++ b/test/Pattern/CaptureCacheTest.php @@ -21,10 +21,27 @@ class CaptureCacheTest extends CommonPatternTest { + protected $_tmpCacheDir; + protected $_umask; + public function setUp() { + $this->_umask = umask(); + + $this->_tmpCacheDir = @tempnam(sys_get_temp_dir(), 'zend_cache_test_'); + if (!$this->_tmpCacheDir) { + $err = error_get_last(); + $this->fail("Can't create temporary cache directory-file: {$err['message']}"); + } elseif (!@unlink($this->_tmpCacheDir)) { + $err = error_get_last(); + $this->fail("Can't remove temporary cache directory-file: {$err['message']}"); + } elseif (!@mkdir($this->_tmpCacheDir, 0777)) { + $err = error_get_last(); + $this->fail("Can't create temporary cache directory: {$err['message']}"); + } + $this->_options = new Cache\Pattern\PatternOptions(array( - // TODO + 'public_dir' => $this->_tmpCacheDir )); $this->_pattern = new Cache\Pattern\CaptureCache(); $this->_pattern->setOptions($this->_options); @@ -34,7 +51,82 @@ public function setUp() public function tearDown() { - // TODO + $this->_removeRecursive($this->_tmpCacheDir); + + if ($this->_umask != umask()) { + umask($this->_umask); + $this->fail("Umask wasn't reset"); + } + parent::tearDown(); } + + protected function _removeRecursive($dir) + { + if (file_exists($dir)) { + $dirIt = new \DirectoryIterator($dir); + foreach ($dirIt as $entry) { + $fname = $entry->getFilename(); + if ($fname == '.' || $fname == '..') { + continue; + } + + if ($entry->isFile()) { + unlink($entry->getPathname()); + } else { + $this->_removeRecursive($entry->getPathname()); + } + } + + rmdir($dir); + } + } + + public function testSetThrowsLogicExceptionOnMissingPublicDir() + { + $captureCache = new Cache\Pattern\CaptureCache(); + + $this->setExpectedException('Zend\Cache\Exception\LogicException'); + $captureCache->set('content', '/pageId'); + } + + public function testSetWithNormalPageId() + { + $this->_pattern->set('content', '/dir1/dir2/file'); + $this->assertTrue(file_exists($this->_tmpCacheDir . '/dir1/dir2/file')); + $this->assertSame(file_get_contents($this->_tmpCacheDir . '/dir1/dir2/file'), 'content'); + } + + public function testSetWithIndexFilename() + { + $this->_options->setIndexFilename('test.html'); + + $this->_pattern->set('content', '/dir1/dir2/'); + $this->assertTrue(file_exists($this->_tmpCacheDir . '/dir1/dir2/test.html')); + $this->assertSame(file_get_contents($this->_tmpCacheDir . '/dir1/dir2/test.html'), 'content'); + } + + public function testGetThrowsLogicExceptionOnMissingPublicDir() + { + $captureCache = new Cache\Pattern\CaptureCache(); + + $this->setExpectedException('Zend\Cache\Exception\LogicException'); + $captureCache->get('/pageId'); + } + + public function testHasThrowsLogicExceptionOnMissingPublicDir() + { + $captureCache = new Cache\Pattern\CaptureCache(); + + $this->setExpectedException('Zend\Cache\Exception\LogicException'); + $captureCache->has('/pageId'); + } + + public function testRemoveThrowsLogicExceptionOnMissingPublicDir() + { + $captureCache = new Cache\Pattern\CaptureCache(); + + $this->setExpectedException('Zend\Cache\Exception\LogicException'); + $captureCache->remove('/pageId'); + } } From 2dbc78b7d644c0b7a5cc2bae3c712946b530cd23 Mon Sep 17 00:00:00 2001 From: RWOverdijk Date: Thu, 9 Aug 2012 09:11:18 +0200 Subject: [PATCH 298/311] PSR-2 added space after control structure --- src/Storage/Adapter/Filesystem.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 4acd600ed..505cf84a1 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -1522,7 +1522,7 @@ protected function putFileContent($file, $data, $nonBlocking = false, & $wouldbl throw new Exception\RuntimeException("chmod('{$file}', 0{$oct}) failed", 0, $err); } - if(!flock($fp, \LOCK_EX | \LOCK_NB, $wouldblock)) { + if (!flock($fp, \LOCK_EX | \LOCK_NB, $wouldblock)) { fclose($fp); $err = ErrorHandler::stop(); if ($wouldblock) { From 19d2447dc26fe533b8b4c7bf8ab032457fe3ae04 Mon Sep 17 00:00:00 2001 From: Wesley Overdijk Date: Thu, 9 Aug 2012 21:58:47 +0300 Subject: [PATCH 299/311] Update library/Zend/Cache/Pattern/PatternOptions.php Removed strict check to just make it PSR-2 --- src/Pattern/PatternOptions.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 9fd410f67..9478f1e81 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -750,7 +750,7 @@ protected function storageFactory($storage) $storage = StorageFactory::factory($storage); } elseif (is_string($storage)) { $storage = StorageFactory::adapterFactory($storage); - } elseif (($storage instanceof Storage) !== true) { + } elseif (!($storage instanceof Storage)) { throw new Exception\InvalidArgumentException( 'The storage must be an instanceof Zend\Cache\Storage\StorageInterface ' . 'or an array passed to Zend\Cache\Storage::factory ' From f17ad52e27ed5d450f07cc44a2e22718d3939539 Mon Sep 17 00:00:00 2001 From: Wesley Overdijk Date: Thu, 9 Aug 2012 21:59:46 +0300 Subject: [PATCH 300/311] Update library/Zend/Cache/Storage/Plugin/ClearExpiredByFactor.php Removed strict check to just make it PRS-2 compliant --- src/Storage/Plugin/ClearExpiredByFactor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Plugin/ClearExpiredByFactor.php b/src/Storage/Plugin/ClearExpiredByFactor.php index df0fd8130..4b4d60a50 100644 --- a/src/Storage/Plugin/ClearExpiredByFactor.php +++ b/src/Storage/Plugin/ClearExpiredByFactor.php @@ -92,7 +92,7 @@ public function detach(EventManagerInterface $events) public function clearExpiredByFactor(PostEvent $event) { $storage = $event->getStorage(); - if (($storage instanceof ClearExpiredInterface) !== true) { + if (!($storage instanceof ClearExpiredInterface)) { return; } From 6ab4a74ec098b2eb7b2b39efd3393352ccf3ab33 Mon Sep 17 00:00:00 2001 From: Wesley Overdijk Date: Thu, 9 Aug 2012 22:00:17 +0300 Subject: [PATCH 301/311] Update library/Zend/Cache/Storage/Plugin/OptimizeByFactor.php Removed strict check to just make it PRS-2 compliant --- src/Storage/Plugin/OptimizeByFactor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Storage/Plugin/OptimizeByFactor.php b/src/Storage/Plugin/OptimizeByFactor.php index cd69af30f..aa09ae1de 100644 --- a/src/Storage/Plugin/OptimizeByFactor.php +++ b/src/Storage/Plugin/OptimizeByFactor.php @@ -89,7 +89,7 @@ public function detach(EventManagerInterface $events) public function optimizeByFactor(PostEvent $event) { $storage = $event->getStorage(); - if (($storage instanceof OptimizableInterface) !== true) { + if (!($storage instanceof OptimizableInterface)) { return; } From c4692ea5e3a514872d74dad93e38bb05052e51b7 Mon Sep 17 00:00:00 2001 From: Wesley Overdijk Date: Thu, 9 Aug 2012 22:03:25 +0300 Subject: [PATCH 302/311] Update tests/ZendTest/Cache/Storage/Adapter/CommonAdapterTest.php Removed strict check to just make it PRS-2 compliant --- test/Storage/Adapter/CommonAdapterTest.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/Storage/Adapter/CommonAdapterTest.php b/test/Storage/Adapter/CommonAdapterTest.php index e0f74943a..5e318775e 100644 --- a/test/Storage/Adapter/CommonAdapterTest.php +++ b/test/Storage/Adapter/CommonAdapterTest.php @@ -856,7 +856,7 @@ public function testTouchItemsReturnsGivenKeysIfNonWritable() public function testOptimize() { - if (($this->_storage instanceof OptimizableInterface) !== true) { + if (!($this->_storage instanceof OptimizableInterface)) { $this->markTestSkipped("Storage doesn't implement OptimizableInterface"); } @@ -897,7 +897,7 @@ public function testIterator() public function testFlush() { - if (($this->_storage instanceof FlushableInterface) !== true) { + if (!($this->_storage instanceof FlushableInterface)) { $this->markTestSkipped("Storage doesn't implement OptimizableInterface"); } @@ -913,7 +913,7 @@ public function testFlush() public function testClearByPrefix() { - if (($this->_storage instanceof ClearByPrefixInterface) !== true) { + if (!($this->_storage instanceof ClearByPrefixInterface)) { $this->markTestSkipped("Storage doesn't implement ClearByPrefixInterface"); } @@ -931,7 +931,7 @@ public function testClearByPrefix() public function testClearByNamespace() { - if (($this->_storage instanceof ClearByNamespaceInterface) !== true) { + if (!($this->_storage instanceof ClearByNamespaceInterface)) { $this->markTestSkipped("Storage doesn't implement ClearByNamespaceInterface"); } @@ -965,7 +965,7 @@ public function testClearByNamespace() public function testClearExpired() { - if (($this->_storage instanceof ClearExpiredInterface) !== true) { + if (!($this->_storage instanceof ClearExpiredInterface)) { $this->markTestSkipped("Storage doesn't implement ClearExpiredInterface"); } @@ -994,7 +994,7 @@ public function testClearExpired() public function testTagable() { - if (($this->_storage instanceof TaggableInterface) !== true) { + if (!($this->_storage instanceof TaggableInterface)) { $this->markTestSkipped("Storage doesn't implement TaggableInterface"); } From 21503d1b38c73c1b414f3a86c70500c5a036fa7f Mon Sep 17 00:00:00 2001 From: Michael Kliewe Date: Sat, 11 Aug 2012 11:27:30 +0200 Subject: [PATCH 303/311] removed all "@return void" in constructors --- src/Storage/Adapter/AbstractAdapter.php | 1 - src/Storage/Adapter/Apc.php | 1 - src/Storage/Adapter/ApcIterator.php | 1 - src/Storage/Adapter/Dba.php | 1 - src/Storage/Adapter/DbaIterator.php | 1 - src/Storage/Adapter/FilesystemIterator.php | 1 - src/Storage/Adapter/KeyListIterator.php | 1 - src/Storage/Adapter/Memcached.php | 1 - src/Storage/Adapter/WinCache.php | 1 - src/Storage/Adapter/ZendServerDisk.php | 1 - src/Storage/Adapter/ZendServerShm.php | 1 - src/Storage/Event.php | 1 - src/Storage/ExceptionEvent.php | 1 - src/Storage/PostEvent.php | 1 - 14 files changed, 14 deletions(-) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 6017a29bd..f78755110 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -77,7 +77,6 @@ abstract class AbstractAdapter implements StorageInterface, EventsCapableInterfa * * @param null|array|Traversable|AdapterOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = null) { diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index de5bd9c27..3785ecb4a 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -48,7 +48,6 @@ class Apc extends AbstractAdapter implements * * @param null|array|Traversable|ApcOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = null) { diff --git a/src/Storage/Adapter/ApcIterator.php b/src/Storage/Adapter/ApcIterator.php index dc035cf06..6cf8b8176 100644 --- a/src/Storage/Adapter/ApcIterator.php +++ b/src/Storage/Adapter/ApcIterator.php @@ -55,7 +55,6 @@ class ApcIterator implements IteratorInterface * @param Apc $storage * @param BaseApcIterator $baseIterator * @param string $prefix - * @return void */ public function __construct(Apc $storage, BaseApcIterator $baseIterator, $prefix) { diff --git a/src/Storage/Adapter/Dba.php b/src/Storage/Adapter/Dba.php index 5e7bf11f6..a85ac19a8 100644 --- a/src/Storage/Adapter/Dba.php +++ b/src/Storage/Adapter/Dba.php @@ -50,7 +50,6 @@ class Dba extends AbstractAdapter implements * * @param null|array|Traversable|DbaOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = null) { diff --git a/src/Storage/Adapter/DbaIterator.php b/src/Storage/Adapter/DbaIterator.php index f6bce58ca..ceaae999d 100644 --- a/src/Storage/Adapter/DbaIterator.php +++ b/src/Storage/Adapter/DbaIterator.php @@ -61,7 +61,6 @@ class DbaIterator implements IteratorInterface * @param Dba $storage * @param resource $handle * @param string $prefix - * @return void */ public function __construct(Dba $storage, $handle, $prefix) { diff --git a/src/Storage/Adapter/FilesystemIterator.php b/src/Storage/Adapter/FilesystemIterator.php index 7cb2f5d7e..142b680f2 100644 --- a/src/Storage/Adapter/FilesystemIterator.php +++ b/src/Storage/Adapter/FilesystemIterator.php @@ -62,7 +62,6 @@ class FilesystemIterator implements IteratorInterface * @param Filesystem $storage * @param string $path * @param string $prefix - * @return void */ public function __construct(Filesystem $storage, $path, $prefix) { diff --git a/src/Storage/Adapter/KeyListIterator.php b/src/Storage/Adapter/KeyListIterator.php index 21de7d5f1..2239b0284 100644 --- a/src/Storage/Adapter/KeyListIterator.php +++ b/src/Storage/Adapter/KeyListIterator.php @@ -62,7 +62,6 @@ class KeyListIterator implements IteratorInterface, Countable * * @param StorageInterface $storage * @param array $keys - * @return void */ public function __construct(StorageInterface $storage, array $keys) { diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index 732192d41..cbd77d8c8 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -52,7 +52,6 @@ class Memcached extends AbstractAdapter implements * * @param null|array|Traversable|MemcachedOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = null) { diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index 1f638ce90..aa78b4c1c 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -34,7 +34,6 @@ class WinCache extends AbstractAdapter implements * * @param array|Traversable|WinCacheOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = null) { diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index 6669f9151..e9fe81baa 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -42,7 +42,6 @@ class ZendServerDisk extends AbstractZendServer implements * * @param null|array|\Traversable|AdapterOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = array()) { diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 5b9c3bbd6..63759e085 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -32,7 +32,6 @@ class ZendServerShm extends AbstractZendServer implements * * @param null|array|\Traversable|AdapterOptions $options * @throws Exception\ExceptionInterface - * @return void */ public function __construct($options = array()) { diff --git a/src/Storage/Event.php b/src/Storage/Event.php index bf55b2cf6..65aba128a 100644 --- a/src/Storage/Event.php +++ b/src/Storage/Event.php @@ -28,7 +28,6 @@ class Event extends BaseEvent * @param string $name Event name * @param StorageInterface $storage * @param ArrayObject $params - * @return void */ public function __construct($name, StorageInterface $storage, ArrayObject $params) { diff --git a/src/Storage/ExceptionEvent.php b/src/Storage/ExceptionEvent.php index 525ebd597..d9ac2942d 100644 --- a/src/Storage/ExceptionEvent.php +++ b/src/Storage/ExceptionEvent.php @@ -44,7 +44,6 @@ class ExceptionEvent extends PostEvent * @param ArrayObject $params * @param mixed $result * @param Exception $exception - * @return void */ public function __construct($name, StorageInterface $storage, ArrayObject $params, & $result, Exception $exception) { diff --git a/src/Storage/PostEvent.php b/src/Storage/PostEvent.php index 93309c794..e627da69d 100644 --- a/src/Storage/PostEvent.php +++ b/src/Storage/PostEvent.php @@ -35,7 +35,6 @@ class PostEvent extends Event * @param StorageInterface $storage * @param ArrayObject $params * @param mixed $result - * @return void */ public function __construct($name, StorageInterface $storage, ArrayObject $params, & $result) { From 4e0c47e77c9dece7cb356bea535b9cf134f4e191 Mon Sep 17 00:00:00 2001 From: Michael Kliewe Date: Sat, 11 Aug 2012 12:29:21 +0200 Subject: [PATCH 304/311] added @return where missing fixed @return where wrong fixed @param where wrong in methods: @var -> @param --- src/Pattern/ClassCache.php | 1 + src/Pattern/ObjectCache.php | 1 + src/Pattern/OutputCache.php | 1 + src/Storage/Adapter/FilesystemOptions.php | 9 ++++++--- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index ba172a0d4..6bd7fbee9 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -23,6 +23,7 @@ class ClassCache extends CallbackCache * Set options * * @param PatternOptions $options + * @return ClassCache * @throws Exception\InvalidArgumentException if missing 'class' or 'storage' options */ public function setOptions(PatternOptions $options) diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index 3a24a8304..e8ab316a7 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -23,6 +23,7 @@ class ObjectCache extends CallbackCache * Set options * * @param PatternOptions $options + * @return void * @throws Exception\InvalidArgumentException */ public function setOptions(PatternOptions $options) diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index c00b3404c..a55f09cf4 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -31,6 +31,7 @@ class OutputCache extends AbstractPattern * Set options * * @param PatternOptions $options + * @return OutputCache * @throws Exception\InvalidArgumentException */ public function setOptions(PatternOptions $options) diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index 63c064e88..1914561c8 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -225,7 +225,8 @@ public function getDirLevel() /** * Set permission to create directories on unix systems * - * @var false|string|int $dirPermission FALSE to disable explicit permission or an octal number + * @param false|string|int $dirPermission FALSE to disable explicit permission or an octal number + * @return FilesystemOptions * @see setUmask * @see setFilePermission * @link http://php.net/manual/function.chmod.php @@ -292,7 +293,8 @@ public function getFileLocking() /** * Set permission to create files on unix systems * - * @var false|string|int $filePermission FALSE to disable explicit permission or an octal number + * @param false|string|int $filePermission FALSE to disable explicit permission or an octal number + * @return FilesystemOptions * @see setUmask * @see setDirPermission * @link http://php.net/manual/function.chmod.php @@ -413,7 +415,8 @@ public function getNoCtime() * * Note: On multithreaded webservers it's better to explicit set file and dir permission. * - * @var false|string|int FALSE to disable umask or an octal number + * @param false|string|int $umask FALSE to disable umask or an octal number + * @return FilesystemOptions * @see setFilePermission * @see setDirPermission * @link http://php.net/manual/function.umask.php From 4ddeb6da5a0cfce51becbba17bffcfc3ae440144 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 21 Aug 2012 10:18:51 -0500 Subject: [PATCH 305/311] [zendframework/zf2#2210] Remove error_get_last usage - Removed two cases where error_get_last() was being used in Cache component; instead, captures the return from ErrorHandler::stop() and calls its getMessage() method. --- src/Pattern/CallbackCache.php | 10 +++++----- src/Storage/Adapter/AdapterOptions.php | 9 ++++++--- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index 06c7ccc5a..de2b1c1d4 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -155,13 +155,13 @@ protected function generateCallbackKey($callback, array $args) "Can't serialize callback: see previous exception", 0, $e ); } - ErrorHandler::stop(); + $error = ErrorHandler::stop(); if (!$serializedObject) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException( - "Can't serialize callback: " . $lastErr['message'] - ); + throw new Exception\RuntimeException(sprintf( + 'Cannot serialize callback: %s', + $error->getMessage() + )); } $callbackKey.= $serializedObject; } diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 3492ad231..04f17afc0 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -96,10 +96,13 @@ public function setKeyPattern($keyPattern) if ($keyPattern !== '') { ErrorHandler::start(E_WARNING); $result = preg_match($keyPattern, ''); - ErrorHandler::stop(); + $error = ErrorHandler::stop(); if ($result === false) { - $err = error_get_last(); - throw new Exception\InvalidArgumentException("Invalid pattern '{$keyPattern}': {$err['message']}"); + throw new Exception\InvalidArgumentException(sprintf( + 'Invalid pattern "%s": %s', + $keyPattern, + $error->getMessage() + )); } } From 97cf4633ea25512691f84aa93734d927f9ec3bfa Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 21 Aug 2012 11:13:05 -0500 Subject: [PATCH 306/311] [zendframework/zf2#2210] Pass ErrorHandler::stop() result as previous exception - Per @mark-mabe - Any place where an exception is throw immediately following an ErrorHandler::stop() call should pass the result of that call as the previous exception. --- src/Pattern/CallbackCache.php | 16 ++++++++-------- src/Storage/Adapter/AdapterOptions.php | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index de2b1c1d4..e5fe0b0fd 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -159,9 +159,9 @@ protected function generateCallbackKey($callback, array $args) if (!$serializedObject) { throw new Exception\RuntimeException(sprintf( - 'Cannot serialize callback: %s', - $error->getMessage() - )); + 'Cannot serialize callback%s', + ($error ? ': ' . $error->getMessage() : '') + ), 0, $error); } $callbackKey.= $serializedObject; } @@ -191,13 +191,13 @@ protected function generateArgumentsKey(array $args) "Can't serialize arguments: see previous exception" , 0, $e); } - ErrorHandler::stop(); + $error = ErrorHandler::stop(); if (!$serializedArgs) { - $lastErr = error_get_last(); - throw new Exception\RuntimeException( - "Can't serialize arguments: " . $lastErr['message'] - ); + throw new Exception\RuntimeException(sprintf( + 'Cannot serialize arguments%s', + ($error ? ': ' . $error->getMessage() : '') + ), 0, $error); } return md5($serializedArgs); diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 04f17afc0..70adb9d5b 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -99,10 +99,10 @@ public function setKeyPattern($keyPattern) $error = ErrorHandler::stop(); if ($result === false) { throw new Exception\InvalidArgumentException(sprintf( - 'Invalid pattern "%s": %s', + 'Invalid pattern "%s"%s', $keyPattern, - $error->getMessage() - )); + ($error ? ': ' . $error->getMessage() : '') + ), 0, $error); } } From 1f6d9df9b2462c6be34f12d4873164660041c1e7 Mon Sep 17 00:00:00 2001 From: Marc Bennewitz Date: Wed, 22 Aug 2012 20:50:48 +0200 Subject: [PATCH 307/311] Minimized comparisons on getting serializer of serializer plugin --- src/Storage/Plugin/PluginOptions.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index fef12f0be..9ca1b41dc 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -213,13 +213,16 @@ public function setSerializer($serializer) */ public function getSerializer() { - if (is_string($this->serializer)) { - $options = $this->getSerializerOptions(); - $this->setSerializer(SerializerFactory::factory($this->serializer, $options)); - } elseif (null === $this->serializer) { - $this->setSerializer(SerializerFactory::getDefaultAdapter()); + if (!$this->serializer instanceof SerializerAdapter) { + // use default serializer + if (!$this->serializer) { + $this->setSerializer(SerializerFactory::getDefaultAdapter()); + // instantiate by class name + serializer_options + } else { + $options = $this->getSerializerOptions(); + $this->setSerializer(SerializerFactory::factory($this->serializer, $options)); + } } - return $this->serializer; } From 1b1d0000fb7aa463024ceb8dfa9430fce95f68a6 Mon Sep 17 00:00:00 2001 From: Michel Hunziker Date: Fri, 31 Aug 2012 17:30:38 +0200 Subject: [PATCH 308/311] Add missing @throws annotations --- src/Pattern/CallbackCache.php | 8 +++++--- src/Pattern/CaptureCache.php | 7 ++++++- src/Pattern/OutputCache.php | 4 ++-- src/PatternFactory.php | 2 +- src/Storage/Adapter/AdapterOptions.php | 1 + src/Storage/Adapter/Filesystem.php | 5 +++++ src/Storage/Adapter/MemoryOptions.php | 1 + src/Storage/Adapter/ZendServerDisk.php | 4 +++- src/Storage/Adapter/ZendServerShm.php | 2 +- src/Storage/Plugin/PluginOptions.php | 4 +++- 10 files changed, 28 insertions(+), 10 deletions(-) diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index e5fe0b0fd..b77e641e7 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -44,7 +44,8 @@ public function setOptions(PatternOptions $options) * @param callable $callback A valid callback * @param array $args Callback arguments * @return mixed Result - * @throws Exception + * @throws Exception\RuntimeException if invalid cached data + * @throws \Exception */ public function call($callback, array $args = array()) { @@ -127,8 +128,9 @@ public function generateKey($callback, array $args = array()) * * @param callable $callback A valid callback * @param array $args Callback arguments + * @throws Exception\RuntimeException if callback not serializable + * @throws Exception\InvalidArgumentException if invalid callback * @return string - * @throws Exception */ protected function generateCallbackKey($callback, array $args) { @@ -173,8 +175,8 @@ protected function generateCallbackKey($callback, array $args) * Generate a unique key of the argument part. * * @param array $args + * @throws Exception\RuntimeException * @return string - * @throws Exception */ protected function generateArgumentsKey(array $args) { diff --git a/src/Pattern/CaptureCache.php b/src/Pattern/CaptureCache.php index b8b2fbce6..1d51337cc 100644 --- a/src/Pattern/CaptureCache.php +++ b/src/Pattern/CaptureCache.php @@ -49,7 +49,7 @@ public function start($pageId = null) * * @param string $content * @param null|string $pageId - * @throws Exception\RuntimeException + * @throws Exception\LogicException */ public function set($content, $pageId = null) { @@ -74,6 +74,7 @@ public function set($content, $pageId = null) * * @param null|string $pageId * @return bool|string + * @throws Exception\LogicException * @throws Exception\RuntimeException */ public function get($pageId = null) @@ -108,6 +109,7 @@ public function get($pageId = null) * Checks if a cache with given id exists * * @param null|string $pageId + * @throws Exception\LogicException * @return boolean */ public function has($pageId = null) @@ -132,6 +134,7 @@ public function has($pageId = null) * Remove from cache * * @param null|string $pageId + * @throws Exception\LogicException * @throws Exception\RuntimeException * @return boolean */ @@ -169,6 +172,7 @@ public function remove($pageId = null) * Clear cached pages matching glob pattern * * @param string $pattern + * @throws Exception\LogicException */ public function clearByGlob($pattern = '**') { @@ -191,6 +195,7 @@ public function clearByGlob($pattern = '**') /** * Determine the page to save from the request * + * @throws Exception\RuntimeException * @return string */ protected function detectPageId() diff --git a/src/Pattern/OutputCache.php b/src/Pattern/OutputCache.php index a55f09cf4..f9aac0a77 100644 --- a/src/Pattern/OutputCache.php +++ b/src/Pattern/OutputCache.php @@ -50,8 +50,8 @@ public function setOptions(PatternOptions $options) * else start buffering output until end() is called or the script ends. * * @param string $key Key + * @throws Exception\MissingKeyException if key is missing * @return boolean - * @throws Exception */ public function start($key) { @@ -76,8 +76,8 @@ public function start($key) * Stops buffering output, write buffered data to cache using the given key on start() * and displays the buffer. * + * @throws Exception\RuntimeException if output cache not started or buffering not active * @return boolean TRUE on success, FALSE on failure writing to cache - * @throws Exception */ public function end() { diff --git a/src/PatternFactory.php b/src/PatternFactory.php index b39efc9fe..5a9de1bc9 100644 --- a/src/PatternFactory.php +++ b/src/PatternFactory.php @@ -32,7 +32,7 @@ class PatternFactory * @param string|Pattern\PatternInterface $patternName * @param array|Traversable|Pattern\PatternOptions $options * @return Pattern\PatternInterface - * @throws Exception\RuntimeException + * @throws Exception\InvalidArgumentException */ public static function factory($patternName, $options = array()) { diff --git a/src/Storage/Adapter/AdapterOptions.php b/src/Storage/Adapter/AdapterOptions.php index 70adb9d5b..f5c0896b4 100644 --- a/src/Storage/Adapter/AdapterOptions.php +++ b/src/Storage/Adapter/AdapterOptions.php @@ -86,6 +86,7 @@ public function setAdapter(StorageInterface $adapter = null) * Set key pattern * * @param null|string $keyPattern + * @throws Exception\InvalidArgumentException * @return AdapterOptions */ public function setKeyPattern($keyPattern) diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index 505cf84a1..a87257a9a 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -103,6 +103,7 @@ public function getOptions() /** * Flush the whole storage * + * @throws Exception\RuntimeException * @return boolean */ public function flush() @@ -179,6 +180,7 @@ public function clearExpired() * Remove items by given namespace * * @param string $namespace + * @throws Exception\RuntimeException * @return boolean */ public function clearByNamespace($namespace) @@ -212,6 +214,7 @@ public function clearByNamespace($namespace) * Remove items matching given prefix * * @param string $prefix + * @throws Exception\RuntimeException * @return boolean */ public function clearByPrefix($prefix) @@ -383,6 +386,7 @@ public function optimize() /** * Get total space in bytes * + * @throws Exception\RuntimeException * @return int|float */ public function getTotalSpace() @@ -419,6 +423,7 @@ public function getTotalSpace() /** * Get available space in bytes * + * @throws Exception\RuntimeException * @return int|float */ public function getAvailableSpace() diff --git a/src/Storage/Adapter/MemoryOptions.php b/src/Storage/Adapter/MemoryOptions.php index ce871fc12..21bb4cc9f 100644 --- a/src/Storage/Adapter/MemoryOptions.php +++ b/src/Storage/Adapter/MemoryOptions.php @@ -80,6 +80,7 @@ public function getMemoryLimit() * Normalized a given value of memory limit into the number of bytes * * @param string|int $value + * @throws Exception\InvalidArgumentException * @return int */ protected function normalizeMemoryLimit($value) diff --git a/src/Storage/Adapter/ZendServerDisk.php b/src/Storage/Adapter/ZendServerDisk.php index e9fe81baa..82c09feb5 100644 --- a/src/Storage/Adapter/ZendServerDisk.php +++ b/src/Storage/Adapter/ZendServerDisk.php @@ -41,7 +41,7 @@ class ZendServerDisk extends AbstractZendServer implements * Constructor * * @param null|array|\Traversable|AdapterOptions $options - * @throws Exception\ExceptionInterface + * @throws Exception\ExtensionNotLoadedException */ public function __construct($options = array()) { @@ -84,6 +84,7 @@ public function clearByNamespace($namespace) /** * Get total space in bytes * + * @throws Exception\RuntimeException * @return int|float */ public function getTotalSpace() @@ -106,6 +107,7 @@ public function getTotalSpace() /** * Get available space in bytes * + * @throws Exception\RuntimeException * @return int|float */ public function getAvailableSpace() diff --git a/src/Storage/Adapter/ZendServerShm.php b/src/Storage/Adapter/ZendServerShm.php index 63759e085..d20b6c995 100644 --- a/src/Storage/Adapter/ZendServerShm.php +++ b/src/Storage/Adapter/ZendServerShm.php @@ -31,7 +31,7 @@ class ZendServerShm extends AbstractZendServer implements * Constructor * * @param null|array|\Traversable|AdapterOptions $options - * @throws Exception\ExceptionInterface + * @throws Exception\ExtensionNotLoadedException */ public function __construct($options = array()) { diff --git a/src/Storage/Plugin/PluginOptions.php b/src/Storage/Plugin/PluginOptions.php index 9ca1b41dc..5bf20b74b 100644 --- a/src/Storage/Plugin/PluginOptions.php +++ b/src/Storage/Plugin/PluginOptions.php @@ -105,7 +105,8 @@ public function getClearingFactor() * Used by: * - ExceptionHandler * - * @param callable ExceptionCallback + * @param callable $exceptionCallback + * @throws Exception\InvalidArgumentException * @return PluginOptions */ public function setExceptionCallback($exceptionCallback) @@ -187,6 +188,7 @@ public function getOptimizingFactor() * - Serializer * * @param string|SerializerAdapter $serializer + * @throws Exception\InvalidArgumentException * @return Serializer */ public function setSerializer($serializer) From d365e1eb48a30adcc9da20d88b2cdf32294060d5 Mon Sep 17 00:00:00 2001 From: Michel Hunziker Date: Fri, 31 Aug 2012 19:52:32 +0200 Subject: [PATCH 309/311] Resolve undefined classes in phpDoc --- src/Pattern/CallbackCache.php | 6 ++++-- src/Pattern/ClassCache.php | 10 ++++++---- src/Pattern/ObjectCache.php | 10 ++++++---- src/Pattern/PatternInterface.php | 2 +- src/Pattern/PatternOptions.php | 4 +++- src/Storage/Adapter/AbstractAdapter.php | 1 + src/Storage/Adapter/Dba.php | 1 + src/Storage/Adapter/DbaOptions.php | 2 +- src/Storage/Adapter/FilesystemIterator.php | 2 +- src/Storage/Adapter/FilesystemOptions.php | 1 + src/Storage/Adapter/WinCache.php | 3 ++- src/Storage/Plugin/ClearExpiredByFactor.php | 4 ++-- src/Storage/StorageInterface.php | 2 ++ 13 files changed, 31 insertions(+), 17 deletions(-) diff --git a/src/Pattern/CallbackCache.php b/src/Pattern/CallbackCache.php index b77e641e7..fe26293d7 100644 --- a/src/Pattern/CallbackCache.php +++ b/src/Pattern/CallbackCache.php @@ -101,7 +101,8 @@ public function call($callback, array $args = array()) * @param string $function Function name to call * @param array $args Function arguments * @return mixed - * @throws Exception + * @throws Exception\RuntimeException + * @throws \Exception */ public function __call($function, array $args) { @@ -115,7 +116,8 @@ public function __call($function, array $args) * @param callable $callback A valid callback * @param array $args Callback arguments * @return string - * @throws Exception + * @throws Exception\RuntimeException + * @throws Exception\InvalidArgumentException */ public function generateKey($callback, array $args = array()) { diff --git a/src/Pattern/ClassCache.php b/src/Pattern/ClassCache.php index 6bd7fbee9..3935c0088 100644 --- a/src/Pattern/ClassCache.php +++ b/src/Pattern/ClassCache.php @@ -44,7 +44,8 @@ public function setOptions(PatternOptions $options) * @param string $method Method name to call * @param array $args Method arguments * @return mixed - * @throws Exception + * @throws Exception\RuntimeException + * @throws \Exception */ public function call($method, array $args = array()) { @@ -78,7 +79,7 @@ public function call($method, array $args = array()) * @param string $method The method * @param array $args Callback arguments * @return string - * @throws Exception + * @throws Exception\RuntimeException */ public function generateKey($method, array $args = array()) { @@ -95,7 +96,7 @@ public function generateKey($method, array $args = array()) * @param callable $callback A valid callback * @param array $args Callback arguments * @return string - * @throws Exception + * @throws Exception\RuntimeException */ protected function generateCallbackKey($callback, array $args) { @@ -110,7 +111,8 @@ protected function generateCallbackKey($callback, array $args) * @param string $method Method name to call * @param array $args Method arguments * @return mixed - * @throws Exception + * @throws Exception\RuntimeException + * @throws \Exception */ public function __call($method, array $args) { diff --git a/src/Pattern/ObjectCache.php b/src/Pattern/ObjectCache.php index e8ab316a7..bff731f50 100644 --- a/src/Pattern/ObjectCache.php +++ b/src/Pattern/ObjectCache.php @@ -43,7 +43,8 @@ public function setOptions(PatternOptions $options) * @param string $method Method name to call * @param array $args Method arguments * @return mixed - * @throws Exception + * @throws Exception\RuntimeException + * @throws \Exception */ public function call($method, array $args = array()) { @@ -158,7 +159,7 @@ public function call($method, array $args = array()) * @param string $method The method * @param array $args Callback arguments * @return string - * @throws Exception + * @throws Exception\RuntimeException */ public function generateKey($method, array $args = array()) { @@ -175,7 +176,7 @@ public function generateKey($method, array $args = array()) * @param callable $callback A valid callback * @param array $args Callback arguments * @return string - * @throws Exception + * @throws Exception\RuntimeException */ protected function generateCallbackKey($callback, array $args = array()) { @@ -190,7 +191,8 @@ protected function generateCallbackKey($callback, array $args = array()) * @param string $method Method name to call * @param array $args Method arguments * @return mixed - * @throws Exception + * @throws Exception\RuntimeException + * @throws \Exception */ public function __call($method, array $args) { diff --git a/src/Pattern/PatternInterface.php b/src/Pattern/PatternInterface.php index 934ccbc53..af39a1e67 100644 --- a/src/Pattern/PatternInterface.php +++ b/src/Pattern/PatternInterface.php @@ -21,7 +21,7 @@ interface PatternInterface * Set pattern options * * @param PatternOptions $options - * @return Pattern + * @return PatternInterface */ public function setOptions(PatternOptions $options); diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 9478f1e81..3090e4b79 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -10,6 +10,7 @@ namespace Zend\Cache\Pattern; +use Traversable; use Zend\Cache\Exception; use Zend\Cache\StorageFactory; use Zend\Cache\Storage\StorageInterface as Storage; @@ -742,7 +743,8 @@ protected function normalizeObjectMethods(array $methods) * Create a storage object from a given specification * * @param array|string|Storage $storage - * @return StorageAdapter + * @throws Exception\InvalidArgumentException + * @return Storage */ protected function storageFactory($storage) { diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index f78755110..9e0e7e53f 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -22,6 +22,7 @@ use Zend\Cache\Storage\PostEvent; use Zend\Cache\Storage\StorageInterface; use Zend\EventManager\EventManager; +use Zend\EventManager\EventManagerInterface; use Zend\EventManager\EventsCapableInterface; /** diff --git a/src/Storage/Adapter/Dba.php b/src/Storage/Adapter/Dba.php index 902498eb1..ef4f2cee8 100644 --- a/src/Storage/Adapter/Dba.php +++ b/src/Storage/Adapter/Dba.php @@ -11,6 +11,7 @@ namespace Zend\Cache\Storage\Adapter; use stdClass; +use Traversable; use Zend\Cache\Exception; use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; diff --git a/src/Storage/Adapter/DbaOptions.php b/src/Storage/Adapter/DbaOptions.php index bcf78379a..5fe3340c2 100644 --- a/src/Storage/Adapter/DbaOptions.php +++ b/src/Storage/Adapter/DbaOptions.php @@ -99,7 +99,7 @@ public function getPathname() /** * * - * @param unknown_type $mode + * @param string $mode * @return \Zend\Cache\Storage\Adapter\DbaOptions */ public function setMode($mode) diff --git a/src/Storage/Adapter/FilesystemIterator.php b/src/Storage/Adapter/FilesystemIterator.php index 142b680f2..b138b2d4b 100644 --- a/src/Storage/Adapter/FilesystemIterator.php +++ b/src/Storage/Adapter/FilesystemIterator.php @@ -74,7 +74,7 @@ public function __construct(Filesystem $storage, $path, $prefix) /** * Get storage instance * - * @return StorageInterface + * @return Filesystem */ public function getStorage() { diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index 1914561c8..e27de8578 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -10,6 +10,7 @@ namespace Zend\Cache\Storage\Adapter; +use Traversable; use Zend\Cache\Exception; /** diff --git a/src/Storage/Adapter/WinCache.php b/src/Storage/Adapter/WinCache.php index aa78b4c1c..bfe8bf9af 100644 --- a/src/Storage/Adapter/WinCache.php +++ b/src/Storage/Adapter/WinCache.php @@ -12,6 +12,7 @@ use ArrayObject; use stdClass; +use Traversable; use Zend\Cache\Exception; use Zend\Cache\Storage\AvailableSpaceCapableInterface; use Zend\Cache\Storage\Capabilities; @@ -60,7 +61,7 @@ public function __construct($options = null) /** * Set options. * - * @param array|\Traversable|WinCacheOptions $options + * @param array|Traversable|WinCacheOptions $options * @return WinCache * @see getOptions() */ diff --git a/src/Storage/Plugin/ClearExpiredByFactor.php b/src/Storage/Plugin/ClearExpiredByFactor.php index 4b4d60a50..0fdbec2ea 100644 --- a/src/Storage/Plugin/ClearExpiredByFactor.php +++ b/src/Storage/Plugin/ClearExpiredByFactor.php @@ -36,7 +36,7 @@ class ClearExpiredByFactor extends AbstractPlugin * * @param EventManagerInterface $events * @param int $priority - * @return ClearByFactor + * @return ClearExpiredByFactor * @throws Exception\LogicException */ public function attach(EventManagerInterface $events, $priority = 1) @@ -62,7 +62,7 @@ public function attach(EventManagerInterface $events, $priority = 1) * Detach * * @param EventManagerInterface $events - * @return ClearByFactor + * @return ClearExpiredByFactor * @throws Exception\LogicException */ public function detach(EventManagerInterface $events) diff --git a/src/Storage/StorageInterface.php b/src/Storage/StorageInterface.php index 8a5df0bcb..3c4f5ec00 100644 --- a/src/Storage/StorageInterface.php +++ b/src/Storage/StorageInterface.php @@ -10,6 +10,8 @@ namespace Zend\Cache\Storage; +use Traversable; + /** * @category Zend * @package Zend_Cache From ec7b2ced3469720a90c6c8fb32f06f44df9ecd1b Mon Sep 17 00:00:00 2001 From: Michel Hunziker Date: Sat, 1 Sep 2012 20:40:03 +0200 Subject: [PATCH 310/311] Resolve more mismatched phpDoc --- src/Pattern/PatternOptions.php | 6 +++--- src/Storage/Adapter/AbstractAdapter.php | 5 ++--- src/Storage/Adapter/AbstractZendServer.php | 3 +-- src/Storage/Adapter/Apc.php | 4 ++-- src/Storage/Adapter/Filesystem.php | 4 ++-- src/Storage/Adapter/FilesystemOptions.php | 2 +- src/Storage/Adapter/Memcached.php | 1 - src/Storage/Adapter/MemcachedOptions.php | 1 + src/Storage/Adapter/Memory.php | 7 ++----- src/Storage/Capabilities.php | 6 +++--- 10 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index 3090e4b79..dce78c9d2 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -152,7 +152,7 @@ class PatternOptions extends AbstractOptions * Constructor * * @param array|Traversable|null $options - * @return AbstractOptions + * @return PatternOptions * @throws Exception\InvalidArgumentException */ public function __construct($options = null) @@ -492,7 +492,7 @@ public function getIndexFilename() /** * Set object to cache * - * @param mixed $value + * @param mixed $object * @return $this */ public function setObject($object) @@ -575,7 +575,7 @@ public function getObjectCacheMethods() * Used by: * - ObjectCache * - * @param mixed $value + * @param mixed $objectKey * @return $this */ public function setObjectKey($objectKey) diff --git a/src/Storage/Adapter/AbstractAdapter.php b/src/Storage/Adapter/AbstractAdapter.php index 9e0e7e53f..61a950042 100644 --- a/src/Storage/Adapter/AbstractAdapter.php +++ b/src/Storage/Adapter/AbstractAdapter.php @@ -538,7 +538,7 @@ public function hasItems(array $keys) /** * Internal method to test multiple items. * - * @param array $keys + * @param array $normalizedKeys * @return array Array of found keys * @throws Exception\ExceptionInterface */ @@ -750,7 +750,6 @@ public function setItems(array $keyValuePairs) * Internal method to store multiple items. * * @param array $normalizedKeyValuePairs - * @param array $normalizedOptions * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ @@ -1234,7 +1233,7 @@ public function removeItems(array $keys) /** * Internal method to remove multiple items. * - * @param array $keys + * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ diff --git a/src/Storage/Adapter/AbstractZendServer.php b/src/Storage/Adapter/AbstractZendServer.php index b18991add..d5d9ffc92 100644 --- a/src/Storage/Adapter/AbstractZendServer.php +++ b/src/Storage/Adapter/AbstractZendServer.php @@ -87,7 +87,6 @@ protected function internalGetItems(array & $normalizedKeys) * Internal method to test if an item exists. * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ @@ -101,7 +100,7 @@ protected function internalHasItem(& $normalizedKey) /** * Internal method to test multiple items. * - * @param array $keys + * @param array $normalizedKeys * @return array Array of found keys * @throws Exception\ExceptionInterface */ diff --git a/src/Storage/Adapter/Apc.php b/src/Storage/Adapter/Apc.php index c5cee10e0..b380672f4 100644 --- a/src/Storage/Adapter/Apc.php +++ b/src/Storage/Adapter/Apc.php @@ -265,7 +265,7 @@ protected function internalHasItem(& $normalizedKey) /** * Internal method to test multiple items. * - * @param array $keys + * @param array $normalizedKeys * @return array Array of found keys * @throws Exception\ExceptionInterface */ @@ -523,7 +523,7 @@ protected function internalRemoveItem(& $normalizedKey) /** * Internal method to remove multiple items. * - * @param array $keys + * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ diff --git a/src/Storage/Adapter/Filesystem.php b/src/Storage/Adapter/Filesystem.php index a87257a9a..4454c7d05 100644 --- a/src/Storage/Adapter/Filesystem.php +++ b/src/Storage/Adapter/Filesystem.php @@ -615,7 +615,6 @@ public function hasItems(array $keys) * Internal method to test if an item exists. * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ @@ -665,6 +664,7 @@ public function getMetadata($key) * Get metadatas * * @param array $keys + * @param array $options * @return array Associative array of keys and metadata */ public function getMetadatas(array $keys, array $options = array()) @@ -1032,7 +1032,7 @@ public function touchItems(array $keys) /** * Internal method to reset lifetime of an item * - * @param string $key + * @param string $normalizedKey * @return boolean * @throws Exception\ExceptionInterface */ diff --git a/src/Storage/Adapter/FilesystemOptions.php b/src/Storage/Adapter/FilesystemOptions.php index e27de8578..bc472f92c 100644 --- a/src/Storage/Adapter/FilesystemOptions.php +++ b/src/Storage/Adapter/FilesystemOptions.php @@ -107,7 +107,7 @@ class FilesystemOptions extends AdapterOptions * Constructor * * @param array|Traversable|null $options - * @return AbstractOptions + * @return FilesystemOptions * @throws Exception\InvalidArgumentException */ public function __construct($options = null) diff --git a/src/Storage/Adapter/Memcached.php b/src/Storage/Adapter/Memcached.php index cbd77d8c8..d0f5a955b 100644 --- a/src/Storage/Adapter/Memcached.php +++ b/src/Storage/Adapter/Memcached.php @@ -17,7 +17,6 @@ use Traversable; use Zend\Cache\Exception; use Zend\Cache\Storage\AvailableSpaceCapableInterface; -use Zend\Cache\Storage\CallbackEvent; use Zend\Cache\Storage\Capabilities; use Zend\Cache\Storage\Event; use Zend\Cache\Storage\FlushableInterface; diff --git a/src/Storage/Adapter/MemcachedOptions.php b/src/Storage/Adapter/MemcachedOptions.php index 89c627786..8f0d3418e 100644 --- a/src/Storage/Adapter/MemcachedOptions.php +++ b/src/Storage/Adapter/MemcachedOptions.php @@ -176,6 +176,7 @@ public function getLibOptions() /** * Get libmemcached option * + * @param string|int $key * @return mixed * @link http://php.net/manual/memcached.constants.php */ diff --git a/src/Storage/Adapter/Memory.php b/src/Storage/Adapter/Memory.php index a779f735e..ba462e717 100644 --- a/src/Storage/Adapter/Memory.php +++ b/src/Storage/Adapter/Memory.php @@ -115,7 +115,7 @@ public function getAvailableSpace() /** * Get the storage iterator * - * @return MemoryIterator + * @return KeyListIterator */ public function getIterator() { @@ -346,9 +346,7 @@ protected function internalGetItems(array & $normalizedKeys) * Internal method to test if an item exists. * * @param string $normalizedKey - * @param array $normalizedOptions * @return boolean - * @throws Exception\ExceptionInterface */ protected function internalHasItem(& $normalizedKey) { @@ -370,9 +368,8 @@ protected function internalHasItem(& $normalizedKey) /** * Internal method to test multiple items. * - * @param array $keys + * @param array $normalizedKeys * @return array Array of found keys - * @throws Exception\ExceptionInterface */ protected function internalHasItems(array & $normalizedKeys) { diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index 97dce7604..d3dcf4197 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -156,7 +156,7 @@ class Capabilities /** * Constructor * - * @param Adapter $adapter + * @param StorageInterface $storage * @param stdClass $marker * @param array $capabilities * @param null|Capabilities $baseCapabilities @@ -179,7 +179,7 @@ public function __construct( /** * Get the storage adapter * - * @return Adapter + * @return StorageInterface */ public function getAdapter() { @@ -514,7 +514,7 @@ protected function getCapability($property, $default = null) * Change a capability * * @param stdClass $marker - * @param string $name + * @param string $property * @param mixed $value * @return Capabilities Fluent interface * @throws Exception\InvalidArgumentException From 6cb2de0226c6d7d9412c35b43d2fbb9d6930b0bb Mon Sep 17 00:00:00 2001 From: Michel Hunziker Date: Sat, 1 Sep 2012 22:09:27 +0200 Subject: [PATCH 311/311] Add more missing @throws annotations --- src/Pattern/PatternOptions.php | 6 ++++++ src/Storage/Capabilities.php | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/src/Pattern/PatternOptions.php b/src/Pattern/PatternOptions.php index dce78c9d2..02b03ff70 100644 --- a/src/Pattern/PatternOptions.php +++ b/src/Pattern/PatternOptions.php @@ -235,6 +235,7 @@ public function getCacheOutput() * - ClassCache * * @param string $class + * @throws Exception\InvalidArgumentException * @return PatternOptions */ public function setClass($class) @@ -319,6 +320,7 @@ public function getClassNonCacheMethods() * Set directory permission * * @param false|int $dirPermission + * @throws Exception\InvalidArgumentException * @return PatternOptions */ public function setDirPermission($dirPermission) @@ -359,6 +361,7 @@ public function getDirPermission() * - CaptureCache * * @param false|int $umask + * @throws Exception\InvalidArgumentException * @return PatternOptions */ public function setUmask($umask) @@ -430,6 +433,7 @@ public function getFileLocking() * Set file permission * * @param false|int $filePermission + * @throws Exception\InvalidArgumentException * @return PatternOptions */ public function setFilePermission($filePermission) @@ -493,6 +497,7 @@ public function getIndexFilename() * Set object to cache * * @param mixed $object + * @throws Exception\InvalidArgumentException * @return $this */ public function setObject($object) @@ -634,6 +639,7 @@ public function getObjectNonCacheMethods() * - CaptureCache * * @param string $publicDir + * @throws Exception\InvalidArgumentException * @return PatternOptions */ public function setPublicDir($publicDir) diff --git a/src/Storage/Capabilities.php b/src/Storage/Capabilities.php index d3dcf4197..de0d3f07d 100644 --- a/src/Storage/Capabilities.php +++ b/src/Storage/Capabilities.php @@ -210,6 +210,7 @@ public function getSupportedDatatypes() * * @param stdClass $marker * @param array $datatypes + * @throws Exception\InvalidArgumentException * @return Capabilities Fluent interface */ public function setSupportedDatatypes(stdClass $marker, array $datatypes) @@ -265,6 +266,7 @@ public function getSupportedMetadata() * * @param stdClass $marker * @param string[] $metadata + * @throws Exception\InvalidArgumentException * @return Capabilities Fluent interface */ public function setSupportedMetadata(stdClass $marker, array $metadata) @@ -292,6 +294,7 @@ public function getMinTtl() * * @param stdClass $marker * @param int $minTtl + * @throws Exception\InvalidArgumentException * @return Capabilities Fluent interface */ public function setMinTtl(stdClass $marker, $minTtl) @@ -318,6 +321,7 @@ public function getMaxTtl() * * @param stdClass $marker * @param int $maxTtl + * @throws Exception\InvalidArgumentException * @return Capabilities Fluent interface */ public function setMaxTtl(stdClass $marker, $maxTtl) @@ -367,6 +371,7 @@ public function getTtlPrecision() * * @param stdClass $marker * @param float $ttlPrecision + * @throws Exception\InvalidArgumentException * @return Capabilities Fluent interface */ public function setTtlPrecision(stdClass $marker, $ttlPrecision) @@ -437,6 +442,7 @@ public function getMaxKeyLength() * * @param stdClass $marker * @param int $maxKeyLength + * @throws Exception\InvalidArgumentException * @return Capabilities Fluent interface */ public function setMaxKeyLength(stdClass $marker, $maxKeyLength)