|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\kw_mapper\Adapters; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\kw_mapper\MapperException; |
|
7
|
|
|
use kalanis\kw_mapper\Records\ARecord; |
|
8
|
|
|
|
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class DataExchange |
|
12
|
|
|
* @package kalanis\kw_mapper\Adapters |
|
13
|
|
|
* Simple exchanging data via array |
|
14
|
|
|
*/ |
|
15
|
|
|
class DataExchange |
|
16
|
|
|
{ |
|
17
|
|
|
protected ARecord $record; |
|
18
|
|
|
/** @var array<string|int, bool> */ |
|
19
|
|
|
protected array $excluded = []; |
|
20
|
|
|
|
|
21
|
9 |
|
public function __construct(ARecord $record) |
|
22
|
|
|
{ |
|
23
|
9 |
|
$this->record = $record; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Add property which will be ignored |
|
28
|
|
|
* @param string|int $property |
|
29
|
|
|
*/ |
|
30
|
1 |
|
public function addExclude($property): void |
|
31
|
|
|
{ |
|
32
|
1 |
|
$this->excluded[$property] = true; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
public function clearExclude(): void |
|
36
|
|
|
{ |
|
37
|
1 |
|
$this->excluded = []; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Import data into record |
|
42
|
|
|
* @param iterable<string|int, mixed> $data |
|
43
|
|
|
* @throws MapperException |
|
44
|
|
|
* @return int how many entries has been imported |
|
45
|
|
|
*/ |
|
46
|
4 |
|
public function import(iterable $data): int |
|
47
|
|
|
{ |
|
48
|
4 |
|
$imported = 0; |
|
49
|
4 |
|
foreach ($data as $property => $value) { |
|
50
|
4 |
|
if (!$this->isExcluded($property) |
|
51
|
4 |
|
&& $this->record->offsetExists($property) |
|
52
|
4 |
|
&& ($this->record->offsetGet($property) != $value) |
|
53
|
|
|
) { |
|
54
|
4 |
|
$this->record->offsetSet($property, $value); |
|
55
|
4 |
|
$imported++; |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
4 |
|
return $imported; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Export data from record |
|
63
|
|
|
* @return array<string|int, mixed> |
|
64
|
|
|
*/ |
|
65
|
6 |
|
public function export(): array |
|
66
|
|
|
{ |
|
67
|
6 |
|
$returnData = []; |
|
68
|
6 |
|
foreach ($this->record as $property => $value) { |
|
69
|
6 |
|
if (!$this->isExcluded($property)) { |
|
70
|
6 |
|
$returnData[$property] = $value; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
6 |
|
return $returnData; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* @param string|int $property |
|
78
|
|
|
* @return bool |
|
79
|
|
|
*/ |
|
80
|
9 |
|
protected function isExcluded($property): bool |
|
81
|
|
|
{ |
|
82
|
9 |
|
return isset($this->excluded[$property]); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
4 |
|
public function getRecord(): ARecord |
|
86
|
|
|
{ |
|
87
|
4 |
|
return $this->record; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|