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

Popolo   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
lcom 0
cbo 2
dl 0
loc 63
rs 10
c 1
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __get() 0 9 2
A fromFilename() 0 7 1
A fromUrl() 0 8 2
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