|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Created for IG Client. |
|
4
|
|
|
* User: jakim <[email protected]> |
|
5
|
|
|
* Date: 16.03.2018 |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace Jakim\Base; |
|
9
|
|
|
|
|
10
|
|
|
|
|
11
|
|
|
use Jakim\Helper\ArrayHelper; |
|
12
|
|
|
|
|
13
|
|
|
abstract class Mapper |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* Attributes map. |
|
17
|
|
|
* |
|
18
|
|
|
* @return array |
|
19
|
|
|
*/ |
|
20
|
|
|
abstract public function config(): array; |
|
21
|
|
|
|
|
22
|
|
|
public function getData(array $content, array $config) |
|
23
|
|
|
{ |
|
24
|
|
|
$envelopeKey = ArrayHelper::getValue($config, 'envelope'); |
|
25
|
|
|
if ($envelopeKey) { |
|
26
|
|
|
$content = ArrayHelper::getValue($content, $envelopeKey, []); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
return $content; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function createModel(array $data, array $config, bool $relations = false) |
|
33
|
|
|
{ |
|
34
|
|
|
$modelClass = ArrayHelper::getValue($config, 'class'); |
|
35
|
|
|
$propertiesMap = ArrayHelper::getValue($config, 'properties', []); |
|
36
|
|
|
|
|
37
|
|
|
$model = new $modelClass(); |
|
38
|
|
|
foreach ($propertiesMap as $to => $from) { |
|
39
|
|
|
$model->$to = ArrayHelper::getValue($data, $from); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
if ($relations === true) { |
|
43
|
|
|
$relationsConfig = ArrayHelper::getValue($config, 'relations', []); |
|
44
|
|
|
$this->createRelations($model, $data, $relationsConfig, $relations); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return $model; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param $model |
|
52
|
|
|
* @param array $data |
|
53
|
|
|
* @param array $relationsConfig |
|
54
|
|
|
* @param bool $relations |
|
55
|
|
|
*/ |
|
56
|
|
|
protected function createRelations($model, array $data, array $relationsConfig, bool $relations = false): void |
|
57
|
|
|
{ |
|
58
|
|
|
foreach ($relationsConfig as $property => $config) { |
|
59
|
|
|
$relationData = $this->getData($data, $config); |
|
60
|
|
|
if ($relationData) { |
|
61
|
|
|
if (ArrayHelper::getValue($config, 'multiple', false)) { |
|
62
|
|
|
foreach ($relationData as $rData) { |
|
63
|
|
|
$model->$property[] = $this->createModel($rData, $config, $relations); |
|
64
|
|
|
} |
|
65
|
|
|
} else { |
|
66
|
|
|
$model->$property = $this->createModel($relationData, $config, $relations); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
} |