Completed
Push — master-3 ( 911075...e0a0a2 )
by Krzysztof
11:33
created

ResultCollection::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
3
namespace KGzocha\Searcher\Result;
4
5
/**
6
 * Can be used to hold results from searching when developer is not 100% sure
7
 * if searching process will return array of objects or a number, or null, or whatever.
8
 * This class regardless the constructor will always be iteratable, so in worse case scenario
9
 * there will be no results inside, but your controllers will still work.
10
 * It's not recommended to use it on development environment due to eventual problems with debugging.
11
 *
12
 * @author Krzysztof Gzocha <[email protected]>
13
 */
14
class ResultCollection implements ResultCollectionInterface
15
{
16
    /**
17
     * @var \Traversable|array
18
     */
19
    private $results;
20
21
    /**
22
     * @param \Traversable|array $results
23
     */
24 23
    public function __construct($results = [])
25
    {
26 23
        if ($this->canUseResults($results)) {
27 17
            $this->results = $results;
28
29 17
            return;
30
        }
31
32 6
        $this->results = [];
33 6
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 16
    public function getResults()
39
    {
40 16
        return $this->results;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 15
    public function count()
47
    {
48 15
        return count($this->results);
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 5
    public function jsonSerialize()
55
    {
56 5
        return $this->results;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 1
    public function getIterator()
63
    {
64 1
        return new \ArrayIterator($this->results);
65
    }
66
67
    /**
68
     * @param \Traversable|array $results
69
     *
70
     * @return bool
71
     */
72 23
    private function canUseResults($results = [])
73
    {
74 23
        return is_array($results)
75 23
            || (is_object($results) && $results instanceof \Traversable);
76
    }
77
}
78