Completed
Push — master ( b69bd3...8db10c )
by Karsten
01:49
created

GetRandomOperation::apply()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * File was created 08.05.2015 15:26
4
 *
5
 * @author Karsten J. Gerber <[email protected]>
6
 */
7
8
namespace PeekAndPoke\Component\Psi\Operation\Terminal;
9
10
use PeekAndPoke\Component\Psi\TerminalOperation;
11
12
/**
13
 * GetRandomOperation
14
 *
15
 * @author Karsten J. Gerber <[email protected]>
16
 */
17
class GetRandomOperation implements TerminalOperation
18
{
19
    /** @var */
20
    private $default;
21
22
    /**
23
     * @param mixed $default
24
     */
25 2
    public function __construct($default)
26
    {
27 2
        $this->default = $default;
28 2
    }
29
30
    /**
31
     * @param \Iterator $set
32
     *
33
     * @return mixed
34
     */
35 2
    public function apply(\Iterator $set)
36
    {
37 2
        $data  = array_values(iterator_to_array($set));
38 2
        $count = count($data);
39
40 2
        if ($count === 0) {
41 1
            return $this->default;
42
        }
43
44 1
        return $data[(int) mt_rand(0, $count - 1)];
45
    }
46
}
47