SortedGenericList::firstOrNull()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cunningsoft\GenericList;
6
7
use function usort;
8
9
/**
10
 * This class must only be used in Sorted*List implementations. It provides a layer on top of php's array to ease
11
 * the creation of concrete list classes like SortedByAgeUserList or SortedByTitleBlogPostList. It also makes sure
12
 * it's elements are in the order defined in the sort callback.
13
 */
14
final class SortedGenericList extends GenericList
15
{
16 5
    public function sort(callable $callback): void
17
    {
18 5
        usort($this->elements, $callback);
19 5
    }
20
21
    /** @return mixed */
22 10
    public function atIndex(int $index)
23
    {
24 10
        if ($index < 0 || $index > $this->count() - 1) {
25 3
            throw new NoElementAtIndex($index);
26
        }
27
28 7
        return $this->elements[$index];
29
    }
30
31
    /** @return mixed|null */
32 8
    public function atIndexOrNull(int $index)
33
    {
34 8
        if ($index < 0 || $index > $this->count() - 1) {
35 3
            return null;
36
        }
37
38 5
        return $this->elements[$index];
39
    }
40
41
    /** @return mixed */
42 3
    public function first()
43
    {
44 3
        if ($this->isEmpty()) {
45 1
            throw new NoElements();
46
        }
47
48 2
        return $this->atIndex(0);
49
    }
50
51
    /** @return mixed|null */
52 2
    public function firstOrNull()
53
    {
54 2
        return $this->atIndexOrNull(0);
55
    }
56
57
    /** @return mixed */
58 3
    public function last()
59
    {
60 3
        if ($this->isEmpty()) {
61 1
            throw new NoElements();
62
        }
63
64 2
        return $this->atIndex($this->count() - 1);
65
    }
66
67
    /** @return mixed|null */
68 2
    public function lastOrNull()
69
    {
70 2
        return $this->atIndexOrNull($this->count() - 1);
71
    }
72
}
73