Completed
Push — master ( 85c19c...2798ac )
by Jesse
02:11
created

Identified::isNullFor()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 3
nop 1
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 = 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
    public function isNullFor(array $row): bool
63
    {
64
        foreach ($this->columnsForLoading as $column) {
65
            if (null !== $row[$column]) {
66
                return false;
67
            }
68
        }
69
        return true;
70
    }
71
72
    /** @throws CannotIdentifyEntity */
73
    private function identifierFor(array $row, array $identifyingColumns): string
74
    {
75
        $id = [];
76
        foreach ($identifyingColumns as $column) {
77
            $this->mustHave($row, $column);
78
            $id[] = replace(self::PROBLEMS, self::SOLUTIONS, $row[$column]);
79
        }
80
        return implode(':', $id);
81
    }
82
83
    /** @throws CannotIdentifyEntity */
84
    private function mustHave(array $row, string $column): void
85
    {
86
        if (!isset($row[$column])) {
87
            throw MissingIdentifyingColumn::inThe($row, $column);
88
        }
89
    }
90
}
91