1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Departements\Datasource; |
4
|
|
|
|
5
|
|
|
use Departements\Model\Region; |
6
|
|
|
use Departements\Model\Departement; |
7
|
|
|
use Departements\Model\Commune; |
8
|
|
|
|
9
|
|
|
use PhpCollection\Sequence; |
10
|
|
|
|
11
|
|
|
class JsonDatasource extends AbstractDatasource implements DatasourceInterface |
12
|
|
|
{ |
13
|
|
|
private $file; |
14
|
|
|
|
15
|
|
|
public function __construct($file) |
16
|
|
|
{ |
17
|
|
|
parent::__construct(); |
18
|
|
|
$this->file = $file; |
19
|
|
|
$this->loadDatas(); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
private function loadDatas() { |
23
|
|
|
$datas = json_decode(file_get_contents($this->file), true); |
24
|
|
|
foreach($datas as $regionCode => $regionDatas) { |
25
|
|
|
$region = new Region(); |
26
|
|
|
$region->setCode($regionCode); |
27
|
|
|
$region->setName($regionDatas['name']); |
28
|
|
|
foreach($regionDatas['depts'] as $deptCode => $deptDatas) { |
29
|
|
|
$departement = new Departement(); |
30
|
|
|
$departement->setCode($deptCode); |
31
|
|
|
$departement->setName($deptDatas['name']); |
32
|
|
|
$departement->setRegion($region); |
33
|
|
|
|
34
|
|
|
$region->addDepartement($departement); |
35
|
|
|
|
36
|
|
|
if (!isset($deptDatas['cities'])) { |
37
|
|
|
$deptDatas['cities'] = array(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
// add cities |
41
|
|
|
foreach($deptDatas['cities'] as $zipcode => $cities) { |
42
|
|
|
$communes = new Sequence(); |
43
|
|
|
foreach($cities as $cityName) { |
44
|
|
|
$commune = new Commune($cityName, $zipcode, $departement); |
45
|
|
|
$this->addToIndex('communes', $cityName, $zipcode); |
46
|
|
|
$communes->add($commune); |
47
|
|
|
$departement->addCommune($commune); |
48
|
|
|
} |
49
|
|
|
$this->communes->set($zipcode, $communes); |
|
|
|
|
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$this->addToIndex('departements', $deptDatas['name'], $deptCode); |
53
|
|
|
$this->departements->set($deptCode, $departement); |
54
|
|
|
} |
55
|
|
|
$this->addToIndex('regions', $region->getName(), $regionCode); |
56
|
|
|
$this->regions->set($regionCode, $region); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: