Passed
Push — master ( ae1a26...486cfe )
by Petr
03:11
created

DataExchange::addExclude()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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
    /** @var ARecord **/
18
    protected $record;
19
    /** @var array<string|int, bool> */
20
    protected $excluded = [];
21
22 9
    public function __construct(ARecord $record)
23
    {
24 9
        $this->record = $record;
25
    }
26
27
    /**
28
     * Add property which will be ignored
29
     * @param string|int $property
30
     */
31 1
    public function addExclude($property): void
32
    {
33 1
        $this->excluded[$property] = true;
34
    }
35
36 1
    public function clearExclude(): void
37
    {
38 1
        $this->excluded = [];
39
    }
40
41
    /**
42
     * Import data into record
43
     * @param iterable<string|int, mixed> $data
44
     * @throws MapperException
45
     * @return int how much nas been imported
46
     */
47 4
    public function import(iterable $data): int
48
    {
49 4
        $imported = 0;
50 4
        foreach ($data as $property => $value) {
51 4
            if (!$this->isExcluded($property)
52 4
                && $this->record->offsetExists($property)
53 4
                && ($this->record->offsetGet($property) != $value)
54
            ) {
55 4
                $this->record->offsetSet($property, $value);
56 4
                $imported++;
57
            }
58
        }
59 4
        return $imported;
60
    }
61
62
    /**
63
     * Export data from record
64
     * @return array<string|int, mixed>
65
     */
66 6
    public function export(): array
67
    {
68 6
        $returnData = [];
69 6
        foreach ($this->record as $property => $value) {
70 6
            if (!$this->isExcluded($property)) {
71 6
                $returnData[$property] = $value;
72
            }
73
        }
74 6
        return $returnData;
75
    }
76
77
    /**
78
     * @param string|int $property
79
     * @return bool
80
     */
81 9
    protected function isExcluded($property): bool
82
    {
83 9
        return isset($this->excluded[$property]);
84
    }
85
86 4
    public function getRecord(): ARecord
87
    {
88 4
        return $this->record;
89
    }
90
}
91