Completed
Push — master ( 12cc86...f0fc0a )
by Dmitry
02:41
created

Mapper::findOrFail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Basis\Test;
4
5
use Exception;
6
7
class Mapper
8
{
9
    protected $data;
10
11 2
    public function __construct($data)
12
    {
13 2
        $this->data = [];
14 2
        foreach ($data as $space => $rows) {
15 2
            $this->data[$space] = [];
16 2
            foreach ($rows as $row) {
17 2
                $this->data[$space][] = (object) $row;
18
            }
19
        }
20 2
    }
21
22 1
    public function find(string $space, $params = [])
23
    {
24 1
        if (array_key_exists($space, $this->data)) {
25 1
            $data = $this->data[$space];
26 1
            if (count($params)) {
27 1
                foreach ($data as $i => $v) {
28 1
                    if (array_intersect_assoc($params, get_object_vars($v)) != $params) {
29 1
                        unset($data[$i]);
30
                    }
31
                }
32 1
                $data = array_values($data);
33
            }
34 1
            return $data;
35
        }
36
        return [];
37
    }
38
39 1
    public function findOne(string $space, $params = [])
40
    {
41 1
        if (array_key_exists($space, $this->data)) {
42 1
            foreach ($this->data[$space] as $candidate) {
43 1
                if (!count($params) || array_intersect_assoc($params, get_object_vars($candidate)) == $params) {
44 1
                    return $candidate;
45
                }
46
            }
47
        }
48 1
    }
49
50 1
    public function findOrFail(string $space, $params = [])
51
    {
52 1
        $result = $this->findOne($space, $params);
53 1
        if (!$result) {
54 1
            throw new Exception("No ".$space.' found using '.json_encode($params));
55
        }
56 1
        return $result;
57
    }
58
}
59