GroupFormatter
3 days ago
LabelFormatter
3 days ago
GroupFormatter.php
3 days ago
Groups.php
3 days ago
LabelFormatter.php
3 days ago
Groups.php
43 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Helper\Select\Generic; |
| 6 | |
| 7 | use AC\Helper\Select; |
| 8 | use AC\Helper\Select\OptionGroup; |
| 9 | |
| 10 | class Groups extends Select\Options |
| 11 | { |
| 12 | public function __construct(Select\Options $options, GroupFormatter $formatter) |
| 13 | { |
| 14 | parent::__construct($this->create_groups($options, $formatter)); |
| 15 | } |
| 16 | |
| 17 | private function create_groups(Select\Options $options, GroupFormatter $formatter): array |
| 18 | { |
| 19 | $groups = []; |
| 20 | |
| 21 | foreach ($options as $option) { |
| 22 | $groups[$formatter->format((string)$option->get_value())][] = $option; |
| 23 | } |
| 24 | |
| 25 | $option_groups = []; |
| 26 | |
| 27 | foreach ($this->sort($groups) as $label => $_options) { |
| 28 | $option_groups[] = new OptionGroup($label, $_options); |
| 29 | } |
| 30 | |
| 31 | return $option_groups; |
| 32 | } |
| 33 | |
| 34 | protected function sort(array $groups): array |
| 35 | { |
| 36 | // sort natural by key |
| 37 | uksort($groups, 'strnatcmp'); |
| 38 | |
| 39 | return $groups; |
| 40 | } |
| 41 | |
| 42 | } |
| 43 |