Passed
Push — master ( f29617...71d8bd )
by Andy
14:17
created

Popolo::__get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 9
rs 9.6666
c 1
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace mySociety\EveryPoliticianPopolo;
4
5
class Popolo
6
{
7
    use Traits\ArrayGetterTrait;
8
9
    private $jsonData;
10
    private $classes = [
11
        'persons'       => 'PersonCollection',
12
        'organizations' => 'OrganizationCollection',
13
        'memberships'   => 'MembershipCollection',
14
        'areas'         => 'AreaCollection',
15
        'posts'         => 'PostCollection',
16
        'events'        => 'EventCollection',
17
    ];
18
19
    /**
20
     * Create a new Popolo Instance from
21
     */
22
    public function __construct($jsonData)
23
    {
24
        $this->jsonData = $jsonData;
25
    }
26
27
    public function __get($prop)
28
    {
29
        if (array_key_exists($prop, $this->classes)) {
30
            $c = 'mySociety\\EveryPoliticianPopolo\\Collections\\'.$this->classes[$prop];
31
            $dataArr = $this->arrGet($this->jsonData, $prop, []);
32
            return new $c($dataArr, $this);
33
        }
34
        trigger_error('Undefined property: '.__CLASS__.'::$'.$prop, E_USER_ERROR);
35
    }
36
37
    /**
38
     * Construct from filename
39
     *
40
     * @param string $filename name of Popolo json file
41
     *
42
     * @return $this
43
     */
44
    public static function fromFilename($filename)
45
    {
46
        $contents = file_get_contents($filename);
47
        $jsonData = json_decode($contents, true);
48
        $instance = new self($jsonData);
49
        return $instance;
50
    }
51
52
    /**
53
     * Construct from URL
54
     *
55
     * @param string $url location of Popolo json file
56
     *
57
     * @return $this
58
     */
59
    public static function fromUrl($url, $client = null)
60
    {
61
        $client = $client ?: new \GuzzleHttp\Client();
62
        $response = $client->get($url);
63
        $jsonData = json_decode($response->getBody()->getContents(), true);
64
        $instance = new self($jsonData);
65
        return $instance;
66
    }
67
}
68