Handler.php
1 month ago
ListingDateRangeFilterTrait.php
1 month ago
ListingDefinition.php
1 year ago
ListingRepository.php
1 month ago
PageLimit.php
2 years ago
index.php
3 years ago
Handler.php
82 lines
| 1 | <?php // phpcs:ignore SlevomatCodingStandard.TypeHints.DeclareStrictTypes.DeclareStrictTypesMissing |
| 2 | |
| 3 | namespace MailPoet\Listing; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | class Handler { |
| 9 | public function getListingDefinition(array $data): ListingDefinition { |
| 10 | $data = $this->processData($data); |
| 11 | return new ListingDefinition( |
| 12 | $data['group'], |
| 13 | $data['filter'] ?? [], |
| 14 | $data['search'], |
| 15 | $data['params'] ?? [], |
| 16 | $data['sort_by'], |
| 17 | $data['sort_order'], |
| 18 | $data['offset'], |
| 19 | $data['limit'], |
| 20 | $data['selection'] ?? [] |
| 21 | ); |
| 22 | } |
| 23 | |
| 24 | private function sanitizeSortBy(string $sortBy): string { |
| 25 | $sortBy = trim($sortBy); |
| 26 | if ($sortBy === '') { |
| 27 | return 'id'; |
| 28 | } |
| 29 | |
| 30 | // Fallback to `id` when there is at least one non-identifier character. |
| 31 | if (strspn($sortBy, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_') !== strlen($sortBy)) { |
| 32 | return 'id'; |
| 33 | } |
| 34 | |
| 35 | return $sortBy; |
| 36 | } |
| 37 | |
| 38 | private function processData(array $data) { |
| 39 | // check if sort order was specified or default to "asc" |
| 40 | $sortOrder = (!empty($data['sort_order'])) ? $data['sort_order'] : 'asc'; |
| 41 | // constrain sort order value to either be "asc" or "desc" |
| 42 | $sortOrder = strtolower(trim((string)$sortOrder)); |
| 43 | if ($sortOrder === '') { |
| 44 | $sortOrder = 'asc'; |
| 45 | } |
| 46 | $sortOrder = in_array($sortOrder, ['asc', 'desc'], true) ? $sortOrder : 'desc'; |
| 47 | |
| 48 | // sanitize sort by |
| 49 | $sortBy = (!empty($data['sort_by'])) |
| 50 | ? $this->sanitizeSortBy((string)$data['sort_by']) |
| 51 | : ''; |
| 52 | |
| 53 | if (empty($sortBy)) { |
| 54 | $sortBy = 'id'; |
| 55 | } |
| 56 | |
| 57 | $data = [ |
| 58 | // extra parameters |
| 59 | 'params' => (isset($data['params']) ? $data['params'] : []), |
| 60 | // pagination |
| 61 | 'offset' => (isset($data['offset']) ? (int)$data['offset'] : 0), |
| 62 | 'limit' => (isset($data['limit']) |
| 63 | ? (int)$data['limit'] |
| 64 | : PageLimit::DEFAULT_LIMIT_PER_PAGE |
| 65 | ), |
| 66 | // searching |
| 67 | 'search' => (isset($data['search']) ? $data['search'] : null), |
| 68 | // sorting |
| 69 | 'sort_by' => $sortBy, |
| 70 | 'sort_order' => $sortOrder, |
| 71 | // grouping |
| 72 | 'group' => (isset($data['group']) ? $data['group'] : null), |
| 73 | // filters |
| 74 | 'filter' => (isset($data['filter']) ? $data['filter'] : null), |
| 75 | // selection |
| 76 | 'selection' => (isset($data['selection']) ? $data['selection'] : null), |
| 77 | ]; |
| 78 | |
| 79 | return $data; |
| 80 | } |
| 81 | } |
| 82 |