Completed
Push — master ( 92fe32...b0dd29 )
by Philip
06:20
created

AbstractData   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 384
Duplicated Lines 4.95 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 4
dl 19
loc 384
ccs 0
cts 108
cp 0
rs 10
c 0
b 0
f 0

20 Methods

Rating   Name   Duplication   Size   Complexity  
doDelete() 0 1 ?
doCreate() 0 1 ?
doUpdate() 0 1 ?
get() 0 1 ?
listEntries() 0 1 ?
getIdToNameMap() 0 1 ?
countBy() 0 1 ?
hasManySet() 0 1 ?
A hydrate() 0 9 2
A enrichEntityWithMetaData() 0 8 1
A getManyFields() 0 7 1
A getFormFields() 0 11 3
A deleteChildren() 0 16 4
A getEvents() 0 4 1
A create() 10 10 2
A update() 9 9 2
A delete() 0 10 2
A getDefinition() 0 4 1
A createEmpty() 0 14 3
A getReferenceIds() 0 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
    protected function hydrate(array $row)
79
    {
80
        $fieldNames = $this->definition->getFieldNames(true);
81
        $entity     = new Entity($this->definition);
82
        foreach ($fieldNames as $fieldName) {
83
            $entity->set($fieldName, $row[$fieldName]);
84
        }
85
        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
    protected function enrichEntityWithMetaData($id, Entity $entity)
98
    {
99
        $entity->set('id', $id);
100
        $createdEntity = $this->get($entity->get('id'));
101
        $entity->set('version', $createdEntity->get('version'));
102
        $entity->set('created_at', $createdEntity->get('created_at'));
103
        $entity->set('updated_at', $createdEntity->get('updated_at'));
104
    }
105
106
    /**
107
     * Gets the many-to-many fields.
108
     *
109
     * @return array|\string[]
110
     * the many-to-many fields
111
     */
112
    protected function getManyFields()
113
    {
114
        $fields = $this->definition->getFieldNames(true);
115
        return array_filter($fields, function($field) {
116
            return $this->definition->getType($field) === 'many';
117
        });
118
    }
119
120
    /**
121
     * Gets all form fields including the many-to-many-ones.
122
     *
123
     * @return array
124
     * all form fields
125
     */
126
    protected function getFormFields()
127
    {
128
        $manyFields = $this->getManyFields();
129
        $formFields = [];
130
        foreach ($this->definition->getEditableFieldNames() as $field) {
131
            if (!in_array($field, $manyFields)) {
132
                $formFields[] = $field;
133
            }
134
        }
135
        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
    protected function deleteChildren($id, $deleteCascade)
153
    {
154
        foreach ($this->definition->getChildren() as $childArray) {
155
            $childData = $this->definition->getService()->getData($childArray[2]);
156
            $children  = $childData->listEntries([$childArray[1] => $id]);
157
            foreach ($children as $child) {
158
                $result = $childData->events->shouldExecute($child, 'before', 'delete');
159
                if (!$result) {
160
                    return static::DELETION_FAILED_EVENT;
161
                }
162
                $childData->doDelete($child, $deleteCascade);
163
                $childData->events->shouldExecute($child, 'after', 'delete');
164
            }
165
        }
166
        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
    protected function getReferenceIds(array $entities, $field)
181
    {
182
        $ids = array_map(function(Entity $entity) use ($field) {
183
            $id = $entity->get($field);
184
            return is_array($id) ? $id['id'] : $id;
185
        }, $entities);
186
        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
    public function getEvents()
218
    {
219
        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 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
        $result = $this->events->shouldExecute($entity, 'before', 'create');
270
        if (!$result) {
271
            return false;
272
        }
273
        $result = $this->doCreate($entity);
274
        $this->events->shouldExecute($entity, 'after', 'create');
275
        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 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
        if (!$this->events->shouldExecute($entity, 'before', 'update')) {
290
            return false;
291
        }
292
        $result = $this->doUpdate($entity);
293
        $this->events->shouldExecute($entity, 'after', 'update');
294
        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
    public function delete($entity)
310
    {
311
        $result = $this->events->shouldExecute($entity, 'before', 'delete');
312
        if (!$result) {
313
            return static::DELETION_FAILED_EVENT;
314
        }
315
        $result = $this->doDelete($entity, $this->definition->isDeleteCascade());
316
        $this->events->shouldExecute($entity, 'after', 'delete');
317
        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
    public function getDefinition()
375
    {
376
        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
    public function createEmpty()
387
    {
388
        $entity = new Entity($this->definition);
389
        $fields = $this->definition->getEditableFieldNames();
390
        foreach ($fields as $field) {
391
            $value = null;
392
            if ($this->definition->getType($field) == 'fixed') {
393
                $value = $this->definition->getField($field, 'value');
394
            }
395
            $entity->set($field, $value);
396
        }
397
        $entity->set('id', null);
398
        return $entity;
399
    }
400
401
402
}
403