Item::fromArray()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Radowoj\Searcher\SearchResult;
4
5
use InvalidArgumentException;
6
7
class Item implements IItem
8
{
9
    protected $url = '';
10
11
    protected $title = null;
12
13
    protected $description = null;
14
15 7
    public function __construct(array $data)
16
    {
17 7
        $this->fromArray($data);
18 5
    }
19
20
21 7
    protected function fromArray(array $data)
22
    {
23 7
        foreach($data as $key => $value) {
24 6
            if (!property_exists($this, $key)) {
25 1
                throw new InvalidArgumentException("Invalid search result item property: {$key}");
26
            }
27
28 5
            $validatorMethod = 'validate' . ucfirst($key);
29 5
            if (method_exists($this, $validatorMethod)) {
30 5
                $this->{$validatorMethod}($value);
31
            }
32
33 4
            $this->{$key} = $value;
34
        }
35 5
    }
36
37
38 1
    public function toArray()
39
    {
40
        return [
41 1
            'url'           => $this->url,
42 1
            'title'         => $this->title,
43 1
            'description'   => $this->description,
44
        ];
45
    }
46
47
48
49 5
    protected function validateUrl($url)
50
    {
51 5
        if (filter_var($url, FILTER_VALIDATE_URL) === false) {
52 1
            throw new InvalidArgumentException("Invalid URL given: {$url}");
53
        }
54 4
    }
55
56
57 1
    public function __toString()
58
    {
59 1
        return $this->url;
60
    }
61
62
63
64
}
65