Completed
Push — master ( 24cab6...edf428 )
by SignpostMarv
03:24
created

RemoveDaftObjectById()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 4
nop 1
dl 0
loc 20
ccs 10
cts 10
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
* Base daft objects.
4
*
5
* @author SignpostMarv
6
*/
7
declare(strict_types=1);
8
9
namespace SignpostMarv\DaftObject;
10
11
use ParagonIE\EasyDB\EasyDB;
12
13
abstract class AbstractDaftObjectEasyDBRepository extends DaftObjectMemoryRepository
14
{
15
    /**
16
    * @var EasyDB
17
    */
18
    protected $db;
19
20 10
    protected function __construct(string $type, EasyDB $db)
21
    {
22 10
        parent::__construct($type);
23 10
        $this->db = $db;
24 10
    }
25
26 18
    public static function DaftObjectRepositoryByType(
27
        string $type,
28
        ? EasyDB $db = null
29
    ) : DaftObjectRepository {
30 18
        $a = is_a($type, DaftObjectCreatedByArray::class, true);
31
        if (
32 18
            false === $a ||
33 18
            false === is_a($type, DefinesOwnIdPropertiesInterface::class, true)
34
        ) {
35 6
            throw new DaftObjectRepositoryTypeByClassMethodAndTypeException(
36 6
                1,
37 6
                static::class,
38 6
                __FUNCTION__,
39 6
                ($a ? DefinesOwnIdPropertiesInterface::class : DaftObjectCreatedByArray::class),
40 6
                $type
41
            );
42 12
        } elseif (false === ($db instanceof EasyDB)) {
43 2
            throw new DatabaseConnectionNotSpecifiedException(
44 2
                2,
45 2
                static::class,
46 2
                __FUNCTION__,
47 2
                EasyDB::class,
48 2
                'null'
49
            );
50
        }
51
52 10
        return new static($type, $db);
53
    }
54
55 10
    public static function DaftObjectRepositoryByDaftObject(
56
        DefinesOwnIdPropertiesInterface $object,
57
        ? EasyDB $db = null
58
    ) : DaftObjectRepository {
59 10
        return static::DaftObjectRepositoryByType(get_class($object), $db);
60
    }
61
62
    /**
63
    * @param mixed $id
64
    */
65 4
    public function RemoveDaftObjectById($id) : void
66
    {
67 4
        $id = array_values(is_array($id) ? $id : [$id]);
68
69
        /**
70
        * @var DefinesOwnIdPropertiesInterface $type
71
        */
72 4
        $type = $this->type;
73 4
        $idkv = [];
74
75 4
        foreach (array_values($type::DaftObjectIdProperties()) as $i => $prop) {
76 4
            $idkv[$prop] = $id[$i];
77 4
            if (is_bool($idkv[$prop])) {
78 4
                $idkv[$prop] = $idkv[$prop] ? 1 : 0;
79
            }
80
        }
81
82 4
        $this->db->delete($this->DaftObjectDatabaseTable(), $idkv);
83
84 4
        $this->ForgetDaftObjectById($id);
85 4
    }
86
87
    abstract protected function DaftObjectDatabaseTable() : string;
88
89
    /**
90
    * @return string[]
91
    */
92 4
    protected function RememberDaftObjectDataCols(DaftObject $object, bool $exists) : array
93
    {
94 4
        $cols = $object::DaftObjectExportableProperties();
95 4
        if ($exists) {
96 4
            $changed = $object->ChangedProperties();
97 4
            $cols = array_filter(
98 4
                $cols,
99 4
                function (string $prop) use ($changed) : bool {
100 4
                    return in_array($prop, $changed, true);
101 4
                }
102
            );
103
        }
104
105 4
        return $cols;
106
    }
107
108
    /**
109
    * @return array<string, mixed>
110
    */
111 4
    protected function RememberDaftObjectDataValues(DaftObject $object, bool $exists) : array
112
    {
113 4
        $values = [];
114 4
        $cols = $this->RememberDaftObjectDataCols($object, $exists);
115 4
        foreach ($cols as $col) {
116 4
            $values[$col] = $object->$col;
117 4
            if (is_bool($values[$col])) {
118 4
                $values[$col] = $values[$col] ? 1 : 0;
119
            }
120
        }
121
122 4
        return $values;
123
    }
124
125 4
    protected function RememberDaftObjectDataUpdate(bool $exists, array $id, array $values) : void
126
    {
127 4
        if (count($values) > 0) {
128 4
            if (false === $exists) {
129 4
                $this->db->insert($this->DaftObjectDatabaseTable(), $values);
130
            } else {
131 4
                $this->db->update($this->DaftObjectDatabaseTable(), $values, $id);
132
            }
133
        }
134 4
    }
135
136 4
    protected function RememberDaftObjectData(DefinesOwnIdPropertiesInterface $object) : void
137
    {
138 4
        $id = [];
139
140 4
        foreach ($object::DaftObjectIdProperties() as $prop) {
141 4
            $id[$prop] = $object->$prop;
142
        }
143
144 4
        $this->db->tryFlatTransaction(function () use ($id, $object) : void {
145 4
            $exists = $this->DaftObjectExistsInDatabase($id);
146 4
            $values = $this->RememberDaftObjectDataValues($object, $exists);
147 4
            $this->RememberDaftObjectDataUpdate($exists, $id, $values);
148 4
        });
149 4
    }
150
151
    /**
152
    * @param mixed $id
153
    */
154 4
    protected function RecallDaftObjectFromData($id) : ? DaftObject
155
    {
156 4
        $type = $this->type;
157 4
        $idkv = [];
158
159 4
        if (is_scalar($id) && 1 === count($type::DaftObjectIdProperties())) {
160
            $id = [$id];
161
        }
162
163 4
        foreach (array_values($type::DaftObjectIdProperties()) as $i => $prop) {
164 4
            $idkv[$prop] = $id[$i];
165
        }
166
167 4
        if (true === $this->DaftObjectExistsInDatabase($idkv)) {
168 4
            $where = [];
169 4
            foreach (array_keys($idkv) as $col) {
170 4
                $where[] = $this->db->escapeIdentifier($col) . ' = ?';
171
            }
172
173 4
            $data = $this->db->safeQuery(
174
                (
175
                    'SELECT * FROM ' .
176 4
                    $this->db->escapeIdentifier($this->DaftObjectDatabaseTable()) .
177 4
                    ' WHERE ' .
178 4
                    implode(' AND ', $where) .
179 4
                    ' LIMIT 1'
180
                ),
181 4
                array_values($idkv)
182
            );
183
184
            /**
185
            * @var DefinesOwnIdPropertiesInterface $out
186
            */
187 4
            $out = new $type($data[0]);
188
189 4
            return $out;
190
        }
191
192 4
        return null;
193
    }
194
195 4
    private function DaftObjectExistsInDatabase(array $id) : bool
196
    {
197 4
        $where = [];
198 4
        foreach (array_keys($id) as $col) {
199 4
            $where[] = $this->db->escapeIdentifier($col) . ' = ?';
200
        }
201
202
        return
203 4
            (int) $this->db->single(
204
                (
205
                    'SELECT COUNT(*) FROM ' .
206 4
                    $this->db->escapeIdentifier($this->DaftObjectDatabaseTable()) .
207 4
                    ' WHERE ' .
208 4
                    implode(' AND ', $where)
209
                ),
210 4
                array_values($id)
211 4
            ) >= 1;
212
    }
213
}
214