iterable_last()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 10
nc 5
nop 2
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Improved;
6
7
/**
8
 * Get the last element of an iterable.
9
 *
10
 * @param iterable $iterable
11
 * @param bool     $required  Throw RangeException instead of returning null for empty iterable
12
 * @return mixed
13
 */
14
function iterable_last(iterable $iterable, bool $required = false)
0 ignored issues
show
introduced by
Function Improved\iterable_last() has parameter $iterable with no value type specified in iterable type iterable.
Loading history...
15
{
16 8
    if (is_array($iterable) && $iterable !== []) {
17 1
        return end($iterable);
18
    }
19
20 7
    $last = null;
21 7
    $empty = true; // because $last can be any value including null.
22
23 7
    foreach ($iterable as $value) {
24 5
        $last = $value;
25 5
        $empty = false;
26
    }
27
28 7
    if ($empty && $required) {
29 1
        throw new \RangeException("Unable to get last element; iterable is empty");
30
    }
31
32 6
    return $last;
33
}
34