Completed
Branch master (6d30bf)
by Philip
13:30
created

AbstractData::getManyFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CRUDlex;
13
14
use League\Flysystem\FilesystemInterface;
15
16
/**
17
 * The abstract class for reading and writing data.
18
 */
19
abstract class AbstractData
20
{
21
22
    /**
23
     * Return value on successful deletion.
24
     */
25
    const DELETION_SUCCESS = 0;
26
27
    /**
28
     * Return value on failed deletion due to existing references.
29
     */
30
    const DELETION_FAILED_STILL_REFERENCED = 1;
31
32
    /**
33
     * Return value on failed deletion due to a failed before delete event.
34
     */
35
    const DELETION_FAILED_EVENT = 2;
36
37
    /**
38
     * Holds the entity definition.
39
     * @var EntityDefinition
40
     */
41
    protected $definition;
42
43
    /**
44
     * Holds the filesystem.
45
     * @var FilesystemInterface
46
     */
47
    protected $filesystem;
48
49
    /**
50
     * Holds the events.
51
     * @var EntityEvents
52
     */
53
    protected $events;
54
55
    /**
56
     * Performs the actual deletion.
57
     *
58
     * @param Entity $entity
59
     * the id of the entry to delete
60
     * @param boolean $deleteCascade
61
     * whether to delete children and subchildren
62
     *
63
     * @return integer
64
     * true on successful deletion
65
     */
66
    abstract protected function doDelete(Entity $entity, $deleteCascade);
67
68
    /**
69
     * Creates an Entity from the raw data array with the field name
70
     * as keys and field values as values.
71
     *
72
     * @param array $row
73
     * the array with the raw data
74
     *
75
     * @return Entity
76
     * the entity containing the array data then
77
     */
78 33
    protected function hydrate(array $row)
79
    {
80 33
        $fieldNames = $this->definition->getFieldNames(true);
81 33
        $entity     = new Entity($this->definition);
82 33
        foreach ($fieldNames as $fieldName) {
83 33
            $entity->set($fieldName, $row[$fieldName]);
84
        }
85 33
        return $entity;
86
    }
87
88
    /**
89
     * Enriches an entity with metadata:
90
     * id, version, created_at, updated_at
91
     *
92
     * @param mixed $id
93
     * the id of the entity to enrich
94
     * @param Entity $entity
95
     * the entity to enrich
96
     */
97 33
    protected function enrichEntityWithMetaData($id, Entity $entity)
98
    {
99 33
        $entity->set('id', $id);
100 33
        $createdEntity = $this->get($entity->get('id'));
101 33
        $entity->set('version', $createdEntity->get('version'));
102 33
        $entity->set('created_at', $createdEntity->get('created_at'));
103 33
        $entity->set('updated_at', $createdEntity->get('updated_at'));
104 33
    }
105
106
    /**
107
     * Gets the many-to-many fields.
108
     *
109
     * @return array|\string[]
110
     * the many-to-many fields
111
     */
112 34
    protected function getManyFields()
113
    {
114 34
        $fields = $this->definition->getFieldNames(true);
115
        return array_filter($fields, function($field) {
116 34
            return $this->definition->getType($field) === 'many';
117 34
        });
118
    }
119
120
    /**
121
     * Gets all form fields including the many-to-many-ones.
122
     *
123
     * @return array
124
     * all form fields
125
     */
126 33
    protected function getFormFields()
127
    {
128 33
        $manyFields = $this->getManyFields();
129 33
        $formFields = [];
130 33
        foreach ($this->definition->getEditableFieldNames() as $field) {
131 33
            if (!in_array($field, $manyFields)) {
132 33
                $formFields[] = $field;
133
            }
134
        }
135 33
        return $formFields;
136
    }
137
138
    /**
139
     * Performs the cascading children deletion.
140
     *
141
     * @param integer $id
142
     * the current entities id
143
     * @param boolean $deleteCascade
144
     * whether to delete children and sub children
145
     *
146
     * @return integer
147
     * returns one of:
148
     * - AbstractData::DELETION_SUCCESS -> successful deletion
149
     * - AbstractData::DELETION_FAILED_STILL_REFERENCED -> failed deletion due to existing references
150
     * - AbstractData::DELETION_FAILED_EVENT -> failed deletion due to a failed before delete event
151
     */
152 3
    protected function deleteChildren($id, $deleteCascade)
153
    {
154 3
        foreach ($this->definition->getChildren() as $childArray) {
155 3
            $childData = $this->definition->getService()->getData($childArray[2]);
156 3
            $children  = $childData->listEntries([$childArray[1] => $id]);
157 3
            foreach ($children as $child) {
158 2
                $result = $childData->events->shouldExecute($child, 'before', 'delete');
159 2
                if (!$result) {
160 1
                    return static::DELETION_FAILED_EVENT;
161
                }
162 2
                $childData->doDelete($child, $deleteCascade);
163 3
                $childData->events->shouldExecute($child, 'after', 'delete');
164
            }
165
        }
166 3
        return static::DELETION_SUCCESS;
167
    }
168
169
    /**
170
     * Gets an array of reference ids for the given entities.
171
     *
172
     * @param array $entities
173
     * the entities to extract the ids
174
     * @param string $field
175
     * the reference field
176
     *
177
     * @return array
178
     * the extracted ids
179
     */
180 21
    protected function getReferenceIds(array $entities, $field)
181
    {
182
        $ids = array_map(function(Entity $entity) use ($field) {
183 21
            $id = $entity->get($field);
184 21
            return is_array($id) ? $id['id'] : $id;
185 21
        }, $entities);
186 21
        return $ids;
187
    }
188
189
    /**
190
     * Performs the persistence of the given entity as new entry in the datasource.
191
     *
192
     * @param Entity $entity
193
     * the entity to persist
194
     *
195
     * @return boolean
196
     * true on successful creation
197
     */
198
    abstract protected function doCreate(Entity $entity);
0 ignored issues
show
Coding Style introduced by
function doCreate() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
199
200
    /**
201
     * Performs the updates of an existing entry in the datasource having the same id.
202
     *
203
     * @param Entity $entity
204
     * the entity with the new data
205
     *
206
     * @return boolean
207
     * true on successful update
208
     */
209
    abstract protected function doUpdate(Entity $entity);
0 ignored issues
show
Coding Style introduced by
function doUpdate() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
210
211
    /**
212
     * Gets the events instance.
213
     *
214
     * @return EntityEvents
215
     * the events instance
216
     */
217 13
    public function getEvents()
218
    {
219 13
        return $this->events;
220
    }
221
222
    /**
223
     * Gets the entity with the given id.
224
     *
225
     * @param string $id
226
     * the id
227
     *
228
     * @return Entity
229
     * the entity belonging to the id or null if not existant
230
     *
231
     * @return void
232
     */
233
    abstract public function get($id);
234
235
    /**
236
     * Gets a list of entities fullfilling the given filter or all if no
237
     * selection was given.
238
     *
239
     * @param array $filter
240
     * the filter all resulting entities must fulfill, the keys as field names
241
     * @param array $filterOperators
242
     * the operators of the filter like "=" defining the full condition of the field
243
     * @param integer|null $skip
244
     * if given and not null, it specifies the amount of rows to skip
245
     * @param integer|null $amount
246
     * if given and not null, it specifies the maximum amount of rows to retrieve
247
     * @param string|null $sortField
248
     * if given and not null, it specifies the field to sort the entries
249
     * @param boolean|null $sortAscending
250
     * if given and not null, it specifies that the sort order is ascending,
251
     * descending else
252
     *
253
     * @return Entity[]
254
     * the entities fulfilling the filter or all if no filter was given
255
     */
256
    abstract public function listEntries(array $filter = [], array $filterOperators = [], $skip = null, $amount = null, $sortField = null, $sortAscending = null);
257
258
    /**
259
     * Persists the given entity as new entry in the datasource.
260
     *
261
     * @param Entity $entity
262
     * the entity to persist
263
     *
264
     * @return boolean
265
     * true on successful creation
266
     */
267 33 View Code Duplication
    public function create(Entity $entity)
0 ignored issues
show
Coding Style introduced by
function create() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
268
    {
269 33
        $result = $this->events->shouldExecute($entity, 'before', 'create');
270 33
        if (!$result) {
271 2
            return false;
272
        }
273 33
        $result = $this->doCreate($entity);
274 33
        $this->events->shouldExecute($entity, 'after', 'create');
275 33
        return $result;
276
    }
277
278
    /**
279
     * Updates an existing entry in the datasource having the same id.
280
     *
281
     * @param Entity $entity
282
     * the entity with the new data
283
     *
284
     * @return boolean
285
     * true on successful update
286
     */
287 13 View Code Duplication
    public function update(Entity $entity)
0 ignored issues
show
Coding Style introduced by
function update() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
    {
289 13
        if (!$this->events->shouldExecute($entity, 'before', 'update')) {
290 2
            return false;
291
        }
292 13
        $result = $this->doUpdate($entity);
293 13
        $this->events->shouldExecute($entity, 'after', 'update');
294 13
        return $result;
295
    }
296
297
    /**
298
     * Deletes an entry from the datasource.
299
     *
300
     * @param Entity $entity
301
     * the entity to delete
302
     *
303
     * @return integer
304
     * returns one of:
305
     * - AbstractData::DELETION_SUCCESS -> successful deletion
306
     * - AbstractData::DELETION_FAILED_STILL_REFERENCED -> failed deletion due to existing references
307
     * - AbstractData::DELETION_FAILED_EVENT -> failed deletion due to a failed before delete event
308
     */
309 4
    public function delete($entity)
310
    {
311 4
        $result = $this->events->shouldExecute($entity, 'before', 'delete');
312 4
        if (!$result) {
313 2
            return static::DELETION_FAILED_EVENT;
314
        }
315 4
        $result = $this->doDelete($entity, $this->definition->isDeleteCascade());
316 4
        $this->events->shouldExecute($entity, 'after', 'delete');
317 4
        return $result;
318
    }
319
320
    /**
321
     * Gets ids and names of a table. Used for building up the dropdown box of
322
     * reference type fields for example.
323
     *
324
     * @param string $entity
325
     * the entity
326
     * @param string $nameField
327
     * the field defining the name of the rows
328
     *
329
     * @return array
330
     * an array with the ids as key and the names as values
331
     */
332
    abstract public function getIdToNameMap($entity, $nameField);
333
334
    /**
335
     * Retrieves the amount of entities in the datasource fulfilling the given
336
     * parameters.
337
     *
338
     * @param string $table
339
     * the table to count in
340
     * @param array $params
341
     * an array with the field names as keys and field values as values
342
     * @param array $paramsOperators
343
     * the operators of the parameters like "=" defining the full condition of the field
344
     * @param boolean $excludeDeleted
345
     * false, if soft deleted entries in the datasource should be counted, too
346
     *
347
     * @return integer
348
     * the count fulfilling the given parameters
349
     */
350
    abstract public function countBy($table, array $params, array $paramsOperators, $excludeDeleted);
351
352
    /**
353
     * Checks whether a given set of ids is assigned to any entity exactly
354
     * like it is given (no subset, no superset).
355
     *
356
     * @param string $field
357
     * the many field
358
     * @param array $thatIds
359
     * the id set to check
360
     * @param string|null $excludeId
361
     * one optional own id to exclude from the check
362
     *
363
     * @return boolean
364
     * true if the set of ids exists for an entity
365
     */
366
    abstract public function hasManySet($field, array $thatIds, $excludeId = null);
367
368
    /**
369
     * Gets the EntityDefinition instance.
370
     *
371
     * @return EntityDefinition
372
     * the definition instance
373
     */
374 78
    public function getDefinition()
375
    {
376 78
        return $this->definition;
377
    }
378
379
    /**
380
     * Creates a new, empty entity instance having all fields prefilled with
381
     * null or the defined value in case of fixed fields.
382
     *
383
     * @return Entity
384
     * the newly created entity
385
     */
386 38
    public function createEmpty()
387
    {
388 38
        $entity = new Entity($this->definition);
389 38
        $fields = $this->definition->getEditableFieldNames();
390 38
        foreach ($fields as $field) {
391 38
            $value = null;
392 38
            if ($this->definition->getType($field) == 'fixed') {
393 36
                $value = $this->definition->getField($field, 'value');
394
            }
395 38
            $entity->set($field, $value);
396
        }
397 38
        $entity->set('id', null);
398 38
        return $entity;
399
    }
400
401
402
}
403