Skip to content

Instantly share code, notes, and snippets.

@dereuromark
Created August 17, 2017 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dereuromark/46e039e793d0f3e06925e92da3d92145 to your computer and use it in GitHub Desktop.
Save dereuromark/46e039e793d0f3e06925e92da3d92145 to your computer and use it in GitHub Desktop.
App Paginator extension for out of bounds redirect instead of 404 exception
<?php
namespace App\Controller\Component;
use Cake\Controller\Component\PaginatorComponent as CorePaginatorComponent;
use Cake\Datasource\QueryInterface;
use Cake\Network\Exception\NotFoundException;
class PaginatorComponent extends CorePaginatorComponent
{
/**
* Overwrite to always redirect from out of bounds to last page of paginated collection.
* If pageCount not available, then use first page.
*
* @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate.
* @param array $settings The settings/configuration used for pagination.
*
* @throws \Cake\Network\Exception\NotFoundException
*
* @return \Cake\Datasource\ResultSetInterface Query results
*/
public function paginate($object, array $settings = [])
{
try {
$resultSet = parent::paginate($object, $settings);
} catch (NotFoundException $exception) {
$query = null;
if ($object instanceof QueryInterface) {
$query = $object;
$object = $query->repository();
}
$alias = $object->alias();
$lastPage = $this->request->params['paging'][$alias]['pageCount'] > 1 ? $this->request->params['paging'][$alias]['pageCount'] : null;
$response = $this->getController()->redirect(['?' => ['page' => $lastPage] + $this->request->getQuery()]);
// To be please PHPCS and tests, cannot be reached in production.
if (PHP_SAPI === 'cli') {
throw new NotFoundException('Redirect to ' . $response->getHeaderLine('Location') . ' for non-CLI.');
} else {
$response->send();
}
exit();
}
return $resultSet;
}
}
@dereuromark
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment