From 006fb884707bd180dccc6430376ef8b56bc8ab60 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 31 Aug 2012 14:44:59 -0500 Subject: [PATCH] [zendframework/zf2#2284][ZF2-507] Updated README - Notice about Date header --- .coveralls.yml | 3 + .gitattributes | 6 + .gitignore | 14 + .php_cs | 43 + .travis.yml | 35 + CONTRIBUTING.md | 229 +++++ LICENSE.txt | 27 + README.md | 8 + composer.json | 49 + phpunit.xml.dist | 34 + phpunit.xml.travis | 34 + src/Adapter/AdapterInterface.php | 31 + src/Adapter/ArrayAdapter.php | 65 ++ src/Adapter/DbSelect.php | 124 +++ src/Adapter/Exception/ExceptionInterface.php | 21 + .../Exception/InvalidArgumentException.php | 22 + src/Adapter/Exception/RuntimeException.php | 22 + .../Exception/UnexpectedValueException.php | 22 + src/Adapter/Iterator.php | 75 ++ src/Adapter/Null.php | 64 ++ src/AdapterAggregateInterface.php | 30 + src/Exception/ExceptionInterface.php | 18 + src/Exception/InvalidArgumentException.php | 21 + src/Exception/RuntimeException.php | 21 + src/Exception/UnexpectedValueException.php | 21 + src/Paginator.php | 972 ++++++++++++++++++ src/ScrollingStyle/All.php | 36 + src/ScrollingStyle/Elastic.php | 49 + src/ScrollingStyle/Jumping.php | 49 + .../ScrollingStyleInterface.php | 29 + src/ScrollingStyle/Sliding.php | 64 ++ src/ScrollingStylePluginManager.php | 62 ++ src/SerializableLimitIterator.php | 134 +++ test/Adapter/ArrayTest.php | 74 ++ test/Adapter/DbSelectTest.php | 69 ++ test/Adapter/IteratorTest.php | 117 +++ test/Adapter/NullTest.php | 100 ++ test/PaginatorTest.php | 806 +++++++++++++++ test/ScrollingStyle/AllTest.php | 99 ++ test/ScrollingStyle/ElasticTest.php | 148 +++ test/ScrollingStyle/JumpingTest.php | 124 +++ test/ScrollingStyle/SlidingTest.php | 131 +++ .../TestAsset/ScrollingStylePluginManager.php | 22 + test/TestAsset/TestAdapter.php | 29 + test/_files/config.xml | 14 + test/_files/scripts/partial.phtml | 1 + test/bootstrap.php | 34 + 47 files changed, 4202 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/Adapter/AdapterInterface.php create mode 100644 src/Adapter/ArrayAdapter.php create mode 100644 src/Adapter/DbSelect.php create mode 100644 src/Adapter/Exception/ExceptionInterface.php create mode 100644 src/Adapter/Exception/InvalidArgumentException.php create mode 100644 src/Adapter/Exception/RuntimeException.php create mode 100644 src/Adapter/Exception/UnexpectedValueException.php create mode 100644 src/Adapter/Iterator.php create mode 100644 src/Adapter/Null.php create mode 100644 src/AdapterAggregateInterface.php create mode 100644 src/Exception/ExceptionInterface.php create mode 100644 src/Exception/InvalidArgumentException.php create mode 100644 src/Exception/RuntimeException.php create mode 100644 src/Exception/UnexpectedValueException.php create mode 100644 src/Paginator.php create mode 100644 src/ScrollingStyle/All.php create mode 100644 src/ScrollingStyle/Elastic.php create mode 100644 src/ScrollingStyle/Jumping.php create mode 100644 src/ScrollingStyle/ScrollingStyleInterface.php create mode 100644 src/ScrollingStyle/Sliding.php create mode 100644 src/ScrollingStylePluginManager.php create mode 100644 src/SerializableLimitIterator.php create mode 100644 test/Adapter/ArrayTest.php create mode 100644 test/Adapter/DbSelectTest.php create mode 100644 test/Adapter/IteratorTest.php create mode 100644 test/Adapter/NullTest.php create mode 100644 test/PaginatorTest.php create mode 100644 test/ScrollingStyle/AllTest.php create mode 100644 test/ScrollingStyle/ElasticTest.php create mode 100644 test/ScrollingStyle/JumpingTest.php create mode 100644 test/ScrollingStyle/SlidingTest.php create mode 100644 test/TestAsset/ScrollingStylePluginManager.php create mode 100644 test/TestAsset/TestAdapter.php create mode 100644 test/_files/config.xml create mode 100644 test/_files/scripts/partial.phtml create mode 100644 test/bootstrap.php diff --git a/.coveralls.yml b/.coveralls.yml new file mode 100644 index 0000000..53bda82 --- /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 0000000..85dc9a8 --- /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 0000000..4cac0a2 --- /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 0000000..bf4b799 --- /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 0000000..fe909ec --- /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 0000000..e27da18 --- /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-paginator/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-paginator.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-paginator) +3. Clone the canonical repository locally and enter it. + + ```console + $ git clone git://github.com:zendframework/zend-paginator.git + $ cd zend-paginator + ``` + +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-paginator.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-paginator.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 0000000..6eab5aa --- /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 0000000..60cf83b --- /dev/null +++ b/README.md @@ -0,0 +1,8 @@ +# zend-paginator + +`Zend\Paginator` is a flexible component for paginating collections of data and +presenting that data to users. + + +- File issues at https://github.com/zendframework/zend-paginator/issues +- Documentation is at http://framework.zend.com/manual/current/en/index.html#zend-paginator diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..9e4909a --- /dev/null +++ b/composer.json @@ -0,0 +1,49 @@ +{ + "name": "zendframework/zend-paginator", + "description": " ", + "license": "BSD-3-Clause", + "keywords": [ + "zf2", + "paginator" + ], + "homepage": "https://github.com/zendframework/zend-paginator", + "autoload": { + "psr-4": { + "Zend\\Paginator": "src/" + } + }, + "require": { + "php": ">=5.3.3", + "zendframework/zend-stdlib": "self.version" + }, + "require-dev": { + "zendframework/zend-cache": "self.version", + "zendframework/zend-db": "self.version", + "zendframework/zend-filter": "self.version", + "zendframework/zend-json": "self.version", + "zendframework/zend-servicemanager": "self.version", + "zendframework/zend-view": "self.version", + "fabpot/php-cs-fixer": "1.7.*", + "satooshi/php-coveralls": "dev-master", + "phpunit/PHPUnit": "~4.0" + }, + "suggest": { + "zendframework/zend-cache": "Zend\\Cache component to support cache features", + "zendframework/zend-db": "Zend\\Db component", + "zendframework/zend-filter": "Zend\\Filter component", + "zendframework/zend-json": "Zend\\Json component", + "zendframework/zend-servicemanager": "Zend\\ServiceManager component", + "zendframework/zend-view": "Zend\\View component" + }, + "extra": { + "branch-alias": { + "dev-master": "2.4-dev", + "dev-develop": "2.5-dev" + } + }, + "autoload-dev": { + "psr-4": { + "ZendTest\\Paginator\\": "test/" + } + } +} \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..0d1dbb1 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,34 @@ + + + + + ./test/ + + + + + + disable + + + + + + ./src + + + + + + + + + + + diff --git a/phpunit.xml.travis b/phpunit.xml.travis new file mode 100644 index 0000000..0d1dbb1 --- /dev/null +++ b/phpunit.xml.travis @@ -0,0 +1,34 @@ + + + + + ./test/ + + + + + + disable + + + + + + ./src + + + + + + + + + + + diff --git a/src/Adapter/AdapterInterface.php b/src/Adapter/AdapterInterface.php new file mode 100644 index 0000000..633fd0e --- /dev/null +++ b/src/Adapter/AdapterInterface.php @@ -0,0 +1,31 @@ +array = $array; + $this->count = count($array); + } + + /** + * Returns an array of items for a page. + * + * @param integer $offset Page offset + * @param integer $itemCountPerPage Number of items per page + * @return array + */ + public function getItems($offset, $itemCountPerPage) + { + return array_slice($this->array, $offset, $itemCountPerPage); + } + + /** + * Returns the total number of rows in the array. + * + * @return integer + */ + public function count() + { + return $this->count; + } +} diff --git a/src/Adapter/DbSelect.php b/src/Adapter/DbSelect.php new file mode 100644 index 0000000..4875fea --- /dev/null +++ b/src/Adapter/DbSelect.php @@ -0,0 +1,124 @@ +select = $select; + + if ($adapterOrSqlObject instanceof Adapter) { + $adapterOrSqlObject = new Sql($adapterOrSqlObject); + } + + if (!$adapterOrSqlObject instanceof Sql) { + throw new Exception\InvalidArgumentException( + '$adapterOrSqlObject must be an instance of Zend\Db\Adapter\Adapter or Zend\Db\Sql\Sql' + ); + } + + $this->sql = $adapterOrSqlObject; + $this->resultSetPrototype = ($resultSetPrototype) ?: new ResultSet; + } + + /** + * Returns an array of items for a page. + * + * @param integer $offset Page offset + * @param integer $itemCountPerPage Number of items per page + * @return array + */ + public function getItems($offset, $itemCountPerPage) + { + $select = clone $this->select; + $select->offset($offset); + $select->limit($itemCountPerPage); + + $statement = $this->sql->prepareStatementForSqlObject($select); + $result = $statement->execute(); + + $resultSet = clone $this->resultSetPrototype; + $resultSet->initialize($result); + + return $resultSet; + } + + /** + * Returns the total number of rows in the result set. + * + * @return integer + */ + public function count() + { + if ($this->rowCount !== null) { + return $this->rowCount; + } + + $select = clone $this->select; + $select->reset(Select::COLUMNS); + $select->reset(Select::LIMIT); + $select->reset(Select::OFFSET); + + $select->columns(array('c' => new Expression('COUNT(1)'))); + + $statement = $this->sql->prepareStatementForSqlObject($select); + $result = $statement->execute(); + $row = $result->current(); + + $this->rowCount = $row['c']; + + return $this->rowCount; + } +} diff --git a/src/Adapter/Exception/ExceptionInterface.php b/src/Adapter/Exception/ExceptionInterface.php new file mode 100644 index 0000000..6401f2d --- /dev/null +++ b/src/Adapter/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ +iterator = $iterator; + $this->count = count($iterator); + } + + /** + * Returns an iterator of items for a page, or an empty array. + * + * @param integer $offset Page offset + * @param integer $itemCountPerPage Number of items per page + * @return array|\Zend\Paginator\SerializableLimitIterator + */ + public function getItems($offset, $itemCountPerPage) + { + if ($this->count == 0) { + return array(); + } + return new Paginator\SerializableLimitIterator($this->iterator, $offset, $itemCountPerPage); + } + + /** + * Returns the total number of rows in the collection. + * + * @return integer + */ + public function count() + { + return $this->count; + } +} diff --git a/src/Adapter/Null.php b/src/Adapter/Null.php new file mode 100644 index 0000000..38c0895 --- /dev/null +++ b/src/Adapter/Null.php @@ -0,0 +1,64 @@ +count = $count; + } + + /** + * Returns an array of items for a page. + * + * @param integer $offset Page offset + * @param integer $itemCountPerPage Number of items per page + * @return array + */ + public function getItems($offset, $itemCountPerPage) + { + if ($offset >= $this->count()) { + return array(); + } + + $remainItemCount = $this->count() - $offset; + $currentItemCount = $remainItemCount > $itemCountPerPage ? $itemCountPerPage : $remainItemCount; + + return array_fill(0, $currentItemCount, null); + } + + /** + * Returns the total number of rows in the array. + * + * @return integer + */ + public function count() + { + return $this->count; + } +} diff --git a/src/AdapterAggregateInterface.php b/src/AdapterAggregateInterface.php new file mode 100644 index 0000000..bce8c18 --- /dev/null +++ b/src/AdapterAggregateInterface.php @@ -0,0 +1,30 @@ +adapter = $adapter; + } elseif ($adapter instanceof AdapterAggregateInterface) { + $this->adapter = $adapter->getPaginatorAdapter(); + } else { + throw new Exception\InvalidArgumentException( + 'Zend_Paginator only accepts instances of the type ' . + 'Zend\Paginator\Adapter\AdapterInterface or Zend\Paginator\AdapterAggregateInterface.' + ); + } + + $config = self::$config; + + if (!empty($config)) { + $setupMethods = array('ItemCountPerPage', 'PageRange'); + + foreach ($setupMethods as $setupMethod) { + $key = strtolower($setupMethod); + $value = isset($config[$key]) ? $config[$key] : null; + + if ($value != null) { + $setupMethod = 'set' . $setupMethod; + $this->$setupMethod($value); + } + } + } + } + + /** + * Serializes the object as a string. Proxies to {@link render()}. + * + * @return string + */ + public function __toString() + { + try { + $return = $this->render(); + return $return; + } catch (\Exception $e) { + trigger_error($e->getMessage(), E_USER_WARNING); + } + + return ''; + } + + /** + * Enables/Disables the cache for this instance + * + * @param bool $enable + * @return Paginator + */ + public function setCacheEnabled($enable) + { + $this->cacheEnabled = (bool)$enable; + return $this; + } + + /** + * Returns the number of pages. + * + * @return integer + */ + public function count() + { + if (!$this->pageCount) { + $this->pageCount = $this->_calculatePageCount(); + } + + return $this->pageCount; + } + + /** + * Returns the total number of items available. + * + * @return integer + */ + public function getTotalItemCount() + { + return count($this->getAdapter()); + } + + /** + * Clear the page item cache. + * + * @param int $pageNumber + * @return Paginator + */ + public function clearPageItemCache($pageNumber = null) + { + if (!$this->cacheEnabled()) { + return $this; + } + + if (null === $pageNumber) { + $prefixLength = strlen(self::CACHE_TAG_PREFIX); + $cacheIterator = self::$cache->getIterator(); + $cacheIterator->setMode(CacheIterator::CURRENT_AS_KEY); + foreach ($cacheIterator as $key) { + $tags = self::$cache->getTags($key); + if ($tags && in_array($this->_getCacheInternalId(), $tags)) { + if (substr($key, 0, $prefixLength) == self::CACHE_TAG_PREFIX) { + self::$cache->removeItem($this->_getCacheId((int)substr($key, $prefixLength))); + } + } + } + } else { + $cleanId = $this->_getCacheId($pageNumber); + self::$cache->removeItem($cleanId); + } + return $this; + } + + /** + * Returns the absolute item number for the specified item. + * + * @param integer $relativeItemNumber Relative item number + * @param integer $pageNumber Page number + * @return integer + */ + public function getAbsoluteItemNumber($relativeItemNumber, $pageNumber = null) + { + $relativeItemNumber = $this->normalizeItemNumber($relativeItemNumber); + + if ($pageNumber == null) { + $pageNumber = $this->getCurrentPageNumber(); + } + + $pageNumber = $this->normalizePageNumber($pageNumber); + + return (($pageNumber - 1) * $this->getItemCountPerPage()) + $relativeItemNumber; + } + + /** + * Returns the adapter. + * + * @return AdapterInterface + */ + public function getAdapter() + { + return $this->adapter; + } + + /** + * Returns the number of items for the current page. + * + * @return integer + */ + public function getCurrentItemCount() + { + if ($this->currentItemCount === null) { + $this->currentItemCount = $this->getItemCount($this->getCurrentItems()); + } + + return $this->currentItemCount; + } + + /** + * Returns the items for the current page. + * + * @return Traversable + */ + public function getCurrentItems() + { + if ($this->currentItems === null) { + $this->currentItems = $this->getItemsByPage($this->getCurrentPageNumber()); + } + + return $this->currentItems; + } + + /** + * Returns the current page number. + * + * @return integer + */ + public function getCurrentPageNumber() + { + return $this->normalizePageNumber($this->currentPageNumber); + } + + /** + * Sets the current page number. + * + * @param integer $pageNumber Page number + * @return Paginator $this + */ + public function setCurrentPageNumber($pageNumber) + { + $this->currentPageNumber = (integer) $pageNumber; + $this->currentItems = null; + $this->currentItemCount = null; + + return $this; + } + + /** + * Get the filter + * + * @return FilterInterface + */ + public function getFilter() + { + return $this->filter; + } + + /** + * Set a filter chain + * + * @param FilterInterface $filter + * @return Paginator + */ + public function setFilter(FilterInterface $filter) + { + $this->filter = $filter; + + return $this; + } + + /** + * Returns an item from a page. The current page is used if there's no + * page specified. + * + * @param integer $itemNumber Item number (1 to itemCountPerPage) + * @param integer $pageNumber + * @throws Exception\InvalidArgumentException + * @return mixed + */ + public function getItem($itemNumber, $pageNumber = null) + { + if ($pageNumber == null) { + $pageNumber = $this->getCurrentPageNumber(); + } elseif ($pageNumber < 0) { + $pageNumber = ($this->count() + 1) + $pageNumber; + } + + $page = $this->getItemsByPage($pageNumber); + $itemCount = $this->getItemCount($page); + + if ($itemCount == 0) { + throw new Exception\InvalidArgumentException('Page ' . $pageNumber . ' does not exist'); + } + + if ($itemNumber < 0) { + $itemNumber = ($itemCount + 1) + $itemNumber; + } + + $itemNumber = $this->normalizeItemNumber($itemNumber); + + if ($itemNumber > $itemCount) { + throw new Exception\InvalidArgumentException('Page ' . $pageNumber . ' does not' + . ' contain item number ' . $itemNumber); + } + + return $page[$itemNumber - 1]; + } + + /** + * Returns the number of items per page. + * + * @return integer + */ + public function getItemCountPerPage() + { + if (empty($this->itemCountPerPage)) { + $this->itemCountPerPage = self::getDefaultItemCountPerPage(); + } + + return $this->itemCountPerPage; + } + + /** + * Sets the number of items per page. + * + * @param integer $itemCountPerPage + * @return Paginator $this + */ + public function setItemCountPerPage($itemCountPerPage = -1) + { + $this->itemCountPerPage = (integer) $itemCountPerPage; + if ($this->itemCountPerPage < 1) { + $this->itemCountPerPage = $this->getTotalItemCount(); + } + $this->pageCount = $this->_calculatePageCount(); + $this->currentItems = null; + $this->currentItemCount = null; + + return $this; + } + + /** + * Returns the number of items in a collection. + * + * @param mixed $items Items + * @return integer + */ + public function getItemCount($items) + { + $itemCount = 0; + + if (is_array($items) || $items instanceof Countable) { + $itemCount = count($items); + } elseif ($items instanceof Traversable) { // $items is something like LimitIterator + $itemCount = iterator_count($items); + } + + return $itemCount; + } + + /** + * Returns the items for a given page. + * + * @param integer $pageNumber + * @return mixed + */ + public function getItemsByPage($pageNumber) + { + $pageNumber = $this->normalizePageNumber($pageNumber); + + if ($this->cacheEnabled()) { + $data = self::$cache->getItem($this->_getCacheId($pageNumber)); + if ($data) { + return $data; + } + } + + $offset = ($pageNumber - 1) * $this->getItemCountPerPage(); + + $items = $this->adapter->getItems($offset, $this->getItemCountPerPage()); + + $filter = $this->getFilter(); + + if ($filter !== null) { + $items = $filter->filter($items); + } + + if (!$items instanceof Traversable) { + $items = new ArrayIterator($items); + } + + if ($this->cacheEnabled()) { + $cacheId = $this->_getCacheId($pageNumber); + self::$cache->setItem($cacheId, $items); + self::$cache->setTags($cacheId, array($this->_getCacheInternalId())); + } + + return $items; + } + + /** + * Returns a foreach-compatible iterator. + * + * @throws Exception\RuntimeException + * @return Traversable + */ + public function getIterator() + { + try { + return $this->getCurrentItems(); + } catch (\Exception $e) { + throw new Exception\RuntimeException('Error producing an iterator', null, $e); + } + } + + /** + * Returns the page range (see property declaration above). + * + * @return integer + */ + public function getPageRange() + { + return $this->pageRange; + } + + /** + * Sets the page range (see property declaration above). + * + * @param integer $pageRange + * @return Paginator $this + */ + public function setPageRange($pageRange) + { + $this->pageRange = (integer) $pageRange; + + return $this; + } + + /** + * Returns the page collection. + * + * @param string $scrollingStyle Scrolling style + * @return array + */ + public function getPages($scrollingStyle = null) + { + if ($this->pages === null) { + $this->pages = $this->_createPages($scrollingStyle); + } + + return $this->pages; + } + + /** + * Returns a subset of pages within a given range. + * + * @param integer $lowerBound Lower bound of the range + * @param integer $upperBound Upper bound of the range + * @return array + */ + public function getPagesInRange($lowerBound, $upperBound) + { + $lowerBound = $this->normalizePageNumber($lowerBound); + $upperBound = $this->normalizePageNumber($upperBound); + + $pages = array(); + + for ($pageNumber = $lowerBound; $pageNumber <= $upperBound; $pageNumber++) { + $pages[$pageNumber] = $pageNumber; + } + + return $pages; + } + + /** + * Returns the page item cache. + * + * @return array + */ + public function getPageItemCache() + { + $data = array(); + if ($this->cacheEnabled()) { + $prefixLength = strlen(self::CACHE_TAG_PREFIX); + $cacheIterator = self::$cache->getIterator(); + $cacheIterator->setMode(CacheIterator::CURRENT_AS_VALUE); + foreach ($cacheIterator as $key => $value) { + $tags = self::$cache->getTags($key); + if ($tags && in_array($this->_getCacheInternalId(), $tags)) { + if (substr($key, 0, $prefixLength) == self::CACHE_TAG_PREFIX) { + $data[(int)substr($key, $prefixLength)] = $value; + } + } + } + } + return $data; + } + + /** + * Retrieves the view instance. + * + * If none registered, instantiates a PhpRenderer instance. + * + * @return \Zend\View\Renderer\RendererInterface|null + */ + public function getView() + { + if ($this->view === null) { + $this->setView(new View\Renderer\PhpRenderer()); + } + + return $this->view; + } + + /** + * Sets the view object. + * + * @param \Zend\View\Renderer\RendererInterface $view + * @return Paginator + */ + public function setView(View\Renderer\RendererInterface $view = null) + { + $this->view = $view; + + return $this; + } + + /** + * Brings the item number in range of the page. + * + * @param integer $itemNumber + * @return integer + */ + public function normalizeItemNumber($itemNumber) + { + $itemNumber = (integer) $itemNumber; + + if ($itemNumber < 1) { + $itemNumber = 1; + } + + if ($itemNumber > $this->getItemCountPerPage()) { + $itemNumber = $this->getItemCountPerPage(); + } + + return $itemNumber; + } + + /** + * Brings the page number in range of the paginator. + * + * @param integer $pageNumber + * @return integer + */ + public function normalizePageNumber($pageNumber) + { + $pageNumber = (integer) $pageNumber; + + if ($pageNumber < 1) { + $pageNumber = 1; + } + + $pageCount = $this->count(); + + if ($pageCount > 0 && $pageNumber > $pageCount) { + $pageNumber = $pageCount; + } + + return $pageNumber; + } + + /** + * Renders the paginator. + * + * @param \Zend\View\Renderer\RendererInterface $view + * @return string + */ + public function render(View\Renderer\RendererInterface $view = null) + { + if (null !== $view) { + $this->setView($view); + } + + $view = $this->getView(); + + return $view->paginationControl($this); + } + + /** + * Returns the items of the current page as JSON. + * + * @return string + */ + public function toJson() + { + $currentItems = $this->getCurrentItems(); + + if ($currentItems instanceof DbAbstractRowset) { + return Json::encode($currentItems->toArray()); + } else { + return Json::encode($currentItems); + } + } + + /** + * Tells if there is an active cache object + * and if the cache has not been disabled + * + * @return bool + */ + protected function cacheEnabled() + { + return ((self::$cache !== null) && $this->cacheEnabled); + } + + /** + * Makes an Id for the cache + * Depends on the adapter object and the page number + * + * Used to store item in cache from that Paginator instance + * and that current page + * + * @param int $page + * @return string + */ + protected function _getCacheId($page = null) + { + if ($page === null) { + $page = $this->getCurrentPageNumber(); + } + return self::CACHE_TAG_PREFIX . $page . '_' . $this->_getCacheInternalId(); + } + + /** + * Get the internal cache id + * Depends on the adapter and the item count per page + * + * Used to tag that unique Paginator instance in cache + * + * @return string + */ + protected function _getCacheInternalId() + { + return md5(serialize(array( + spl_object_hash($this->getAdapter()), + $this->getItemCountPerPage() + ))); + } + + /** + * Calculates the page count. + * + * @return integer + */ + protected function _calculatePageCount() + { + return (integer) ceil($this->getAdapter()->count() / $this->getItemCountPerPage()); + } + + /** + * Creates the page collection. + * + * @param string $scrollingStyle Scrolling style + * @return stdClass + */ + protected function _createPages($scrollingStyle = null) + { + $pageCount = $this->count(); + $currentPageNumber = $this->getCurrentPageNumber(); + + $pages = new \stdClass(); + $pages->pageCount = $pageCount; + $pages->itemCountPerPage = $this->getItemCountPerPage(); + $pages->first = 1; + $pages->current = $currentPageNumber; + $pages->last = $pageCount; + + // Previous and next + if ($currentPageNumber - 1 > 0) { + $pages->previous = $currentPageNumber - 1; + } + + if ($currentPageNumber + 1 <= $pageCount) { + $pages->next = $currentPageNumber + 1; + } + + // Pages in range + $scrollingStyle = $this->_loadScrollingStyle($scrollingStyle); + $pages->pagesInRange = $scrollingStyle->getPages($this); + $pages->firstPageInRange = min($pages->pagesInRange); + $pages->lastPageInRange = max($pages->pagesInRange); + + // Item numbers + if ($this->getCurrentItems() !== null) { + $pages->currentItemCount = $this->getCurrentItemCount(); + $pages->itemCountPerPage = $this->getItemCountPerPage(); + $pages->totalItemCount = $this->getTotalItemCount(); + $pages->firstItemNumber = (($currentPageNumber - 1) * $this->getItemCountPerPage()) + 1; + $pages->lastItemNumber = $pages->firstItemNumber + $pages->currentItemCount - 1; + } + + return $pages; + } + + /** + * Loads a scrolling style. + * + * @param string $scrollingStyle + * @return ScrollingStyleInterface + * @throws Exception\InvalidArgumentException + */ + protected function _loadScrollingStyle($scrollingStyle = null) + { + if ($scrollingStyle === null) { + $scrollingStyle = self::$defaultScrollingStyle; + } + + switch (strtolower(gettype($scrollingStyle))) { + case 'object': + if (!$scrollingStyle instanceof ScrollingStyleInterface) { + throw new Exception\InvalidArgumentException( + 'Scrolling style must implement Zend\Paginator\ScrollingStyle\ScrollingStyleInterface' + ); + } + + return $scrollingStyle; + + case 'string': + return self::getScrollingStylePluginManager()->get($scrollingStyle); + + case 'null': + // Fall through to default case + + default: + throw new Exception\InvalidArgumentException( + 'Scrolling style must be a class ' . + 'name or object implementing Zend\Paginator\ScrollingStyle\ScrollingStyleInterface' + ); + } + } +} diff --git a/src/ScrollingStyle/All.php b/src/ScrollingStyle/All.php new file mode 100644 index 0000000..5651748 --- /dev/null +++ b/src/ScrollingStyle/All.php @@ -0,0 +1,36 @@ +getPagesInRange(1, $paginator->count()); + } +} diff --git a/src/ScrollingStyle/Elastic.php b/src/ScrollingStyle/Elastic.php new file mode 100644 index 0000000..59bf15b --- /dev/null +++ b/src/ScrollingStyle/Elastic.php @@ -0,0 +1,49 @@ +getPageRange(); + $pageNumber = $paginator->getCurrentPageNumber(); + + $originalPageRange = $pageRange; + $pageRange = $pageRange * 2 - 1; + + if ($originalPageRange + $pageNumber - 1 < $pageRange) { + $pageRange = $originalPageRange + $pageNumber - 1; + } elseif ($originalPageRange + $pageNumber - 1 > count($paginator)) { + $pageRange = $originalPageRange + count($paginator) - $pageNumber; + } + + return parent::getPages($paginator, $pageRange); + } +} diff --git a/src/ScrollingStyle/Jumping.php b/src/ScrollingStyle/Jumping.php new file mode 100644 index 0000000..7c290be --- /dev/null +++ b/src/ScrollingStyle/Jumping.php @@ -0,0 +1,49 @@ +getPageRange(); + $pageNumber = $paginator->getCurrentPageNumber(); + + $delta = $pageNumber % $pageRange; + + if ($delta == 0) { + $delta = $pageRange; + } + + $offset = $pageNumber - $delta; + $lowerBound = $offset + 1; + $upperBound = $offset + $pageRange; + + return $paginator->getPagesInRange($lowerBound, $upperBound); + } +} diff --git a/src/ScrollingStyle/ScrollingStyleInterface.php b/src/ScrollingStyle/ScrollingStyleInterface.php new file mode 100644 index 0000000..4e84448 --- /dev/null +++ b/src/ScrollingStyle/ScrollingStyleInterface.php @@ -0,0 +1,29 @@ +getPageRange(); + } + + $pageNumber = $paginator->getCurrentPageNumber(); + $pageCount = count($paginator); + + if ($pageRange > $pageCount) { + $pageRange = $pageCount; + } + + $delta = ceil($pageRange / 2); + + if ($pageNumber - $delta > $pageCount - $pageRange) { + $lowerBound = $pageCount - $pageRange + 1; + $upperBound = $pageCount; + } else { + if ($pageNumber - $delta < 0) { + $delta = $pageNumber; + } + + $offset = $pageNumber - $delta; + $lowerBound = $offset + 1; + $upperBound = $offset + $pageRange; + } + + return $paginator->getPagesInRange($lowerBound, $upperBound); + } +} diff --git a/src/ScrollingStylePluginManager.php b/src/ScrollingStylePluginManager.php new file mode 100644 index 0000000..18a4e0f --- /dev/null +++ b/src/ScrollingStylePluginManager.php @@ -0,0 +1,62 @@ + 'Zend\Paginator\ScrollingStyle\All', + 'elastic' => 'Zend\Paginator\ScrollingStyle\Elastic', + 'jumping' => 'Zend\Paginator\ScrollingStyle\Jumping', + 'sliding' => 'Zend\Paginator\ScrollingStyle\Sliding', + ); + + /** + * Validate the plugin + * + * Checks that the adapter loaded is an instance of ScrollingStyle\ScrollingStyleInterface. + * + * @param mixed $plugin + * @return void + * @throws Exception\InvalidArgumentException if invalid + */ + public function validatePlugin($plugin) + { + if ($plugin instanceof ScrollingStyle\ScrollingStyleInterface) { + // we're okay + return; + } + + throw new Exception\InvalidArgumentException(sprintf( + 'Plugin of type %s is invalid; must implement %s\ScrollingStyle\ScrollingStyleInterface', + (is_object($plugin) ? get_class($plugin) : gettype($plugin)), + __NAMESPACE__ + )); + } +} + diff --git a/src/SerializableLimitIterator.php b/src/SerializableLimitIterator.php new file mode 100644 index 0000000..f127616 --- /dev/null +++ b/src/SerializableLimitIterator.php @@ -0,0 +1,134 @@ +offset = $offset; + $this->count = $count; + } + + /** + * @return string representation of the instance + */ + public function serialize() + { + return serialize(array( + 'it' => $this->getInnerIterator(), + 'offset' => $this->offset, + 'count' => $this->count, + 'pos' => $this->getPosition(), + )); + } + + /** + * @param string $data representation of the instance + * @return void + */ + public function unserialize($data) + { + $dataArr = unserialize($data); + $this->__construct($dataArr['it'], $dataArr['offset'], $dataArr['count']); + $this->seek($dataArr['pos']+$dataArr['offset']); + } + + /** + * Returns value of the Iterator + * + * @param int $offset + * @return mixed + */ + public function offsetGet($offset) + { + $currentOffset = $this->key(); + $this->seek($offset); + $current = $this->current(); + $this->seek($currentOffset); + return $current; + } + + /** + * Does nothing + * Required by the ArrayAccess implementation + * + * @param int $offset + * @param mixed $value + */ + public function offsetSet($offset, $value) + { + } + + /** + * Determine if a value of Iterator is set and is not NULL + * + * @param int $offset + * @return bool + */ + public function offsetExists($offset) + { + if ($offset > 0 && $offset < $this->count) { + try { + $currentOffset = $this->key(); + $this->seek($offset); + $current = $this->current(); + $this->seek($currentOffset); + return null !== $current; + } catch (\OutOfBoundsException $e) { + // reset position in case of exception is assigned null + $this->seek($currentOffset); + return false; + } + } + return false; + } + + /** + * Does nothing + * Required by the ArrayAccess implementation + * + * @param int $offset + */ + public function offsetUnset($offset) + { + } +} diff --git a/test/Adapter/ArrayTest.php b/test/Adapter/ArrayTest.php new file mode 100644 index 0000000..05edeeb --- /dev/null +++ b/test/Adapter/ArrayTest.php @@ -0,0 +1,74 @@ +adapter = new Adapter\ArrayAdapter(range(1, 101)); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown () + { + $this->adapter = null; + parent::tearDown(); + } + + public function testGetsItemsAtOffsetZero() + { + $expected = range(1, 10); + $actual = $this->adapter->getItems(0, 10); + $this->assertEquals($expected, $actual); + } + + public function testGetsItemsAtOffsetTen() + { + $expected = range(11, 20); + $actual = $this->adapter->getItems(10, 10); + $this->assertEquals($expected, $actual); + } + + public function testReturnsCorrectCount() + { + $this->assertEquals(101, $this->adapter->count()); + } + + + /** + * @group ZF-4151 + */ + public function testEmptySet() + { + $this->adapter = new Adapter\ArrayAdapter(array()); + $actual = $this->adapter->getItems(0, 10); + $this->assertEquals(array(), $actual); + } +} diff --git a/test/Adapter/DbSelectTest.php b/test/Adapter/DbSelectTest.php new file mode 100644 index 0000000..7e63fb1 --- /dev/null +++ b/test/Adapter/DbSelectTest.php @@ -0,0 +1,69 @@ +getMock('Zend\Db\Adapter\Driver\StatementInterface'); + $mockResult = $this->getMock('Zend\Db\Adapter\Driver\ResultInterface'); + + $mockDriver = $this->getMock('Zend\Db\Adapter\Driver\DriverInterface'); + $mockDriver->expects($this->any())->method('createStatement')->will($this->returnValue($mockStatement)); + $mockStatement->expects($this->any())->method('execute')->will($this->returnValue($mockResult)); + $mockPlatform = $this->getMock('Zend\Db\Adapter\Platform\PlatformInterface'); + $mockPlatform->expects($this->any())->method('getName')->will($this->returnValue('platform')); + $mockAdapter = $this->getMockForAbstractClass( + 'Zend\Db\Adapter\Adapter', + array($mockDriver, $mockPlatform) + ); + + $this->mockSelect = $this->getMock('Zend\Db\Sql\Select'); + $this->mockResult = $mockResult; + $this->dbSelect = new DbSelect($this->mockSelect, $mockAdapter); + } + + public function testGetItems() + { + $this->mockSelect->expects($this->once())->method('limit')->with($this->equalTo(10)); + $this->mockSelect->expects($this->once())->method('offset')->with($this->equalTo(2)); + $items = $this->dbSelect->getItems(2, 10); + $this->assertInstanceOf('Zend\Db\ResultSet\ResultSet', $items); + } + + public function testCount() + { + $this->mockSelect->expects($this->once())->method('columns')->with($this->equalTo(array('c' => new Expression('COUNT(1)')))); + $this->mockResult->expects($this->any())->method('current')->will($this->returnValue(array('c' => 5))); + $count = $this->dbSelect->count(); + $this->assertEquals(5, $count); + } +} diff --git a/test/Adapter/IteratorTest.php b/test/Adapter/IteratorTest.php new file mode 100644 index 0000000..ec81be4 --- /dev/null +++ b/test/Adapter/IteratorTest.php @@ -0,0 +1,117 @@ +adapter = new Adapter\Iterator($iterator); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown () + { + $this->adapter = null; + parent::tearDown(); + } + + public function testGetsItemsAtOffsetZero() + { + $actual = $this->adapter->getItems(0, 10); + $this->assertInstanceOf('LimitIterator', $actual); + + $i = 1; + foreach ($actual as $item) { + $this->assertEquals($i, $item); + $i++; + } + } + + public function testGetsItemsAtOffsetTen() + { + $actual = $this->adapter->getItems(10, 10); + $this->assertInstanceOf('LimitIterator', $actual); + + $i = 11; + foreach ($actual as $item) { + $this->assertEquals($i, $item); + $i++; + } + } + + public function testReturnsCorrectCount() + { + $this->assertEquals(101, $this->adapter->count()); + } + + public function testThrowsExceptionIfNotCountable() + { + $iterator = new \LimitIterator(new \ArrayIterator(range(1, 101))); + + $this->setExpectedException('Zend\Paginator\Adapter\Exception\InvalidArgumentException', 'Iterator must implement Countable'); + new Adapter\Iterator($iterator); + } + + /** + * @group ZF-4151 + */ + public function testDoesNotThrowOutOfBoundsExceptionIfIteratorIsEmpty() + { + $this->paginator = new Paginator(new Adapter\Iterator(new \ArrayIterator(array()))); + $items = $this->paginator->getCurrentItems(); + + foreach ($items as $item); + } + + /** + * @group ZF-8084 + */ + public function testGetItemsSerializable() + { + $items = $this->adapter->getItems(0, 1); + $innerIterator = $items->getInnerIterator(); + $items = unserialize(serialize($items)); + $this->assertTrue( ($items->getInnerIterator() == $innerIterator), 'getItems has to be serializable to use caching'); + } + + /** + * @group ZF-4151 + */ + public function testEmptySet() + { + $iterator = new \ArrayIterator(array()); + $this->adapter = new Adapter\Iterator($iterator); + $actual = $this->adapter->getItems(0, 10); + $this->assertEquals(array(), $actual); + } +} diff --git a/test/Adapter/NullTest.php b/test/Adapter/NullTest.php new file mode 100644 index 0000000..2af5664 --- /dev/null +++ b/test/Adapter/NullTest.php @@ -0,0 +1,100 @@ +adapter = new Adapter\Null(101); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->adapter = null; + parent::tearDown(); + } + + public function testGetsItems() + { + $actual = $this->adapter->getItems(0, 10); + $this->assertEquals(array_fill(0, 10, null), $actual); + } + + public function testReturnsCorrectCount() + { + $this->assertEquals(101, $this->adapter->count()); + } + + /** + * @group ZF-3873 + */ + public function testAdapterReturnsCorrectValues() + { + $paginator = new Paginator\Paginator(new Adapter\Null(2)); + $paginator->setCurrentPageNumber(1); + $paginator->setItemCountPerPage(5); + + $pages = $paginator->getPages(); + + $this->assertEquals(2, $pages->currentItemCount); + $this->assertEquals(2, $pages->lastItemNumber); + + $paginator = new Paginator\Paginator(new Adapter\Null(19)); + $paginator->setCurrentPageNumber(4); + $paginator->setItemCountPerPage(5); + + $pages = $paginator->getPages(); + + $this->assertEquals(4, $pages->currentItemCount); + $this->assertEquals(19, $pages->lastItemNumber); + } + + /** + * @group ZF-4151 + */ + public function testEmptySet() + { + $this->adapter = new Adapter\Null(0); + $actual = $this->adapter->getItems(0, 10); + $this->assertEquals(array(), $actual); + } + + /** + * Verify that the fix for ZF-4151 doesn't create an OBO error + */ + public function testSetOfOne() + { + $this->adapter = new Adapter\Null(1); + $actual = $this->adapter->getItems(0, 10); + $this->assertEquals(array_fill(0, 1, null), $actual); + } +} diff --git a/test/PaginatorTest.php b/test/PaginatorTest.php new file mode 100644 index 0000000..23a724b --- /dev/null +++ b/test/PaginatorTest.php @@ -0,0 +1,806 @@ +select = new Sql\Select; + $this->select->from('test'); + + $this->testCollection = range(1, 101); + $this->paginator = new Paginator\Paginator(new Paginator\Adapter\ArrayAdapter($this->testCollection)); + + $this->config = Config\Factory::fromFile(__DIR__ . '/_files/config.xml', true); + + $this->cache = CacheFactory::adapterFactory('memory', array('memory_limit' => 0)); + Paginator\Paginator::setCache($this->cache); + + $this->_restorePaginatorDefaults(); + } + + protected function tearDown() + { + $this->testCollection = null; + $this->paginator = null; + } + + protected function _getTmpDir() + { + $tmpDir = rtrim(sys_get_temp_dir(), '/\\') . DIRECTORY_SEPARATOR . 'zend_paginator'; + if (!is_dir($tmpDir)) { + mkdir($tmpDir); + } + $this->cacheDir = $tmpDir; + return $tmpDir; + } + + protected function _rmDirRecursive($path) + { + $dir = new \DirectoryIterator($path); + foreach ($dir as $file) { + if (!$file->isDir()) { + unlink($file->getPathname()); + } elseif (!in_array($file->getFilename(), array('.', '..'))) { + $this->_rmDirRecursive($file->getPathname()); + } + } + unset($file, $dir); // required on windows to remove file handle + if (!rmdir($path)) { + throw new Exception\RuntimeException('Unable to remove temporary directory ' . $path + . '; perhaps it has a nested structure?'); + } + } + + protected function _restorePaginatorDefaults() + { + $this->paginator->setItemCountPerPage(10); + $this->paginator->setCurrentPageNumber(1); + $this->paginator->setPageRange(10); + $this->paginator->setView(); + + Paginator\Paginator::setDefaultScrollingStyle(); + Helper\PaginationControl::setDefaultViewPartial(null); + + Paginator\Paginator::setGlobalConfig($this->config->default); + + Paginator\Paginator::setScrollingStylePluginManager(new Paginator\ScrollingStylePluginManager()); + + $this->paginator->setCacheEnabled(true); + } + + public function testGetsAndSetsDefaultScrollingStyle() + { + $this->assertEquals(Paginator\Paginator::getDefaultScrollingStyle(), 'Sliding'); + Paginator\Paginator::setDefaultScrollingStyle('Scrolling'); + $this->assertEquals(Paginator\Paginator::getDefaultScrollingStyle(), 'Scrolling'); + Paginator\Paginator::setDefaultScrollingStyle('Sliding'); + } + + public function testHasCorrectCountAfterInit() + { + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); + $this->assertEquals(11, $paginator->count()); + } + + public function testHasCorrectCountOfAllItemsAfterInit() + { + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); + $this->assertEquals(101, $paginator->getTotalItemCount()); + } + + public function testLoadsFromConfig() + { + Paginator\Paginator::setGlobalConfig($this->config->testing); + $this->assertEquals('Scrolling', Paginator\Paginator::getDefaultScrollingStyle()); + + $plugins = Paginator\Paginator::getScrollingStylePluginManager(); + $this->assertInstanceOf('ZendTest\Paginator\TestAsset\ScrollingStylePluginManager', $plugins); + + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); + $this->assertEquals(3, $paginator->getItemCountPerPage()); + $this->assertEquals(7, $paginator->getPageRange()); + } + + public function testGetsPagesForPageOne() + { + $expected = new stdClass(); + $expected->pageCount = 11; + $expected->itemCountPerPage = 10; + $expected->first = 1; + $expected->current = 1; + $expected->last = 11; + $expected->next = 2; + $expected->pagesInRange = array_combine(range(1, 10), range(1, 10)); + $expected->firstPageInRange = 1; + $expected->lastPageInRange = 10; + $expected->currentItemCount = 10; + $expected->totalItemCount = 101; + $expected->firstItemNumber = 1; + $expected->lastItemNumber = 10; + + $actual = $this->paginator->getPages(); + + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesForPageTwo() + { + $expected = new stdClass(); + $expected->pageCount = 11; + $expected->itemCountPerPage = 10; + $expected->first = 1; + $expected->current = 2; + $expected->last = 11; + $expected->previous = 1; + $expected->next = 3; + $expected->pagesInRange = array_combine(range(1, 10), range(1, 10)); + $expected->firstPageInRange = 1; + $expected->lastPageInRange = 10; + $expected->currentItemCount = 10; + $expected->totalItemCount = 101; + $expected->firstItemNumber = 11; + $expected->lastItemNumber = 20; + + $this->paginator->setCurrentPageNumber(2); + $actual = $this->paginator->getPages(); + + $this->assertEquals($expected, $actual); + } + + public function testRendersWithoutPartial() + { + $this->paginator->setView(new View\Renderer\PhpRenderer()); + $string = @$this->paginator->__toString(); + $this->assertEquals('', $string); + } + + public function testRendersWithPartial() + { + $view = new View\Renderer\PhpRenderer(); + $view->resolver()->addPath(__DIR__ . '/_files/scripts'); + + Helper\PaginationControl::setDefaultViewPartial('partial.phtml'); + + $this->paginator->setView($view); + + $string = $this->paginator->__toString(); + $this->assertEquals('partial rendered successfully', $string); + } + + public function testGetsPageCount() + { + $this->assertEquals(11, $this->paginator->count()); + } + + public function testGetsAndSetsItemCountPerPage() + { + Paginator\Paginator::setGlobalConfig(new Config\Config(array())); + $this->paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); + $this->assertEquals(10, $this->paginator->getItemCountPerPage()); + $this->paginator->setItemCountPerPage(15); + $this->assertEquals(15, $this->paginator->getItemCountPerPage()); + $this->paginator->setItemCountPerPage(0); + $this->assertEquals(101, $this->paginator->getItemCountPerPage()); + $this->paginator->setItemCountPerPage(10); + } + + /** + * @group ZF-5376 + */ + public function testGetsAndSetsItemCounterPerPageOfNegativeOne() + { + Paginator\Paginator::setGlobalConfig(new Config\Config(array())); + $this->paginator = new Paginator\Paginator(new Paginator\Adapter\ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(-1); + $this->assertEquals(101, $this->paginator->getItemCountPerPage()); + $this->paginator->setItemCountPerPage(10); + } + + /** + * @group ZF-5376 + */ + public function testGetsAndSetsItemCounterPerPageOfZero() + { + Paginator\Paginator::setGlobalConfig(new Config\Config(array())); + $this->paginator = new Paginator\Paginator(new Paginator\Adapter\ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(0); + $this->assertEquals(101, $this->paginator->getItemCountPerPage()); + $this->paginator->setItemCountPerPage(10); + } + + /** + * @group ZF-5376 + */ + public function testGetsAndSetsItemCounterPerPageOfNull() + { + Paginator\Paginator::setGlobalConfig(new Config\Config(array())); + $this->paginator = new Paginator\Paginator(new Paginator\Adapter\ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(); + $this->assertEquals(101, $this->paginator->getItemCountPerPage()); + $this->paginator->setItemCountPerPage(10); + } + + public function testGetsCurrentItemCount() + { + $this->paginator->setItemCountPerPage(10); + $this->paginator->setPageRange(10); + + $this->assertEquals(10, $this->paginator->getCurrentItemCount()); + + $this->paginator->setCurrentPageNumber(11); + + $this->assertEquals(1, $this->paginator->getCurrentItemCount()); + + $this->paginator->setCurrentPageNumber(1); + } + + public function testGetsCurrentItems() + { + $items = $this->paginator->getCurrentItems(); + $this->assertInstanceOf('ArrayIterator', $items); + + $count = 0; + + foreach ($items as $item) { + $count++; + } + + $this->assertEquals(10, $count); + } + + public function testGetsIterator() + { + $items = $this->paginator->getIterator(); + $this->assertInstanceOf('ArrayIterator', $items); + + $count = 0; + + foreach ($items as $item) { + $count++; + } + + $this->assertEquals(10, $count); + } + + public function testGetsAndSetsCurrentPageNumber() + { + $this->assertEquals(1, $this->paginator->getCurrentPageNumber()); + $this->paginator->setCurrentPageNumber(-1); + $this->assertEquals(1, $this->paginator->getCurrentPageNumber()); + $this->paginator->setCurrentPageNumber(11); + $this->assertEquals(11, $this->paginator->getCurrentPageNumber()); + $this->paginator->setCurrentPageNumber(111); + $this->assertEquals(11, $this->paginator->getCurrentPageNumber()); + $this->paginator->setCurrentPageNumber(1); + $this->assertEquals(1, $this->paginator->getCurrentPageNumber()); + } + + public function testGetsAbsoluteItemNumber() + { + $this->assertEquals(1, $this->paginator->getAbsoluteItemNumber(1)); + $this->assertEquals(11, $this->paginator->getAbsoluteItemNumber(1, 2)); + $this->assertEquals(24, $this->paginator->getAbsoluteItemNumber(4, 3)); + } + + public function testGetsItem() + { + $this->assertEquals(1, $this->paginator->getItem(1)); + $this->assertEquals(11, $this->paginator->getItem(1, 2)); + $this->assertEquals(24, $this->paginator->getItem(4, 3)); + } + + public function testThrowsExceptionWhenCollectionIsEmpty() + { + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(array())); + + $this->setExpectedException('Zend\Paginator\Exception\InvalidArgumentException', 'Page 1 does not exist'); + $paginator->getItem(1); + } + + public function testThrowsExceptionWhenRetrievingNonexistentItemFromLastPage() + { + $this->setExpectedException('Zend\Paginator\Exception\InvalidArgumentException', 'Page 11 does not contain item number 10'); + $this->paginator->getItem(10, 11); + } + + public function testNormalizesPageNumber() + { + $this->assertEquals(1, $this->paginator->normalizePageNumber(0)); + $this->assertEquals(1, $this->paginator->normalizePageNumber(1)); + $this->assertEquals(2, $this->paginator->normalizePageNumber(2)); + $this->assertEquals(5, $this->paginator->normalizePageNumber(5)); + $this->assertEquals(10, $this->paginator->normalizePageNumber(10)); + $this->assertEquals(11, $this->paginator->normalizePageNumber(11)); + $this->assertEquals(11, $this->paginator->normalizePageNumber(12)); + } + + public function testNormalizesItemNumber() + { + $this->assertEquals(1, $this->paginator->normalizeItemNumber(0)); + $this->assertEquals(1, $this->paginator->normalizeItemNumber(1)); + $this->assertEquals(2, $this->paginator->normalizeItemNumber(2)); + $this->assertEquals(5, $this->paginator->normalizeItemNumber(5)); + $this->assertEquals(9, $this->paginator->normalizeItemNumber(9)); + $this->assertEquals(10, $this->paginator->normalizeItemNumber(10)); + $this->assertEquals(10, $this->paginator->normalizeItemNumber(11)); + } + + /** + * @group ZF-8656 + */ + public function testNormalizesPageNumberWhenGivenAFloat() + { + $this->assertEquals(1, $this->paginator->normalizePageNumber(0.5)); + $this->assertEquals(1, $this->paginator->normalizePageNumber(1.99)); + $this->assertEquals(2, $this->paginator->normalizePageNumber(2.3)); + $this->assertEquals(5, $this->paginator->normalizePageNumber(5.1)); + $this->assertEquals(10, $this->paginator->normalizePageNumber(10.06)); + $this->assertEquals(11, $this->paginator->normalizePageNumber(11.5)); + $this->assertEquals(11, $this->paginator->normalizePageNumber(12.7889)); + } + + /** + * @group ZF-8656 + */ + public function testNormalizesItemNumberWhenGivenAFloat() + { + $this->assertEquals(1, $this->paginator->normalizeItemNumber(0.5)); + $this->assertEquals(1, $this->paginator->normalizeItemNumber(1.99)); + $this->assertEquals(2, $this->paginator->normalizeItemNumber(2.3)); + $this->assertEquals(5, $this->paginator->normalizeItemNumber(5.1)); + $this->assertEquals(9, $this->paginator->normalizeItemNumber(9.06)); + $this->assertEquals(10, $this->paginator->normalizeItemNumber(10.5)); + $this->assertEquals(10, $this->paginator->normalizeItemNumber(11.7889)); + } + + public function testGetsPagesInSubsetRange() + { + $actual = $this->paginator->getPagesInRange(3, 8); + $this->assertEquals(array_combine(range(3, 8), range(3, 8)), $actual); + } + + public function testGetsPagesInOutOfBoundsRange() + { + $actual = $this->paginator->getPagesInRange(-1, 12); + $this->assertEquals(array_combine(range(1, 11), range(1, 11)), $actual); + } + + public function testGetsItemsByPage() + { + $expected = new \ArrayIterator(range(1, 10)); + + $page1 = $this->paginator->getItemsByPage(1); + + $this->assertEquals($page1, $expected); + $this->assertEquals($page1, $this->paginator->getItemsByPage(1)); + } + + public function testGetsItemCount() + { + $this->assertEquals(101, $this->paginator->getItemCount(range(1, 101))); + + $limitIterator = new \LimitIterator(new \ArrayIterator(range(1, 101))); + $this->assertEquals(101, $this->paginator->getItemCount($limitIterator)); + } + + public function testGeneratesViewIfNonexistent() + { + $this->assertInstanceOf('Zend\\View\\Renderer\\RendererInterface', $this->paginator->getView()); + } + + public function testGetsAndSetsView() + { + $this->paginator->setView(new View\Renderer\PhpRenderer()); + $this->assertInstanceOf('Zend\\View\\Renderer\\RendererInterface', $this->paginator->getView()); + } + + public function testRenders() + { + $this->setExpectedException('Zend\\View\\Exception\\ExceptionInterface', 'view partial'); + $this->paginator->render(new View\Renderer\PhpRenderer()); + } + + public function testGetsAndSetsPageRange() + { + $this->assertEquals(10, $this->paginator->getPageRange()); + $this->paginator->setPageRange(15); + $this->assertEquals(15, $this->paginator->getPageRange()); + } + + /** + * @group ZF-3720 + */ + public function testGivesCorrectItemCount() + { + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); + $paginator->setCurrentPageNumber(5) + ->setItemCountPerPage(5); + $expected = new \ArrayIterator(range(21, 25)); + + $this->assertEquals($expected, $paginator->getCurrentItems()); + } + + /** + * @group ZF-3737 + */ + public function testKeepsCurrentPageNumberAfterItemCountPerPageSet() + { + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(array('item1', 'item2'))); + $paginator->setCurrentPageNumber(2) + ->setItemCountPerPage(1); + + $items = $paginator->getCurrentItems(); + + $this->assertEquals('item2', $items[0]); + } + + /** + * @group ZF-4193 + */ + public function testCastsIntegerValuesToInteger() + { + // Current page number + $this->paginator->setCurrentPageNumber(3.3); + $this->assertTrue($this->paginator->getCurrentPageNumber() == 3); + + // Item count per page + $this->paginator->setItemCountPerPage(3.3); + $this->assertTrue($this->paginator->getItemCountPerPage() == 3); + + // Page range + $this->paginator->setPageRange(3.3); + $this->assertTrue($this->paginator->getPageRange() == 3); + } + + /** + * @group ZF-4207 + */ + public function testAcceptsTraversableInstanceFromAdapter() + { + $paginator = new Paginator\Paginator(new TestAsset\TestAdapter()); + $this->assertInstanceOf('ArrayObject', $paginator->getCurrentItems()); + } + + public function testCachedItem() + { + $this->paginator->setCurrentPageNumber(1)->getCurrentItems(); + $this->paginator->setCurrentPageNumber(2)->getCurrentItems(); + $this->paginator->setCurrentPageNumber(3)->getCurrentItems(); + + $pageItems = $this->paginator->getPageItemCache(); + $expected = array( + 1 => new \ArrayIterator(range(1, 10)), + 2 => new \ArrayIterator(range(11, 20)), + 3 => new \ArrayIterator(range(21, 30)) + ); + $this->assertEquals($expected, $pageItems); + } + + public function testClearPageItemCache() + { + $this->paginator->setCurrentPageNumber(1)->getCurrentItems(); + $this->paginator->setCurrentPageNumber(2)->getCurrentItems(); + $this->paginator->setCurrentPageNumber(3)->getCurrentItems(); + + // clear only page 2 items + $this->paginator->clearPageItemCache(2); + $pageItems = $this->paginator->getPageItemCache(); + $expected = array( + 1 => new \ArrayIterator(range(1, 10)), + 3 => new \ArrayIterator(range(21, 30)) + ); + $this->assertEquals($expected, $pageItems); + + // clear all + $this->paginator->clearPageItemCache(); + $pageItems = $this->paginator->getPageItemCache(); + $this->assertEquals(array(), $pageItems); + } + + public function testWithCacheDisabled() + { + $this->paginator->setCacheEnabled(false); + $this->paginator->setCurrentPageNumber(1)->getCurrentItems(); + + $cachedPageItems = $this->paginator->getPageItemCache(); + $expected = new \ArrayIterator(range(1, 10)); + + $this->assertEquals(array(), $cachedPageItems); + + $pageItems = $this->paginator->getCurrentItems(); + + $this->assertEquals($expected, $pageItems); + } + + public function testCacheDoesNotDisturbResultsWhenChangingParam() + { + $this->paginator->setCurrentPageNumber(1)->getCurrentItems(); + $pageItems = $this->paginator->setItemCountPerPage(5)->getCurrentItems(); + + $expected = new \ArrayIterator(range(1, 5)); + $this->assertEquals($expected, $pageItems); + + $pageItems = $this->paginator->getItemsByPage(2); + $expected = new \ArrayIterator(range(6, 10)); + $this->assertEquals($expected, $pageItems); + + // change the inside Paginator scale + $pageItems = $this->paginator->setItemCountPerPage(8)->setCurrentPageNumber(3)->getCurrentItems(); + + $pageItems = $this->paginator->getPageItemCache(); + $expected = /*array(3 => */ new \ArrayIterator(range(17, 24)) /*) */; + $this->assertEquals($expected, $pageItems[3]); + + // get back to already cached data + $this->paginator->setItemCountPerPage(5); + $pageItems = $this->paginator->getPageItemCache(); + $expected =array(1 => new \ArrayIterator(range(1, 5)), + 2 => new \ArrayIterator(range(6, 10))); + $this->assertEquals($expected[1], $pageItems[1]); + $this->assertEquals($expected[2], $pageItems[2]); + } + + public function testToJson() + { + $this->paginator->setCurrentPageNumber(1); + + $json = $this->paginator->toJson(); + + $expected = '"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10'; + + $this->assertContains($expected, $json); + } + + // ZF-5519 + public function testFilter() + { + $filter = new Filter\Callback(array($this, 'filterCallback')); + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 101))); + $paginator->setFilter($filter); + + $page = $paginator->getCurrentItems(); + + $this->assertEquals(new \ArrayIterator(range(10, 100, 10)), $page); + } + + public function filterCallback($value) + { + $data = array(); + + foreach ($value as $number) { + $data[] = ($number * 10); + } + + return $data; + } + + /** + * @group ZF-5785 + */ + public function testGetSetDefaultItemCountPerPage() + { + Paginator\Paginator::setGlobalConfig(new Config\Config(array())); + + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 10))); + $this->assertEquals(10, $paginator->getItemCountPerPage()); + + Paginator\Paginator::setDefaultItemCountPerPage(20); + $this->assertEquals(20, Paginator\Paginator::getDefaultItemCountPerPage()); + + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 10))); + $this->assertEquals(20, $paginator->getItemCountPerPage()); + + $this->_restorePaginatorDefaults(); + } + + /** + * @group ZF-7207 + */ + public function testItemCountPerPageByDefault() + { + $paginator = new Paginator\Paginator(new Adapter\ArrayAdapter(range(1, 20))); + $this->assertEquals(2, $paginator->count()); + } + + /** + * @group ZF-5427 + */ + public function testNegativeItemNumbers() + { + $this->assertEquals(10, $this->paginator->getItem(-1, 1)); + $this->assertEquals(9, $this->paginator->getItem(-2, 1)); + $this->assertEquals(101, $this->paginator->getItem(-1, -1)); + } + + /** + * @group ZF-7602 + */ + public function testAcceptAndHandlePaginatorAdapterAggregateDataInFactory() + { + $p = new Paginator\Paginator(new TestArrayAggregate()); + + $this->assertEquals(1, count($p)); + $this->assertInstanceOf('Zend\Paginator\Adapter\ArrayAdapter', $p->getAdapter()); + $this->assertEquals(4, count($p->getAdapter())); + } + + /** + * @group ZF-7602 + */ + public function testAcceptAndHandlePaginatorAdapterAggregateInConstructor() + { + $p = new Paginator\Paginator(new TestArrayAggregate()); + + $this->assertEquals(1, count($p)); + $this->assertInstanceOf('Zend\Paginator\Adapter\ArrayAdapter', $p->getAdapter()); + $this->assertEquals(4, count($p->getAdapter())); + } + + /** + * @group ZF-7602 + */ + public function testInvalidDataInConstructor_ThrowsException() + { + $this->setExpectedException('Zend\Paginator\Exception\ExceptionInterface'); + + new Paginator\Paginator(array()); + } + + /** + * @group ZF-9396 + */ + public function testArrayAccessInClassSerializableLimitIterator() + { + $iterator = new \ArrayIterator(array('zf9396', 'foo', null)); + $paginator = new Paginator\Paginator(new Adapter\Iterator($iterator)); + + $this->assertEquals('zf9396', $paginator->getItem(1)); + + $items = $paginator->getAdapter() + ->getItems(0, 10); + + $this->assertEquals('foo', $items[1]); + $this->assertEquals(0, $items->key()); + $this->assertFalse(isset($items[2])); + $this->assertTrue(isset($items[1])); + $this->assertFalse(isset($items[3])); + } + + public function testSetGlobalConfigThrowsInvalidArgumentException() + { + $this->setExpectedException( + 'Zend\Paginator\Exception\InvalidArgumentException', + 'setGlobalConfig expects an array or Traversable' + ); + + $this->paginator->setGlobalConfig('not array'); + } + + public function testSetScrollingStylePluginManagerWithStringThrowsInvalidArgumentException() + { + $this->setExpectedException( + 'Zend\Paginator\Exception\InvalidArgumentException', + 'Unable to locate scrolling style plugin manager with class "invalid adapter"; class not found' + ); + + $this->paginator->setScrollingStylePluginManager('invalid adapter'); + } + + public function testSetScrollingStylePluginManagerWithAdapterThrowsInvalidArgumentException() + { + $this->setExpectedException( + 'Zend\Paginator\Exception\InvalidArgumentException', + 'Pagination scrolling-style manager must extend ScrollingStylePluginManager; received "stdClass"' + ); + + $this->paginator->setScrollingStylePluginManager( + new stdClass() + ); + } + + public function testLoadScrollingStyleWithDigitThrowsInvalidArgumentException() + { + $adapter = new TestAsset\TestAdapter; + $paginator = new Paginator\Paginator($adapter); + $reflection = new ReflectionMethod($paginator, '_loadScrollingStyle'); + $reflection->setAccessible(true); + + $this->setExpectedException( + 'Zend\Paginator\Exception\InvalidArgumentException', + 'Scrolling style must be a class ' . + 'name or object implementing Zend\Paginator\ScrollingStyle\ScrollingStyleInterface' + ); + + $reflection->invoke($paginator, 12345); + } + + public function testLoadScrollingStyleWithObjectThrowsInvalidArgumentException() + { + $adapter = new TestAsset\TestAdapter; + $paginator = new Paginator\Paginator($adapter); + $reflection = new ReflectionMethod($paginator, '_loadScrollingStyle'); + $reflection->setAccessible(true); + + $this->setExpectedException( + 'Zend\Paginator\Exception\InvalidArgumentException', + 'Scrolling style must implement Zend\Paginator\ScrollingStyle\ScrollingStyleInterface' + ); + + $reflection->invoke($paginator, new stdClass()); + } + + public function testGetCacheId() + { + $adapter = new TestAsset\TestAdapter; + $paginator = new Paginator\Paginator($adapter); + $reflectionGetCacheId = new ReflectionMethod($paginator, '_getCacheId'); + $reflectionGetCacheId->setAccessible(true); + $outputGetCacheId = $reflectionGetCacheId->invoke($paginator, null); + + $reflectionGetCacheInternalId = new ReflectionMethod($paginator, '_getCacheInternalId'); + $reflectionGetCacheInternalId->setAccessible(true); + $outputGetCacheInternalId = $reflectionGetCacheInternalId->invoke($paginator); + + $this->assertEquals($outputGetCacheId, 'Zend_Paginator_1_' . $outputGetCacheInternalId); + } + +} + +class TestArrayAggregate implements Paginator\AdapterAggregateInterface +{ + public function getPaginatorAdapter() + { + return new Adapter\ArrayAdapter(array(1, 2, 3, 4)); + } +} diff --git a/test/ScrollingStyle/AllTest.php b/test/ScrollingStyle/AllTest.php new file mode 100644 index 0000000..bcbce56 --- /dev/null +++ b/test/ScrollingStyle/AllTest.php @@ -0,0 +1,99 @@ +scrollingStyle = new \Zend\Paginator\ScrollingStyle\All(); + $this->paginator = new Paginator(new ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(10); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown () + { + $this->scrollingStyle = null; + $this->paginator = null; + parent::tearDown(); + } + + public function testGetsPages() + { + $expected = array_combine(range(1, 11), range(1, 11)); + $pages = $this->scrollingStyle->getPages($this->paginator); + $this->assertEquals($expected, $pages); + } + + public function testGetsNextAndPreviousPageForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $pages = $this->paginator->getPages('All'); + + $this->assertEquals(2, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $pages = $this->paginator->getPages('All'); + $this->assertEquals(1, $pages->previous); + $this->assertEquals(3, $pages->next); + } + + public function testGetsNextAndPreviousPageForMiddlePage() + { + $this->paginator->setCurrentPageNumber(6); + $pages = $this->paginator->getPages('All'); + $this->assertEquals(5, $pages->previous); + $this->assertEquals(7, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondLastPage() + { + $this->paginator->setCurrentPageNumber(10); + $pages = $this->paginator->getPages('All'); + $this->assertEquals(9, $pages->previous); + $this->assertEquals(11, $pages->next); + } + + public function testGetsNextAndPreviousPageForLastPage() + { + $this->paginator->setCurrentPageNumber(11); + $pages = $this->paginator->getPages('All'); + $this->assertEquals(10, $pages->previous); + } +} diff --git a/test/ScrollingStyle/ElasticTest.php b/test/ScrollingStyle/ElasticTest.php new file mode 100644 index 0000000..b0d12a6 --- /dev/null +++ b/test/ScrollingStyle/ElasticTest.php @@ -0,0 +1,148 @@ +scrollingStyle = new \Zend\Paginator\ScrollingStyle\Elastic(); + $this->paginator = new Paginator(new ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(5); + $this->paginator->setPageRange(5); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->scrollingStyle = null; + $this->paginator = null; + parent::tearDown(); + } + + public function testGetsPagesInRangeForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $actual = $this->scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(1, 5), range(1, 5)); + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesInRangeForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $actual = $this->scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(1, 6), range(1, 6)); + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesInRangeForTenthPage() + { + $this->paginator->setCurrentPageNumber(10); + $actual = $this->scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(6, 14), range(6, 14)); + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesInRangeForLastPage() + { + $this->paginator->setCurrentPageNumber(21); + $actual = $this->scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(17, 21), range(17, 21)); + $this->assertEquals($expected, $actual); + } + + public function testGetsNextAndPreviousPageForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $pages = $this->paginator->getPages('Elastic'); + + $this->assertEquals(2, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(1, $pages->previous); + $this->assertEquals(3, $pages->next); + } + + public function testGetsNextAndPreviousPageForMiddlePage() + { + $this->paginator->setCurrentPageNumber(10); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(9, $pages->previous); + $this->assertEquals(11, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondLastPage() + { + $this->paginator->setCurrentPageNumber(20); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(19, $pages->previous); + $this->assertEquals(21, $pages->next); + } + + public function testGetsNextAndPreviousPageForLastPage() + { + $this->paginator->setCurrentPageNumber(21); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(20, $pages->previous); + } + + public function testNoPagesOnLastPageEqualsPageRange() + { + $this->paginator->setPageRange(3); + $this->paginator->setCurrentPageNumber(21); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(3, count($pages->pagesInRange)); + } + + public function testNoPagesOnSecondLastPageEqualsPageRangeMinOne() + { + $this->paginator->setPageRange(3); + $this->paginator->setCurrentPageNumber(20); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(4, count($pages->pagesInRange)); + } + + public function testNoPagesBeforeSecondLastPageEqualsPageRangeMinTwo() + { + $this->paginator->setPageRange(3); + $this->paginator->setCurrentPageNumber(19); + $pages = $this->paginator->getPages('Elastic'); + $this->assertEquals(5, count($pages->pagesInRange)); + } +} diff --git a/test/ScrollingStyle/JumpingTest.php b/test/ScrollingStyle/JumpingTest.php new file mode 100644 index 0000000..ba00272 --- /dev/null +++ b/test/ScrollingStyle/JumpingTest.php @@ -0,0 +1,124 @@ +scrollingStyle = new \Zend\Paginator\ScrollingStyle\Jumping(); + $this->paginator = new Paginator(new ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(10); + $this->paginator->setPageRange(10); + $this->expectedRange = array_combine(range(1, 10), range(1, 10)); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->scrollingStyle = null; + $this->paginator = null; + parent::tearDown(); + } + + public function testGetsPagesInRangeForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $actual = $this->scrollingStyle->getPages($this->paginator); + $this->assertEquals($this->expectedRange, $actual); + } + + public function testGetsPagesInRangeForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $actual = $this->scrollingStyle->getPages($this->paginator); + $this->assertEquals($this->expectedRange, $actual); + } + + public function testGetsPagesInRangeForSecondLastPage() + { + $this->paginator->setCurrentPageNumber(10); + $actual = $this->scrollingStyle->getPages($this->paginator); + $this->assertEquals($this->expectedRange, $actual); + } + + public function testGetsPagesInRangeForLastPage() + { + $this->paginator->setCurrentPageNumber(11); + $actual = $this->scrollingStyle->getPages($this->paginator); + $expected = array(11 => 11); + $this->assertEquals($expected, $actual); + } + + public function testGetsNextAndPreviousPageForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $pages = $this->paginator->getPages('Jumping'); + + $this->assertEquals(2, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $pages = $this->paginator->getPages('Jumping'); + $this->assertEquals(1, $pages->previous); + $this->assertEquals(3, $pages->next); + } + + public function testGetsNextAndPreviousPageForMiddlePage() + { + $this->paginator->setCurrentPageNumber(6); + $pages = $this->paginator->getPages('Jumping'); + $this->assertEquals(5, $pages->previous); + $this->assertEquals(7, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondLastPage() + { + $this->paginator->setCurrentPageNumber(10); + $pages = $this->paginator->getPages('Jumping'); + $this->assertEquals(9, $pages->previous); + $this->assertEquals(11, $pages->next); + } + + public function testGetsNextAndPreviousPageForLastPage() + { + $this->paginator->setCurrentPageNumber(11); + $pages = $this->paginator->getPages('Jumping'); + $this->assertEquals(10, $pages->previous); + } +} diff --git a/test/ScrollingStyle/SlidingTest.php b/test/ScrollingStyle/SlidingTest.php new file mode 100644 index 0000000..c90a31f --- /dev/null +++ b/test/ScrollingStyle/SlidingTest.php @@ -0,0 +1,131 @@ +_scrollingStyle = new \Zend\Paginator\ScrollingStyle\Sliding(); + $this->paginator = new Paginator(new ArrayAdapter(range(1, 101))); + $this->paginator->setItemCountPerPage(10); + $this->paginator->setPageRange(5); + } + /** + * Cleans up the environment after running a test. + */ + protected function tearDown() + { + $this->_scrollingStyle = null; + $this->paginator = null; + parent::tearDown(); + } + + public function testGetsPagesInRangeForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $actual = $this->_scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(1, 5), range(1, 5)); + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesInRangeForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $actual = $this->_scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(1, 5), range(1, 5)); + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesInRangeForFifthPage() + { + $this->paginator->setCurrentPageNumber(5); + $actual = $this->_scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(3, 7), range(3, 7)); + $this->assertEquals($expected, $actual); + } + + public function testGetsPagesInRangeForLastPage() + { + $this->paginator->setCurrentPageNumber(11); + $actual = $this->_scrollingStyle->getPages($this->paginator); + $expected = array_combine(range(7, 11), range(7, 11)); + $this->assertEquals($expected, $actual); + } + + public function testGetsNextAndPreviousPageForFirstPage() + { + $this->paginator->setCurrentPageNumber(1); + $pages = $this->paginator->getPages('Sliding'); + + $this->assertEquals(2, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondPage() + { + $this->paginator->setCurrentPageNumber(2); + $pages = $this->paginator->getPages('Sliding'); + $this->assertEquals(1, $pages->previous); + $this->assertEquals(3, $pages->next); + } + + public function testGetsNextAndPreviousPageForMiddlePage() + { + $this->paginator->setCurrentPageNumber(6); + $pages = $this->paginator->getPages('Sliding'); + $this->assertEquals(5, $pages->previous); + $this->assertEquals(7, $pages->next); + } + + public function testGetsNextAndPreviousPageForSecondLastPage() + { + $this->paginator->setCurrentPageNumber(10); + $pages = $this->paginator->getPages('Sliding'); + $this->assertEquals(9, $pages->previous); + $this->assertEquals(11, $pages->next); + } + + public function testGetsNextAndPreviousPageForLastPage() + { + $this->paginator->setCurrentPageNumber(11); + $pages = $this->paginator->getPages('Sliding'); + $this->assertEquals(10, $pages->previous); + } + + public function testAcceptsPageRangeLargerThanPageCount() + { + $this->paginator->setPageRange(100); + $pages = $this->paginator->getPages(); + $this->assertEquals(11, $pages->last); + } +} diff --git a/test/TestAsset/ScrollingStylePluginManager.php b/test/TestAsset/ScrollingStylePluginManager.php new file mode 100644 index 0000000..66229ea --- /dev/null +++ b/test/TestAsset/ScrollingStylePluginManager.php @@ -0,0 +1,22 @@ + + + + 10 + 10 + + + Scrolling + ZendTest\Paginator\TestAsset\ScrollingStylePluginManager + ZendTest\Paginator\TestAsset\AdapterPluginManager + 3 + 7 + + diff --git a/test/_files/scripts/partial.phtml b/test/_files/scripts/partial.phtml new file mode 100644 index 0000000..f53e81c --- /dev/null +++ b/test/_files/scripts/partial.phtml @@ -0,0 +1 @@ +partial rendered successfully \ No newline at end of file diff --git a/test/bootstrap.php b/test/bootstrap.php new file mode 100644 index 0000000..a0019f7 --- /dev/null +++ b/test/bootstrap.php @@ -0,0 +1,34 @@ +