1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Stratadox\TableLoader; |
5
|
|
|
|
6
|
|
|
use function array_merge; |
7
|
|
|
use function implode; |
8
|
|
|
use function str_replace as replace; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Identifies the entities in the table rows. |
12
|
|
|
* |
13
|
|
|
* @author Stratadox |
14
|
|
|
*/ |
15
|
|
|
final class Identified implements IdentifiesEntities |
16
|
|
|
{ |
17
|
|
|
private const PROBLEMS = ['\\', ':']; |
18
|
|
|
private const SOLUTIONS = ['\\\\', '\\:']; |
19
|
|
|
|
20
|
|
|
private $identifyingColumns; |
21
|
|
|
private $columnsForLoading; |
22
|
|
|
|
23
|
|
|
private function __construct(array $identifyingColumns, array $forLoading) |
24
|
|
|
{ |
25
|
|
|
$this->identifyingColumns = $identifyingColumns; |
26
|
|
|
$this->columnsForLoading = $forLoading; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Creates an object that identifies entities based on these columns. |
31
|
|
|
* |
32
|
|
|
* @param string ...$identifyingColumns The columns to use for identification. |
33
|
|
|
* |
34
|
|
|
* @return Identified The identifying object. |
35
|
|
|
*/ |
36
|
|
|
public static function by(string ...$identifyingColumns): self |
37
|
|
|
{ |
38
|
|
|
return new self($identifyingColumns, []); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** @inheritdoc */ |
42
|
|
|
public function andForLoading(string ...$columns): IdentifiesEntities |
43
|
|
|
{ |
44
|
|
|
return new self($this->identifyingColumns, $columns); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** @inheritdoc */ |
48
|
|
|
public function forIdentityMap(array $row): string |
49
|
|
|
{ |
50
|
|
|
return $this->identifierFor($row, $this->identifyingColumns); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** @inheritdoc */ |
54
|
|
|
public function forLoading(array $row): string |
55
|
|
|
{ |
56
|
|
|
return $this->identifierFor($row, array_merge( |
57
|
|
|
$this->identifyingColumns, |
58
|
|
|
$this->columnsForLoading |
59
|
|
|
)); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** @throws CannotIdentifyEntity */ |
63
|
|
|
private function identifierFor(array $row, array $identifyingColumns): string |
64
|
|
|
{ |
65
|
|
|
$id = []; |
66
|
|
|
foreach ($identifyingColumns as $column) { |
67
|
|
|
$this->mustHave($row, $column); |
68
|
|
|
$id[] = replace(self::PROBLEMS, self::SOLUTIONS, $row[$column]); |
69
|
|
|
} |
70
|
|
|
return '#' . implode(':', $id); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** @throws CannotIdentifyEntity */ |
74
|
|
|
private function mustHave(array $row, string $column): void |
75
|
|
|
{ |
76
|
|
|
if (!isset($row[$column])) { |
77
|
|
|
throw MissingIdentifyingColumn::inThe($row, $column); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|