Completed
Push — master ( fdf968...f297ee )
by SignpostMarv
04:51
created

RememberDaftObjectDataUpdate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

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