/**
* @inheritDoc
*
* @throws Yosymfony\Spress\Core\Exception\AttributeValueException if bad attribute value.
*/
public function generateItems(ItemInterface $templateItem, array $collections)
{
$result = [];
$options = $this->getAttributesResolver($templateItem);
if ($options['max_page'] < 1) {
throw new AttributeValueException('Items per page value must be great than 0.', 'max_page', $templateItem->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE));
}
$arr = new ArrayWrapper($collections);
$providerName = $this->providerToCollection($options['provider']);
if ($arr->has($providerName) === false || is_array($provider = $arr->get($providerName)) === false) {
throw new AttributeValueException(sprintf('Provider: "%s" for pagination not found.', $options['provider']), 'provider', $templateItem->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE));
}
$arr->setArray($provider);
$pages = $arr->paginate($options['max_page']);
$totalPages = count($pages);
$totalItems = count($provider);
$templatePath = dirname($templateItem->getPath(Item::SNAPSHOT_PATH_RELATIVE));
if ($templatePath === '.') {
$templatePath = '';
}
foreach ($pages as $page => $items) {
$previousPage = $page > 1 ? $page - 1 : null;
$previousPagePath = $this->getPageRelativePath($templatePath, $options['permalink'], $previousPage);
$previousPageUrl = $this->getPagePermalink($previousPagePath);
$nextPage = $page === $totalPages ? null : $page + 1;
$nextPagePath = $this->getPageRelativePath($templatePath, $options['permalink'], $nextPage);
$nextPageUrl = $this->getPagePermalink($nextPagePath);
$pageAttr = new ArrayWrapper($templateItem->getAttributes());
$pageAttr->set('pagination.per_page', $options['max_page']);
$pageAttr->set('pagination.total_items', $totalItems);
$pageAttr->set('pagination.total_pages', $totalPages);
$pageAttr->set('pagination.page', $page);
$pageAttr->set('pagination.previous_page', $previousPage);
$pageAttr->set('pagination.previous_page_path', $previousPagePath);
$pageAttr->set('pagination.previous_page_url', $previousPageUrl);
$pageAttr->set('pagination.next_page', $nextPage);
$pageAttr->set('pagination.next_page_path', $nextPagePath);
$pageAttr->set('pagination.next_page_url', $nextPageUrl);
$pageAttr->remove('permalink');
$pagePath = $this->getPageRelativePath($templatePath, $options['permalink'], $page);
$permalink = $this->getPagePermalink($pagePath);
$item = new PaginationItem($templateItem->getContent(), $pagePath, $pageAttr->getArray());
$item->setPageItems($items);
$item->setPath($pagePath, Item::SNAPSHOT_PATH_RELATIVE);
$item->setPath($permalink, Item::SNAPSHOT_PATH_PERMALINK);
$result[] = $item;
}
return $result;
}