Created
August 17, 2017 12:35
-
-
Save dereuromark/46e039e793d0f3e06925e92da3d92145 to your computer and use it in GitHub Desktop.
App Paginator extension for out of bounds redirect instead of 404 exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For CakePHP 5+ see https://github.com/dereuromark/cakephp-shim/releases/tag/3.2.0 instead.