3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Paginator
;
14 use IteratorAggregate
;
16 use Zend\Cache\Storage\IteratorInterface
as CacheIterator
;
17 use Zend\Cache\Storage\StorageInterface
as CacheStorage
;
18 use Zend\Db\ResultSet\AbstractResultSet
;
19 use Zend\Filter\FilterInterface
;
21 use Zend\Paginator\Adapter\AdapterInterface
;
22 use Zend\Paginator\ScrollingStyle\ScrollingStyleInterface
;
23 use Zend\Stdlib\ArrayUtils
;
26 class Paginator
implements Countable
, IteratorAggregate
30 * The cache tag prefix used to namespace Paginator results in the cache
33 const CACHE_TAG_PREFIX
= 'Zend_Paginator_';
36 * Adapter plugin manager
38 * @var AdapterPluginManager
40 protected static $adapters = null;
47 protected static $config = null;
50 * Default scrolling style
54 protected static $defaultScrollingStyle = 'Sliding';
57 * Default item count per page
61 protected static $defaultItemCountPerPage = 10;
64 * Scrolling style plugin manager
66 * @var ScrollingStylePluginManager
68 protected static $scrollingStyles = null;
75 protected static $cache;
78 * Enable or disable the cache by Zend\Paginator\Paginator instance
82 protected $cacheEnabled = true;
87 * @var AdapterInterface
89 protected $adapter = null;
92 * Number of items in the current page
96 protected $currentItemCount = null;
103 protected $currentItems = null;
106 * Current page number (starting from 1)
110 protected $currentPageNumber = 1;
115 * @var FilterInterface
117 protected $filter = null;
120 * Number of items per page
124 protected $itemCountPerPage = null;
131 protected $pageCount = null;
134 * Number of local pages (i.e., the number of discrete page numbers
135 * that will be displayed, including the current page number)
139 protected $pageRange = 10;
146 protected $pages = null;
149 * View instance used for self rendering
151 * @var \Zend\View\Renderer\RendererInterface
153 protected $view = null;
156 * Set a global config
158 * @param array|Traversable $config
159 * @throws Exception\InvalidArgumentException
161 public static function setGlobalConfig($config)
163 if ($config instanceof Traversable
) {
164 $config = ArrayUtils
::iteratorToArray($config);
166 if (!is_array($config)) {
167 throw new Exception\
InvalidArgumentException(__METHOD__
. ' expects an array or Traversable');
170 static::$config = $config;
172 if (isset($config['scrolling_style_plugins'])
173 && null !== ($adapters = $config['scrolling_style_plugins'])
175 static::setScrollingStylePluginManager($adapters);
178 $scrollingStyle = isset($config['scrolling_style']) ?
$config['scrolling_style'] : null;
180 if ($scrollingStyle != null) {
181 static::setDefaultScrollingStyle($scrollingStyle);
186 * Returns the default scrolling style.
190 public static function getDefaultScrollingStyle()
192 return static::$defaultScrollingStyle;
196 * Get the default item count per page
200 public static function getDefaultItemCountPerPage()
202 return static::$defaultItemCountPerPage;
206 * Set the default item count per page
210 public static function setDefaultItemCountPerPage($count)
212 static::$defaultItemCountPerPage = (int) $count;
216 * Sets a cache object
218 * @param CacheStorage $cache
220 public static function setCache(CacheStorage
$cache)
222 static::$cache = $cache;
226 * Sets the default scrolling style.
228 * @param string $scrollingStyle
230 public static function setDefaultScrollingStyle($scrollingStyle = 'Sliding')
232 static::$defaultScrollingStyle = $scrollingStyle;
235 public static function setScrollingStylePluginManager($scrollingAdapters)
237 if (is_string($scrollingAdapters)) {
238 if (!class_exists($scrollingAdapters)) {
239 throw new Exception\
InvalidArgumentException(sprintf(
240 'Unable to locate scrolling style plugin manager with class "%s"; class not found',
244 $scrollingAdapters = new $scrollingAdapters();
246 if (!$scrollingAdapters instanceof ScrollingStylePluginManager
) {
247 throw new Exception\
InvalidArgumentException(sprintf(
248 'Pagination scrolling-style manager must extend ScrollingStylePluginManager; received "%s"',
249 (is_object($scrollingAdapters) ?
get_class($scrollingAdapters) : gettype($scrollingAdapters))
252 static::$scrollingStyles = $scrollingAdapters;
256 * Returns the scrolling style manager. If it doesn't exist it's
259 * @return ScrollingStylePluginManager
261 public static function getScrollingStylePluginManager()
263 if (static::$scrollingStyles === null) {
264 static::$scrollingStyles = new ScrollingStylePluginManager();
267 return static::$scrollingStyles;
273 * @param AdapterInterface|AdapterAggregateInterface $adapter
274 * @throws Exception\InvalidArgumentException
276 public function __construct($adapter)
278 if ($adapter instanceof AdapterInterface
) {
279 $this->adapter
= $adapter;
280 } elseif ($adapter instanceof AdapterAggregateInterface
) {
281 $this->adapter
= $adapter->getPaginatorAdapter();
283 throw new Exception\
InvalidArgumentException(
284 'Zend\Paginator only accepts instances of the type ' .
285 'Zend\Paginator\Adapter\AdapterInterface or Zend\Paginator\AdapterAggregateInterface.'
289 $config = static::$config;
291 if (!empty($config)) {
292 $setupMethods = array('ItemCountPerPage', 'PageRange');
294 foreach ($setupMethods as $setupMethod) {
295 $key = strtolower($setupMethod);
296 $value = isset($config[$key]) ?
$config[$key] : null;
298 if ($value != null) {
299 $setupMethod = 'set' . $setupMethod;
300 $this->$setupMethod($value);
307 * Serializes the object as a string. Proxies to {@link render()}.
311 public function __toString()
314 $return = $this->render();
316 } catch (\Exception
$e) {
317 trigger_error($e->getMessage(), E_USER_WARNING
);
324 * Enables/Disables the cache for this instance
326 * @param bool $enable
329 public function setCacheEnabled($enable)
331 $this->cacheEnabled
= (bool) $enable;
336 * Returns the number of pages.
340 public function count()
342 if (!$this->pageCount
) {
343 $this->pageCount
= $this->_calculatePageCount();
346 return $this->pageCount
;
350 * Returns the total number of items available.
354 public function getTotalItemCount()
356 return count($this->getAdapter());
360 * Clear the page item cache.
362 * @param int $pageNumber
365 public function clearPageItemCache($pageNumber = null)
367 if (!$this->cacheEnabled()) {
371 if (null === $pageNumber) {
372 $prefixLength = strlen(self
::CACHE_TAG_PREFIX
);
373 $cacheIterator = static::$cache->getIterator();
374 $cacheIterator->setMode(CacheIterator
::CURRENT_AS_KEY
);
375 foreach ($cacheIterator as $key) {
376 $tags = static::$cache->getTags($key);
377 if ($tags && in_array($this->_getCacheInternalId(), $tags)) {
378 if (substr($key, 0, $prefixLength) == self
::CACHE_TAG_PREFIX
) {
379 static::$cache->removeItem($this->_getCacheId((int)substr($key, $prefixLength)));
384 $cleanId = $this->_getCacheId($pageNumber);
385 static::$cache->removeItem($cleanId);
391 * Returns the absolute item number for the specified item.
393 * @param int $relativeItemNumber Relative item number
394 * @param int $pageNumber Page number
397 public function getAbsoluteItemNumber($relativeItemNumber, $pageNumber = null)
399 $relativeItemNumber = $this->normalizeItemNumber($relativeItemNumber);
401 if ($pageNumber == null) {
402 $pageNumber = $this->getCurrentPageNumber();
405 $pageNumber = $this->normalizePageNumber($pageNumber);
407 return (($pageNumber - 1) * $this->getItemCountPerPage()) +
$relativeItemNumber;
411 * Returns the adapter.
413 * @return AdapterInterface
415 public function getAdapter()
417 return $this->adapter
;
421 * Returns the number of items for the current page.
425 public function getCurrentItemCount()
427 if ($this->currentItemCount
=== null) {
428 $this->currentItemCount
= $this->getItemCount($this->getCurrentItems());
431 return $this->currentItemCount
;
435 * Returns the items for the current page.
437 * @return Traversable
439 public function getCurrentItems()
441 if ($this->currentItems
=== null) {
442 $this->currentItems
= $this->getItemsByPage($this->getCurrentPageNumber());
445 return $this->currentItems
;
449 * Returns the current page number.
453 public function getCurrentPageNumber()
455 return $this->normalizePageNumber($this->currentPageNumber
);
459 * Sets the current page number.
461 * @param int $pageNumber Page number
462 * @return Paginator $this
464 public function setCurrentPageNumber($pageNumber)
466 $this->currentPageNumber
= (int) $pageNumber;
467 $this->currentItems
= null;
468 $this->currentItemCount
= null;
476 * @return FilterInterface
478 public function getFilter()
480 return $this->filter
;
486 * @param FilterInterface $filter
489 public function setFilter(FilterInterface
$filter)
491 $this->filter
= $filter;
497 * Returns an item from a page. The current page is used if there's no
500 * @param int $itemNumber Item number (1 to itemCountPerPage)
501 * @param int $pageNumber
502 * @throws Exception\InvalidArgumentException
505 public function getItem($itemNumber, $pageNumber = null)
507 if ($pageNumber == null) {
508 $pageNumber = $this->getCurrentPageNumber();
509 } elseif ($pageNumber < 0) {
510 $pageNumber = ($this->count() +
1) +
$pageNumber;
513 $page = $this->getItemsByPage($pageNumber);
514 $itemCount = $this->getItemCount($page);
516 if ($itemCount == 0) {
517 throw new Exception\
InvalidArgumentException('Page ' . $pageNumber . ' does not exist');
520 if ($itemNumber < 0) {
521 $itemNumber = ($itemCount +
1) +
$itemNumber;
524 $itemNumber = $this->normalizeItemNumber($itemNumber);
526 if ($itemNumber > $itemCount) {
527 throw new Exception\
InvalidArgumentException('Page ' . $pageNumber . ' does not'
528 . ' contain item number ' . $itemNumber);
531 return $page[$itemNumber - 1];
535 * Returns the number of items per page.
539 public function getItemCountPerPage()
541 if (empty($this->itemCountPerPage
)) {
542 $this->itemCountPerPage
= static::getDefaultItemCountPerPage();
545 return $this->itemCountPerPage
;
549 * Sets the number of items per page.
551 * @param int $itemCountPerPage
552 * @return Paginator $this
554 public function setItemCountPerPage($itemCountPerPage = -1)
556 $this->itemCountPerPage
= (int) $itemCountPerPage;
557 if ($this->itemCountPerPage
< 1) {
558 $this->itemCountPerPage
= $this->getTotalItemCount();
560 $this->pageCount
= $this->_calculatePageCount();
561 $this->currentItems
= null;
562 $this->currentItemCount
= null;
568 * Returns the number of items in a collection.
570 * @param mixed $items Items
573 public function getItemCount($items)
577 if (is_array($items) ||
$items instanceof Countable
) {
578 $itemCount = count($items);
579 } elseif ($items instanceof Traversable
) { // $items is something like LimitIterator
580 $itemCount = iterator_count($items);
587 * Returns the items for a given page.
589 * @param int $pageNumber
592 public function getItemsByPage($pageNumber)
594 $pageNumber = $this->normalizePageNumber($pageNumber);
596 if ($this->cacheEnabled()) {
597 $data = static::$cache->getItem($this->_getCacheId($pageNumber));
603 $offset = ($pageNumber - 1) * $this->getItemCountPerPage();
605 $items = $this->adapter
->getItems($offset, $this->getItemCountPerPage());
607 $filter = $this->getFilter();
609 if ($filter !== null) {
610 $items = $filter->filter($items);
613 if (!$items instanceof Traversable
) {
614 $items = new ArrayIterator($items);
617 if ($this->cacheEnabled()) {
618 $cacheId = $this->_getCacheId($pageNumber);
619 static::$cache->setItem($cacheId, $items);
620 static::$cache->setTags($cacheId, array($this->_getCacheInternalId()));
627 * Returns a foreach-compatible iterator.
629 * @throws Exception\RuntimeException
630 * @return Traversable
632 public function getIterator()
635 return $this->getCurrentItems();
636 } catch (\Exception
$e) {
637 throw new Exception\
RuntimeException('Error producing an iterator', null, $e);
642 * Returns the page range (see property declaration above).
646 public function getPageRange()
648 return $this->pageRange
;
652 * Sets the page range (see property declaration above).
654 * @param int $pageRange
655 * @return Paginator $this
657 public function setPageRange($pageRange)
659 $this->pageRange
= (int) $pageRange;
665 * Returns the page collection.
667 * @param string $scrollingStyle Scrolling style
670 public function getPages($scrollingStyle = null)
672 if ($this->pages
=== null) {
673 $this->pages
= $this->_createPages($scrollingStyle);
680 * Returns a subset of pages within a given range.
682 * @param int $lowerBound Lower bound of the range
683 * @param int $upperBound Upper bound of the range
686 public function getPagesInRange($lowerBound, $upperBound)
688 $lowerBound = $this->normalizePageNumber($lowerBound);
689 $upperBound = $this->normalizePageNumber($upperBound);
693 for ($pageNumber = $lowerBound; $pageNumber <= $upperBound; $pageNumber++
) {
694 $pages[$pageNumber] = $pageNumber;
701 * Returns the page item cache.
705 public function getPageItemCache()
708 if ($this->cacheEnabled()) {
709 $prefixLength = strlen(self
::CACHE_TAG_PREFIX
);
710 $cacheIterator = static::$cache->getIterator();
711 $cacheIterator->setMode(CacheIterator
::CURRENT_AS_VALUE
);
712 foreach ($cacheIterator as $key => $value) {
713 $tags = static::$cache->getTags($key);
714 if ($tags && in_array($this->_getCacheInternalId(), $tags)) {
715 if (substr($key, 0, $prefixLength) == self
::CACHE_TAG_PREFIX
) {
716 $data[(int) substr($key, $prefixLength)] = $value;
725 * Retrieves the view instance.
727 * If none registered, instantiates a PhpRenderer instance.
729 * @return \Zend\View\Renderer\RendererInterface|null
731 public function getView()
733 if ($this->view
=== null) {
734 $this->setView(new View\Renderer\
PhpRenderer());
741 * Sets the view object.
743 * @param \Zend\View\Renderer\RendererInterface $view
746 public function setView(View\Renderer\RendererInterface
$view = null)
754 * Brings the item number in range of the page.
756 * @param int $itemNumber
759 public function normalizeItemNumber($itemNumber)
761 $itemNumber = (int) $itemNumber;
763 if ($itemNumber < 1) {
767 if ($itemNumber > $this->getItemCountPerPage()) {
768 $itemNumber = $this->getItemCountPerPage();
775 * Brings the page number in range of the paginator.
777 * @param int $pageNumber
780 public function normalizePageNumber($pageNumber)
782 $pageNumber = (int) $pageNumber;
784 if ($pageNumber < 1) {
788 $pageCount = $this->count();
790 if ($pageCount > 0 && $pageNumber > $pageCount) {
791 $pageNumber = $pageCount;
798 * Renders the paginator.
800 * @param \Zend\View\Renderer\RendererInterface $view
803 public function render(View\Renderer\RendererInterface
$view = null)
805 if (null !== $view) {
806 $this->setView($view);
809 $view = $this->getView();
811 return $view->paginationControl($this);
815 * Returns the items of the current page as JSON.
819 public function toJson()
821 $currentItems = $this->getCurrentItems();
823 if ($currentItems instanceof AbstractResultSet
) {
824 return Json
::encode($currentItems->toArray());
826 return Json
::encode($currentItems);
830 * Tells if there is an active cache object
831 * and if the cache has not been disabled
835 protected function cacheEnabled()
837 return ((static::$cache !== null) && $this->cacheEnabled
);
841 * Makes an Id for the cache
842 * Depends on the adapter object and the page number
844 * Used to store item in cache from that Paginator instance
845 * and that current page
850 protected function _getCacheId($page = null)
852 if ($page === null) {
853 $page = $this->getCurrentPageNumber();
855 return self
::CACHE_TAG_PREFIX
. $page . '_' . $this->_getCacheInternalId();
859 * Get the internal cache id
860 * Depends on the adapter and the item count per page
862 * Used to tag that unique Paginator instance in cache
866 protected function _getCacheInternalId()
868 return md5(serialize(array(
869 spl_object_hash($this->getAdapter()),
870 $this->getItemCountPerPage()
875 * Calculates the page count.
879 protected function _calculatePageCount()
881 return (int) ceil($this->getAdapter()->count() / $this->getItemCountPerPage());
885 * Creates the page collection.
887 * @param string $scrollingStyle Scrolling style
890 protected function _createPages($scrollingStyle = null)
892 $pageCount = $this->count();
893 $currentPageNumber = $this->getCurrentPageNumber();
895 $pages = new \
stdClass();
896 $pages->pageCount
= $pageCount;
897 $pages->itemCountPerPage
= $this->getItemCountPerPage();
899 $pages->current
= $currentPageNumber;
900 $pages->last
= $pageCount;
903 if ($currentPageNumber - 1 > 0) {
904 $pages->previous
= $currentPageNumber - 1;
907 if ($currentPageNumber +
1 <= $pageCount) {
908 $pages->next
= $currentPageNumber +
1;
912 $scrollingStyle = $this->_loadScrollingStyle($scrollingStyle);
913 $pages->pagesInRange
= $scrollingStyle->getPages($this);
914 $pages->firstPageInRange
= min($pages->pagesInRange
);
915 $pages->lastPageInRange
= max($pages->pagesInRange
);
918 if ($this->getCurrentItems() !== null) {
919 $pages->currentItemCount
= $this->getCurrentItemCount();
920 $pages->itemCountPerPage
= $this->getItemCountPerPage();
921 $pages->totalItemCount
= $this->getTotalItemCount();
922 $pages->firstItemNumber
= (($currentPageNumber - 1) * $this->getItemCountPerPage()) +
1;
923 $pages->lastItemNumber
= $pages->firstItemNumber +
$pages->currentItemCount
- 1;
930 * Loads a scrolling style.
932 * @param string $scrollingStyle
933 * @return ScrollingStyleInterface
934 * @throws Exception\InvalidArgumentException
936 protected function _loadScrollingStyle($scrollingStyle = null)
938 if ($scrollingStyle === null) {
939 $scrollingStyle = static::$defaultScrollingStyle;
942 switch (strtolower(gettype($scrollingStyle))) {
944 if (!$scrollingStyle instanceof ScrollingStyleInterface
) {
945 throw new Exception\
InvalidArgumentException(
946 'Scrolling style must implement Zend\Paginator\ScrollingStyle\ScrollingStyleInterface'
950 return $scrollingStyle;
953 return static::getScrollingStylePluginManager()->get($scrollingStyle);
956 // Fall through to default case
959 throw new Exception\
InvalidArgumentException(
960 'Scrolling style must be a class ' .
961 'name or object implementing Zend\Paginator\ScrollingStyle\ScrollingStyleInterface'