Identified::andForLoading()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\TableLoader\Loader;
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 = array_merge(
27
            $forLoading,
28
            $this->identifyingColumns
29
        );
30
    }
31
32
    /**
33
     * Creates an object that identifies entities based on these columns.
34
     *
35
     * @param string ...$identifyingColumns The columns to use for identification.
36
     *
37
     * @return IdentifiesEntities           The identifying object.
38
     */
39
    public static function by(string ...$identifyingColumns): IdentifiesEntities
40
    {
41
        return new self($identifyingColumns, []);
42
    }
43
44
    /** @inheritdoc */
45
    public function andForLoading(string ...$columns): IdentifiesEntities
46
    {
47
        return new self($this->identifyingColumns, $columns);
48
    }
49
50
    /** @inheritdoc */
51
    public function forIdentityMap(array $row): string
52
    {
53
        return $this->identifierFor($row, $this->identifyingColumns);
54
    }
55
56
    /** @inheritdoc */
57
    public function forLoading(array $row): string
58
    {
59
        return $this->identifierFor($row, $this->columnsForLoading);
60
    }
61
62
    /** @inheritdoc */
63
    public function isNullFor(array $row): bool
64
    {
65
        foreach ($this->columnsForLoading as $column) {
66
            if (null !== $row[$column]) {
67
                return false;
68
            }
69
        }
70
        return true;
71
    }
72
73
    /** @throws CannotIdentifyEntity */
74
    private function identifierFor(array $row, array $identifyingColumns): string
75
    {
76
        $id = [];
77
        foreach ($identifyingColumns as $column) {
78
            $this->mustHave($row, $column);
79
            $id[] = replace(self::PROBLEMS, self::SOLUTIONS, $row[$column]);
80
        }
81
        return implode(':', $id);
82
    }
83
84
    /** @throws CannotIdentifyEntity */
85
    private function mustHave(array $row, string $column): void
86
    {
87
        if (!isset($row[$column])) {
88
            throw MissingIdentifyingColumn::inThe($row, $column);
89
        }
90
    }
91
}
92