|
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
|
|
|
|