Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
NamespaceSort | |
100.00% |
15 / 15 |
|
100.00% |
3 / 3 |
5 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
__invoke | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
sort | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
2 |
1 | <?php |
2 | /** |
3 | * Given two namespaces, sort them by the number of levels, then the length of the final part |
4 | */ |
5 | |
6 | namespace BrianHenryIE\Strauss\Helpers; |
7 | |
8 | class NamespaceSort |
9 | { |
10 | |
11 | const LONGEST = false; |
12 | const SHORTEST = true; |
13 | |
14 | protected bool $order; |
15 | |
16 | public function __construct(bool $order = self::SHORTEST) |
17 | { |
18 | $this->order = $order; |
19 | } |
20 | |
21 | public function __invoke(string $a, string $b): int |
22 | { |
23 | $a = trim($a, '\\'); |
24 | $b = trim($b, '\\'); |
25 | |
26 | return $this->order === self::LONGEST |
27 | ? $this->sort($a, $b) |
28 | : $this->sort($b, $a); |
29 | } |
30 | |
31 | protected function sort(string $a, string $b): int |
32 | { |
33 | |
34 | $aParts = explode('\\', $a); |
35 | $bParts = explode('\\', $b); |
36 | |
37 | $aPartCount = count($aParts); |
38 | $bPartCount = count($bParts); |
39 | |
40 | if ($aPartCount !== $bPartCount) { |
41 | return $bPartCount - $aPartCount; |
42 | } |
43 | |
44 | $bLastPart = array_pop($aParts); |
45 | $aLastPart = array_pop($bParts); |
46 | |
47 | return strlen($aLastPart) - strlen($bLastPart); |
48 | } |
49 | } |