Completed
Push — master ( b45ad0...170fbf )
by SignpostMarv
03:25 queued 27s
created

RememberDaftObjectDataUpdate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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