Popolo::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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