diff --git a/src/Compat/CompatController.php b/src/Compat/CompatController.php index f4c2fb0b..735d0da9 100644 --- a/src/Compat/CompatController.php +++ b/src/Compat/CompatController.php @@ -10,6 +10,7 @@ use ipl\Html\HtmlDocument; use ipl\Html\HtmlString; use ipl\Html\ValidHtml; +use ipl\Orm\Common\SortUtil; use ipl\Orm\Query; use ipl\Stdlib\Contract\Paginatable; use ipl\Web\Control\LimitControl; @@ -294,15 +295,25 @@ public function createSortControl(Query $query, array $columns): SortControl $this->params->shift($sortControl->getSortParam()); - $sortControl->handleRequest($this->getServerRequest()); - $defaultSort = null; - if (func_num_args() === 3) { $defaultSort = func_get_args()[2]; } - return $sortControl->apply($query, $defaultSort); + $default = $defaultSort ?? $query->getModel()->getDefaultSort(); + if (! empty($default)) { + $sortControl->setDefault(SortUtil::normalizeSortSpec($default)); + + $columns = $sortControl->getColumns(); + $default = $sortControl->getDefault(); + if (! empty($defaultSort) && ! isset($columns[$default])) { + throw new InvalidArgumentException(sprintf('Invalid default sort "%s" given', $default)); + } + } + + $sortControl->handleRequest($this->getServerRequest()); + + return $sortControl->apply($query); } /** diff --git a/src/Control/SortControl.php b/src/Control/SortControl.php index 65c2c3d7..6b06c6c4 100644 --- a/src/Control/SortControl.php +++ b/src/Control/SortControl.php @@ -197,11 +197,10 @@ public function getSort(): ?string * Sort the given query according to the request * * @param Query $query - * @param ?array|string $defaultSort * * @return $this */ - public function apply(Query $query, $defaultSort = null): self + public function apply(Query $query): self { if ($this->getRequest() === null) { // handleRequest() has not been called yet @@ -209,11 +208,6 @@ public function apply(Query $query, $defaultSort = null): self $this->handleRequest(ServerRequest::fromGlobals()); } - $default = $defaultSort ?? (array) $query->getModel()->getDefaultSort(); - if (! empty($default)) { - $this->setDefault(SortUtil::normalizeSortSpec($default)); - } - $sort = $this->getSort(); if (! empty($sort)) { $query->orderBy(SortUtil::createOrderBy($sort));