Skip to content

Commit

Permalink
feat: add prepList() to api
Browse files Browse the repository at this point in the history
When you need to return a formatted list which you don't want to paginate.
  • Loading branch information
wilr authored Jun 19, 2022
1 parent 8e0a5dd commit ef9dc14
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions src/Controllers/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,19 +135,58 @@ public function returnArray($arr)
return $this->getResponse()->setBody(json_encode($arr));
}


/**
* Convert a provided DataList to a PaginatedList and return the source.
*
* @param SS_List $list
* @param callable $keyFunc
* @param callabale $dataFunc
* @param int $pageLength
*
* @return array
*/
public function prepList(SS_List $list, $keyFunc = null, $dataFunc = null): array
{
$output = [];

foreach ($list as $item) {
if ($dataFunc) {
$record = $dataFunc($item);
} else if (is_array($item)) {
$record = $item;
} else {
$record = $item->toApi();
}

if ($keyFunc) {
$output[$keyFunc($item)] = $record;
} else {
$output[] = $record;
}
}

return [
$list,
$output
];
}


/**
* Convert a provided List to a PaginatedList and return the source.
*
* @param SS_List $list
* @param callable $keyFunc
* @param callabale $dataFunc
* @param int $pageLength
*
* @return array
*/
public function prepPaginatedOutput(SS_List $list, $keyFunc = null, $dataFunc = null): array
public function prepPaginatedOutput(SS_List $list, $keyFunc = null, $dataFunc = null, $pageLength = 100): array
{
$list = new PaginatedList($list, $this->request);
$list->setPageLength(100);
$list->setPageLength($pageLength);
$output = [];

foreach ($list as $item) {
Expand Down

0 comments on commit ef9dc14

Please sign in to comment.