Skip to content

Commit

Permalink
pimcore#5540: implemented natural sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
mehlichmeyer committed Jan 24, 2020
1 parent 333de09 commit df67260
Showing 1 changed file with 26 additions and 9 deletions.
Expand Up @@ -154,19 +154,13 @@ public function treeGetChildsByIdAction(Request $request, EventDispatcherInterfa
$childsList->setLimit($limit);
$childsList->setOffset($offset);

$sort = 'ASC';
if($object->getReverseSort()) {
$sort = 'DESC';
}

if ($object->getChildrenSortBy() === 'index') {
$childsList->setOrderKey(sprintf('objects.o_index %s', $sort), false);
$childsList->setOrderKey('objects.o_index ASC', false);
} else {
$childsList->setOrderKey(
sprintf(
'CAST(objects.o_%s AS CHAR CHARACTER SET utf8) COLLATE utf8_general_ci %s',
$object->getChildrenSortBy(),
$sort
'CAST(objects.o_%s AS CHAR CHARACTER SET utf8) COLLATE utf8_general_ci ASC',
$object->getChildrenSortBy()
),
false
);
Expand Down Expand Up @@ -204,7 +198,9 @@ public function treeGetChildsByIdAction(Request $request, EventDispatcherInterfa
'objects' => $objects,
]);
$eventDispatcher->dispatch(AdminEvents::OBJECT_TREE_GET_CHILDREN_BY_ID_PRE_SEND_DATA, $event);

$objects = $event->getArgument('objects');
$objects = $this->sortChildrenNaturally($objects, $object->getChildrenSortBy(), $object->getReverseSort());

if ($limit) {
return $this->adminJson([
Expand All @@ -222,6 +218,26 @@ public function treeGetChildsByIdAction(Request $request, EventDispatcherInterfa
return $this->adminJson($objects);
}

private function sortChildrenNaturally(array $objects, string $sortBy, bool $reverse): array
{
if('index' === $sortBy) {
$sortBy = 'idx';
}

usort(
$objects,
function ($a, $b) use ($sortBy) {
return strnatcasecmp($a[$sortBy], $b[$sortBy]);
}
);

if($reverse) {
$objects = array_reverse($objects);
}

return $objects;
}

/**
* @param DataObject\AbstractObject $element
*
Expand All @@ -234,6 +250,7 @@ protected function getTreeNodeConfig($element)
$tmpObject = [
'id' => $child->getId(),
'idx' => intval($child->getIndex()),
'key' => $child->getKey(),
'sortBy' => $child->getChildrenSortBy(),
'text' => htmlspecialchars($child->getKey()),
'type' => $child->getType(),
Expand Down

0 comments on commit df67260

Please sign in to comment.