Lines 5.55% 1 / 18
Functions and Methods 33.33% 1 / 3
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
Base 5.55% 1 / 18 33.33% 1 / 3 17.48 0.00% 0 / 1
 offsetSet 100.00% 1 / 1 100.00% 1 / 1 1
 sortByName 0.00% 0 / 5 0.00% 0 / 1 2
 sortWithCollator 0.00% 0 / 12 0.00% 0 / 1 6
1<?php
2
3/**
4 * @package Zmsdldb
5 * @copyright BerlinOnline Stadtportal GmbH & Co. KG
6 **/
7
8namespace BO\Zmsdldb\Collection;
9
10use BO\Zmsdldb\Helper\Sorter;
11
12/**
13 * @template T of \BO\Zmsdldb\Entity\Base
14 * @extends \ArrayObject<int|string, T>
15 */
16class Base extends \ArrayObject
17{
18    #[\Override]
19    public function offsetSet(mixed $key, mixed $value): void
20    {
21        parent::offsetSet($key, $value);
22    }
23
24    public function sortByName(): static
25    {
26        $itemList = clone $this;
27        $itemList->uasort(function ($a, $b) {
28            return strcmp(Sorter::toSortableString($a->getName()), Sorter::toSortableString($b->getName()));
29        });
30        return $itemList;
31    }
32
33    /**
34     * @psalm-api
35     */
36    public function sortWithCollator(string $field = 'name', string $locale = 'de'): static
37    {
38        $collator = collator_create($locale);
39        if ($collator === null) {
40            throw new \RuntimeException('Could not create collator for locale ' . $locale);
41        }
42        $collator->setStrength(\Collator::QUATERNARY);
43        $collator->setAttribute(\Collator::QUATERNARY, \Collator::ON);
44        $collator->setAttribute(\Collator::CASE_FIRST, \Collator::ON);
45        $collator->setAttribute(\Collator::NUMERIC_COLLATION, \Collator::ON);
46
47        $itemList = clone $this;
48        $itemList->uasort(function ($itemA, $itemB) use ($collator, $field) {
49            return collator_compare($collator, $itemA[$field], $itemB[$field]);
50        });
51        return $itemList;
52    }
53}