Passed
Push — master ( f11b74...94359f )
by
unknown
03:34
created

AttachmentAwareTrait   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 417
Duplicated Lines 3.36 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 43
lcom 1
cbo 2
dl 14
loc 417
rs 8.96
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
F getAttachments() 14 134 18
A hasAttachments() 0 4 1
A numAttachments() 0 6 1
A addAttachment() 0 21 3
A removeJoins() 0 10 1
A removeAttachmentJoins() 0 18 2
A deleteAttachments() 0 8 2
B attachmentObjTypes() 0 47 8
A parseAttachmentOptions() 0 10 1
A filterAttachmentOption() 0 17 5
A getDefaultAttachmentOptions() 0 10 1
id() 0 1 ?
modelFactory() 0 1 ?
collectionLoader() 0 1 ?

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AttachmentAwareTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AttachmentAwareTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Charcoal\Attachment\Traits;
4
5
use InvalidArgumentException;
6
7
// From 'charcoal-core'
8
use Charcoal\Model\ModelInterface;
9
10
// From 'charcoal-attachment'
11
use Charcoal\Attachment\Interfaces\AttachableInterface;
12
use Charcoal\Attachment\Interfaces\AttachmentAwareInterface;
13
use Charcoal\Attachment\Interfaces\AttachmentContainerInterface;
14
15
use Charcoal\Attachment\Object\Join;
16
use Charcoal\Attachment\Object\Attachment;
17
18
/**
19
 * Provides support for attachments to objects.
20
 *
21
 * Used by objects that can have an attachment to other objects.
22
 * This is the glue between the {@see Join} object and the current object.
23
 *
24
 * Abstract method needs to be implemented.
25
 *
26
 * Implementation of {@see \Charcoal\Attachment\Interfaces\AttachmentAwareInterface}
27
 *
28
 * ## Required Services
29
 *
30
 * - "model/factory" — {@see \Charcoal\Model\ModelFactory}
31
 * - "model/collection/loader" — {@see \Charcoal\Loader\CollectionLoader}
32
 */
33
trait AttachmentAwareTrait
34
{
35
    /**
36
     * A store of cached attachments, by ID.
37
     *
38
     * @var Attachment[] $attachmentCache
39
     */
40
    protected static $attachmentCache = [];
41
42
    /**
43
     * Store a collection of node objects.
44
     *
45
     * @var Collection|Attachment[]
46
     */
47
    protected $attachments = [];
48
49
    /**
50
     * Retrieve the objects associated to the current object.
51
     *
52
     * @param  array|string|null $group  Filter the attachments by a group identifier.
53
     *                                   When an array, filter the attachments by a options list.
54
     * @param  string|null       $type   Filter the attachments by type.
55
     * @param  callable|null     $before Process each attachment before applying data.
56
     * @param  callable|null     $after  Process each attachment after applying data.
57
     * @throws InvalidArgumentException If the $group or $type is invalid.
58
     * @return Collection|Attachment[]
59
     */
60
    public function getAttachments(
61
        $group = null,
62
        $type = null,
63
        callable $before = null,
64
        callable $after = null
65
    ) {
66
        if (is_array($group)) {
67
            $options = $group;
68
        } else {
69
            if ($group !== null) {
70
                $this->logger->warning(
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
71
                    'AttachmentAwareTrait::getAttachments() parameters are deprecated. '.
72
                    'An array of parameters should be used.',
73
                    [ 'package' => 'locomotivemtl/charcoal-attachment' ]
74
                );
75
            }
76
            $options = [
77
                'group'  => $group,
78
                'type'   => $type,
79
                'before' => $before,
80
                'after'  => $after,
81
            ];
82
        }
83
84
        $options = $this->parseAttachmentOptions($options);
85
        extract($options);
86
87 View Code Duplication
        if ($group !== 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
88
            if (!is_string($group)) {
89
                throw new InvalidArgumentException(sprintf(
90
                    'The "group" must be a string, received %s',
91
                    is_object($group) ? get_class($group) : gettype($group)
92
                ));
93
            }
94
        }
95
96
        if ($type !== 0) {
97 View Code Duplication
            if (!is_string($type)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
98
                throw new InvalidArgumentException(sprintf(
99
                    'The "type" must be a string, received %s',
100
                    is_object($type) ? get_class($type) : gettype($type)
101
                ));
102
            }
103
104
            $type = preg_replace('/([a-z])([A-Z])/', '$1-$2', $type);
105
            $type = strtolower(str_replace('\\', '/', $type));
106
        }
107
108
        if (isset($this->attachments[$group][$type])) {
109
            return $this->attachments[$group][$type];
110
        }
111
112
        $objType = $this->objType();
0 ignored issues
show
Bug introduced by
The method objType() does not exist on Charcoal\Attachment\Traits\AttachmentAwareTrait. Did you maybe mean attachmentObjTypes()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
113
        $objId   = $this->id();
114
115
        $joinProto = $this->modelFactory()->get(Join::class);
116
        $joinTable = $joinProto->source()->table();
117
118
        $attProto = $this->modelFactory()->get(Attachment::class);
119
        $attTable = $attProto->source()->table();
120
121
        if (!$attProto->source()->tableExists() || !$joinProto->source()->tableExists()) {
122
            return [];
123
        }
124
125
        $query = sprintf('
126
            SELECT
127
                attachment.*,
128
                joined.attachment_id AS attachment_id,
129
                joined.position AS position
130
            FROM
131
                `%s` AS attachment
132
            LEFT JOIN
133
                `%s` AS joined
134
            ON
135
                joined.attachment_id = attachment.id
136
            WHERE
137
                1 = 1', $attTable, $joinTable);
138
139
        /** Disable `active` check in admin, or according to $isActive value */
140
        if ($isActive === true) {
141
            $query .= '
142
            AND
143
                attachment.active = 1';
144
        }
145
146
        if ($type) {
147
            $query .= sprintf('
148
            AND
149
                attachment.type = "%s"', $type);
150
        }
151
152
        $query .= sprintf('
153
            AND
154
                joined.object_type = "%s"
155
            AND
156
                joined.object_id = "%s"', $objType, $objId);
157
158
        if ($group) {
159
            $query .= sprintf('
160
            AND
161
                joined.group = "%s"', $group);
162
        }
163
164
        $query .= '
165
            ORDER BY joined.position';
166
167
        $loader = $this->collectionLoader();
168
        $loader->setModel($attProto);
169
        $loader->setDynamicTypeField('type');
170
171
        $callable = function (&$att) use ($before) {
172
            if ($this instanceof AttachableInterface) {
173
                $att->setContainerObj($this);
174
            }
175
176
            $att->isPresentable(true);
177
178
            if ($att->presenter() !== null) {
179
                $att = $this->modelFactory()
180
                            ->create($att->presenter())
181
                            ->setData($att->flatData());
182
            }
183
184
            if ($before !== null) {
185
                call_user_func_array($before, [ &$att ]);
186
            }
187
        };
188
        $collection = $loader->loadFromQuery($query, $after, $callable->bindTo($this));
189
190
        $this->attachments[$group][$type] = $collection;
191
192
        return $this->attachments[$group][$type];
193
    }
194
195
    /**
196
     * Determine if the current object has any nodes.
197
     *
198
     * @return boolean Whether $this has any nodes (TRUE) or not (FALSE).
199
     */
200
    public function hasAttachments()
201
    {
202
        return !!($this->numAttachments());
203
    }
204
205
    /**
206
     * Count the number of nodes associated to the current object.
207
     *
208
     * @return integer
209
     */
210
    public function numAttachments()
211
    {
212
        return count($this->getAttachments([
213
            'group' => null
214
        ]));
215
    }
216
217
    /**
218
     * Attach an node to the current object.
219
     *
220
     * @param  AttachableInterface|ModelInterface $attachment An attachment or object.
221
     * @param  string                             $group      Attachment group, defaults to contents.
222
     * @return boolean|self
223
     */
224
    public function addAttachment($attachment, $group = 'contents')
225
    {
226
        if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) {
227
            return false;
228
        }
229
230
        $join = $this->modelFactory()->create(Join::class);
231
232
        $objId   = $this->id();
233
        $objType = $this->objType();
0 ignored issues
show
Bug introduced by
The method objType() does not exist on Charcoal\Attachment\Traits\AttachmentAwareTrait. Did you maybe mean attachmentObjTypes()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
234
        $attId   = $attachment->id();
0 ignored issues
show
Bug introduced by
The method id does only exist in Charcoal\Model\ModelInterface, but not in Charcoal\Attachment\Interfaces\AttachableInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
235
236
        $join->setAttachmentId($attId);
237
        $join->setObjectId($objId);
238
        $join->setGroup($group);
239
        $join->setObjectType($objType);
240
241
        $join->save();
242
243
        return $this;
244
    }
245
246
    /**
247
     * Remove all joins linked to a specific attachment.
248
     *
249
     * @deprecated in favour of AttachmentAwareTrait::removeAttachmentJoins()
250
     * @return boolean
251
     */
252
    public function removeJoins()
253
    {
254
        $this->logger->warning(
255
            'AttachmentAwareTrait::removeJoins() is deprecated. '.
256
            'Use AttachmentAwareTrait::removeAttachmentJoins() instead.',
257
            [ 'package' => 'locomotivemtl/charcoal-attachment' ]
258
        );
259
260
        return $this->removeAttachmentJoins();
261
    }
262
263
    /**
264
     * Remove all joins linked to a specific attachment.
265
     *
266
     * @return boolean
267
     */
268
    public function removeAttachmentJoins()
269
    {
270
        $joinProto = $this->modelFactory()->get(Join::class);
271
272
        $loader = $this->collectionLoader();
273
        $loader
274
            ->setModel($joinProto)
275
            ->addFilter('object_type', $this->objType())
0 ignored issues
show
Bug introduced by
The method objType() does not exist on Charcoal\Attachment\Traits\AttachmentAwareTrait. Did you maybe mean attachmentObjTypes()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
276
            ->addFilter('object_id', $this->id());
277
278
        $collection = $loader->load();
279
280
        foreach ($collection as $obj) {
281
            $obj->delete();
282
        }
283
284
        return true;
285
    }
286
287
    /**
288
     * Delete the objects associated to the current object.
289
     *
290
     * @param  array $options Filter the attachments by an option list.
291
     * @return boolean
292
     */
293
    public function deleteAttachments(array $options = [])
294
    {
295
        foreach ($this->getAttachments($options) as $attachment) {
296
            $attachment->delete();
297
        }
298
299
        return true;
300
    }
301
302
    /**
303
     * Available attachment obj_type related to the current object.
304
     * This goes throught the entire forms / form groups, starting from the
305
     * dashboard widgets.
306
     * Returns an array of object classes by group
307
     * [
308
     *    group : [
309
     *        'object\type',
310
     *        'object\type2',
311
     *        'object\type3'
312
     *    ]
313
     * ]
314
     * @return array Attachment obj_types.
315
     */
316
    public function attachmentObjTypes()
317
    {
318
        $defaultEditDashboard = $this->metadata()->get('admin.default_edit_dashboard');
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
319
        $dashboards = $this->metadata()->get('admin.dashboards');
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
320
        $editDashboard = $dashboards[$defaultEditDashboard];
321
        $widgets = $editDashboard['widgets'];
322
323
        $formIdent = '';
324
        foreach ($widgets as $ident => $val) {
325
            if ($val['type'] == 'charcoal/admin/widget/object-form') {
326
                $formIdent = $val['form_ident'];
327
            }
328
        }
329
330
        if (!$formIdent) {
331
            // No good!
332
            return [];
333
        }
334
335
        // Current form
336
        $form = $this->metadata()->get('admin.forms.'.$formIdent);
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
337
338
        // Setted form gruops
339
        $formGroups = $this->metadata()->get('admin.form_groups');
0 ignored issues
show
Bug introduced by
It seems like metadata() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
340
341
        // Current form groups
342
        $groups = $form['groups'];
343
344
        $attachmentObjects = [];
345
        foreach ($groups as $groupIdent => $group) {
346
            if (isset($formGroups[$groupIdent])) {
347
                $group = array_replace_recursive(
348
                    $formGroups[$groupIdent],
349
                    $group
350
                );
351
            }
352
353
            if (isset($group['attachable_objects'])) {
354
                $attachmentObjects[$group['group']] = [];
355
                foreach ($group['attachable_objects'] as $type => $content) {
356
                    $attachmentObjects[$group['group']][] = $type;
357
                }
358
            }
359
        }
360
361
        return $attachmentObjects;
362
    }
363
364
    /**
365
     * Parse a given options for loading a collection of attachments.
366
     *
367
     * @param  array $options A list of options.
368
     *    Option keys not present in {@see self::getDefaultAttachmentOptions() default options}
369
     *    are rejected.
370
     * @return array
371
     */
372
    protected function parseAttachmentOptions(array $options)
373
    {
374
        $defaults = $this->getDefaultAttachmentOptions();
375
376
        $options = array_intersect_key($options, $defaults);
377
        $options = array_filter($options, [ $this, 'filterAttachmentOption' ], ARRAY_FILTER_USE_BOTH);
378
        $options = array_replace($defaults, $options);
379
380
        return $options;
381
    }
382
383
    /**
384
     * Parse a given options for loading a collection of attachments.
385
     *
386
     * @param  mixed  $val The option value.
387
     * @param  string $key The option key.
388
     * @return boolean Return TRUE if the value is preserved. Otherwise FALSE.
389
     */
390
    protected function filterAttachmentOption($val, $key)
391
    {
392
        if ($val === null) {
393
            return false;
394
        }
395
396
        switch ($key) {
397
            case 'isActive':
398
                return is_bool($val);
399
400
            case 'before':
401
            case 'after':
402
                return is_callable($val);
403
        }
404
405
        return true;
406
    }
407
408
    /**
409
     * Retrieve the default options for loading a collection of attachments.
410
     *
411
     * @return array
412
     */
413
    protected function getDefaultAttachmentOptions()
414
    {
415
        return [
416
            'group'    => 0,
417
            'type'     => 0,
418
            'before'   => null,
419
            'after'    => null,
420
            'isActive' => true
421
        ];
422
    }
423
424
425
426
    // Abstract Methods
427
    // =========================================================================
428
429
    /**
430
     * Retrieve the object's unique ID.
431
     *
432
     * @return mixed
433
     */
434
    abstract public function id();
435
436
    /**
437
     * Retrieve the object model factory.
438
     *
439
     * @return \Charcoal\Factory\FactoryInterface
440
     */
441
    abstract public function modelFactory();
442
443
    /**
444
     * Retrieve the model collection loader.
445
     *
446
     * @return \Charcoal\Loader\CollectionLoader
447
     */
448
    abstract public function collectionLoader();
449
}
450