Completed
Push — master ( 085b0c...5fa401 )
by
unknown
02:48
created

AttachmentAwareTrait   C

Complexity

Total Complexity 53

Size/Duplication

Total Lines 494
Duplicated Lines 2.83 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 53
lcom 1
cbo 3
dl 14
loc 494
rs 6.96
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
F getAttachments() 14 181 26
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
A attachmentWidget() 0 4 1
A setAttachmentWidget() 0 6 1
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-admin'
11
use Charcoal\Admin\Widget\AttachmentWidget;
12
13
// From 'charcoal-attachment'
14
use Charcoal\Attachment\Interfaces\AttachableInterface;
15
use Charcoal\Attachment\Interfaces\AttachmentAwareInterface;
16
use Charcoal\Attachment\Interfaces\AttachmentContainerInterface;
17
18
use Charcoal\Attachment\Object\Join;
19
use Charcoal\Attachment\Object\Attachment;
20
21
/**
22
 * Provides support for attachments to objects.
23
 *
24
 * Used by objects that can have an attachment to other objects.
25
 * This is the glue between the {@see Join} object and the current object.
26
 *
27
 * Abstract method needs to be implemented.
28
 *
29
 * Implementation of {@see \Charcoal\Attachment\Interfaces\AttachmentAwareInterface}
30
 *
31
 * ## Required Services
32
 *
33
 * - "model/factory" — {@see \Charcoal\Model\ModelFactory}
34
 * - "model/collection/loader" — {@see \Charcoal\Loader\CollectionLoader}
35
 */
36
trait AttachmentAwareTrait
37
{
38
    /**
39
     * A store of cached attachments, by ID.
40
     *
41
     * @var Attachment[] $attachmentCache
42
     */
43
    protected static $attachmentCache = [];
44
45
    /**
46
     * Store a collection of node objects.
47
     *
48
     * @var Collection|Attachment[]
49
     */
50
    protected $attachments = [];
51
52
    /**
53
     * Store the widget instance currently displaying attachments.
54
     *
55
     * @var AttachmentWidget
56
     */
57
    protected $attachmentWidget;
58
59
    /**
60
     * Retrieve the objects associated to the current object.
61
     *
62
     * @param  array|string|null $group  Filter the attachments by a group identifier.
63
     *                                   When an array, filter the attachments by a options list.
64
     * @param  string|null       $type   Filter the attachments by type.
65
     * @param  callable|null     $before Process each attachment before applying data.
66
     * @param  callable|null     $after  Process each attachment after applying data.
67
     * @throws InvalidArgumentException If the $group or $type is invalid.
68
     * @return Collection|Attachment[]
69
     */
70
    public function getAttachments(
71
        $group = null,
72
        $type = null,
73
        callable $before = null,
74
        callable $after = null
75
    ) {
76
        if (is_array($group)) {
77
            $options = $group;
78
        } else {
79
            if ($group !== null) {
80
                $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...
81
                    'AttachmentAwareTrait::attachments() parameters are deprecated. '.
82
                    'An array of parameters should be used.',
83
                    [ 'package' => 'locomotivemtl/charcoal-attachment' ]
84
                );
85
            }
86
            $options = [
87
                'group'  => $group,
88
                'type'   => $type,
89
                'before' => $before,
90
                'after'  => $after,
91
            ];
92
        }
93
94
        $options = $this->parseAttachmentOptions($options);
95
        extract($options);
96
97 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...
98
            if (!is_string($group)) {
99
                throw new InvalidArgumentException(sprintf(
100
                    'The "group" must be a string, received %s',
101
                    is_object($group) ? get_class($group) : gettype($group)
102
                ));
103
            }
104
        }
105
106
        if ($type !== 0) {
107 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...
108
                throw new InvalidArgumentException(sprintf(
109
                    'The "type" must be a string, received %s',
110
                    is_object($type) ? get_class($type) : gettype($type)
111
                ));
112
            }
113
114
            $type = preg_replace('/([a-z])([A-Z])/', '$1-$2', $type);
115
            $type = strtolower(str_replace('\\', '/', $type));
116
        }
117
118
        if (isset($this->attachments[$group][$type])) {
119
            return $this->attachments[$group][$type];
120
        }
121
122
        $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...
123
        $objId   = $this->id();
124
125
        $joinProto = $this->modelFactory()->get(Join::class);
126
        $joinTable = $joinProto->source()->table();
127
128
        $attProto = $this->modelFactory()->get(Attachment::class);
129
        $attTable = $attProto->source()->table();
130
131
        if (!$attProto->source()->tableExists() || !$joinProto->source()->tableExists()) {
132
            return [];
133
        }
134
135
        $widget = $this->attachmentWidget();
136
137
        $query = sprintf('
138
            SELECT
139
                attachment.*,
140
                joined.attachment_id AS attachment_id,
141
                joined.position AS position
142
            FROM
143
                `%s` AS attachment
144
            LEFT JOIN
145
                `%s` AS joined
146
            ON
147
                joined.attachment_id = attachment.id
148
            WHERE
149
                1 = 1', $attTable, $joinTable);
150
151
        /** Disable `active` check in admin, or according to $isActive value */
152
        if (!$widget instanceof AttachmentWidget && $isActive === true) {
153
            $query .= '
154
            AND
155
                attachment.active = 1';
156
        }
157
158
        if ($type) {
159
            $query .= sprintf('
160
            AND
161
                attachment.type = "%s"', $type);
162
        }
163
164
        $query .= sprintf('
165
            AND
166
                joined.object_type = "%s"
167
            AND
168
                joined.object_id = "%s"', $objType, $objId);
169
170
        if ($group) {
171
            $query .= sprintf('
172
            AND
173
                joined.group = "%s"', $group);
174
        }
175
176
        $query .= '
177
            ORDER BY joined.position';
178
179
        $loader = $this->collectionLoader();
180
        $loader->setModel($attProto);
181
        $loader->setDynamicTypeField('type');
182
183
        if ($widget instanceof AttachmentWidget) {
184
            $callable = function (&$att) use ($widget, $before) {
185
                if ($this instanceof AttachableInterface) {
186
                    $att->setContainerObj($this);
187
                }
188
189
                if ($att instanceof AttachmentAwareInterface) {
190
                    $att['attachment_widget'] = $widget;
191
                }
192
193
                $kind = $att->type();
194
                $attachables = $widget->attachableObjects();
195
196
                if (isset($attachables[$kind]['data'])) {
197
                    $att->setData($attachables[$kind]['data']);
198
                }
199
200
                if (!$att->rawHeading()) {
201
                    $att->setHeading($widget->attachmentHeading());
202
                }
203
204
                if (!$att->rawPreview()) {
205
                    $att->setPreview($widget->attachmentPreview());
206
                }
207
208
                $att->isPresentable(true);
209
210
                /** Not Sure if we want to present the attachment for backend preview.
211
                 * Might want to have a second presenter key on attachment model
212
                 * so we can supply either the same presenter,
213
                 * another one or none at all.
214
                 */
215
                // if ($att->presenter() !== null) {
216
                //         $att = $this->modelFactory()
217
                //                     ->create($att->presenterClass())
218
                //                     ->setData($att->flatData());
219
                // }
220
221
                if ($before !== null) {
222
                    call_user_func_array($before, [ &$att ]);
223
                }
224
            };
225
        } else {
226
            $callable = function (&$att) use ($before) {
227
                if ($this instanceof AttachableInterface) {
228
                    $att->setContainerObj($this);
229
                }
230
231
                $att->isPresentable(true);
232
233
                if ($att->presenter() !== null) {
234
                    $att = $this->modelFactory()
235
                                ->create($att->presenter())
236
                                ->setData($att->flatData());
237
                }
238
239
                if ($before !== null) {
240
                    call_user_func_array($before, [ &$att ]);
241
                }
242
            };
243
        }
244
245
        $collection = $loader->loadFromQuery($query, $after, $callable->bindTo($this));
246
247
        $this->attachments[$group][$type] = $collection;
248
249
        return $this->attachments[$group][$type];
250
    }
251
252
    /**
253
     * Determine if the current object has any nodes.
254
     *
255
     * @return boolean Whether $this has any nodes (TRUE) or not (FALSE).
256
     */
257
    public function hasAttachments()
258
    {
259
        return !!($this->numAttachments());
260
    }
261
262
    /**
263
     * Count the number of nodes associated to the current object.
264
     *
265
     * @return integer
266
     */
267
    public function numAttachments()
268
    {
269
        return count($this->getAttachments([
270
            'group' => null
271
        ]));
272
    }
273
274
    /**
275
     * Attach an node to the current object.
276
     *
277
     * @param  AttachableInterface|ModelInterface $attachment An attachment or object.
278
     * @param  string                             $group      Attachment group, defaults to contents.
279
     * @return boolean|self
280
     */
281
    public function addAttachment($attachment, $group = 'contents')
282
    {
283
        if (!$attachment instanceof AttachableInterface && !$attachment instanceof ModelInterface) {
284
            return false;
285
        }
286
287
        $join = $this->modelFactory()->create(Join::class);
288
289
        $objId   = $this->id();
290
        $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...
291
        $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...
292
293
        $join->setAttachmentId($attId);
294
        $join->setObjectId($objId);
295
        $join->setGroup($group);
296
        $join->setObjectType($objType);
297
298
        $join->save();
299
300
        return $this;
301
    }
302
303
    /**
304
     * Remove all joins linked to a specific attachment.
305
     *
306
     * @deprecated in favour of AttachmentAwareTrait::removeAttachmentJoins()
307
     * @return boolean
308
     */
309
    public function removeJoins()
310
    {
311
        $this->logger->warning(
312
            'AttachmentAwareTrait::removeJoins() is deprecated. '.
313
            'Use AttachmentAwareTrait::removeAttachmentJoins() instead.',
314
            [ 'package' => 'locomotivemtl/charcoal-attachment' ]
315
        );
316
317
        return $this->removeAttachmentJoins();
318
    }
319
320
    /**
321
     * Remove all joins linked to a specific attachment.
322
     *
323
     * @return boolean
324
     */
325
    public function removeAttachmentJoins()
326
    {
327
        $joinProto = $this->modelFactory()->get(Join::class);
328
329
        $loader = $this->collectionLoader();
330
        $loader
331
            ->setModel($joinProto)
332
            ->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...
333
            ->addFilter('object_id', $this->id());
334
335
        $collection = $loader->load();
336
337
        foreach ($collection as $obj) {
338
            $obj->delete();
339
        }
340
341
        return true;
342
    }
343
344
    /**
345
     * Delete the objects associated to the current object.
346
     *
347
     * @param  array $options Filter the attachments by an option list.
348
     * @return boolean
349
     */
350
    public function deleteAttachments(array $options = [])
351
    {
352
        foreach ($this->getAttachments($options) as $attachment) {
353
            $attachment->delete();
354
        }
355
356
        return true;
357
    }
358
359
    /**
360
     * Retrieve the attachment widget.
361
     *
362
     * @return AttachmentWidget
363
     */
364
    protected function attachmentWidget()
365
    {
366
        return $this->attachmentWidget;
367
    }
368
369
    /**
370
     * Set the attachment widget.
371
     *
372
     * @param  AttachmentWidget $widget The widget displaying attachments.
373
     * @return string
374
     */
375
    protected function setAttachmentWidget(AttachmentWidget $widget)
376
    {
377
        $this->attachmentWidget = $widget;
378
379
        return $this;
380
    }
381
382
    /**
383
     * Available attachment obj_type related to the current object.
384
     * This goes throught the entire forms / form groups, starting from the
385
     * dashboard widgets.
386
     * Returns an array of object classes by group
387
     * [
388
     *    group : [
389
     *        'object\type',
390
     *        'object\type2',
391
     *        'object\type3'
392
     *    ]
393
     * ]
394
     * @return array Attachment obj_types.
395
     */
396
    public function attachmentObjTypes()
397
    {
398
        $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...
399
        $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...
400
        $editDashboard = $dashboards[$defaultEditDashboard];
401
        $widgets = $editDashboard['widgets'];
402
403
        $formIdent = '';
404
        foreach ($widgets as $ident => $val) {
405
            if ($val['type'] == 'charcoal/admin/widget/object-form') {
406
                $formIdent = $val['form_ident'];
407
            }
408
        }
409
410
        if (!$formIdent) {
411
            // No good!
412
            return [];
413
        }
414
415
        // Current form
416
        $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...
417
418
        // Setted form gruops
419
        $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...
420
421
        // Current form groups
422
        $groups = $form['groups'];
423
424
        $attachmentObjects = [];
425
        foreach ($groups as $groupIdent => $group) {
426
            if (isset($formGroups[$groupIdent])) {
427
                $group = array_replace_recursive(
428
                    $formGroups[$groupIdent],
429
                    $group
430
                );
431
            }
432
433
            if (isset($group['attachable_objects'])) {
434
                $attachmentObjects[$group['group']] = [];
435
                foreach ($group['attachable_objects'] as $type => $content) {
436
                    $attachmentObjects[$group['group']][] = $type;
437
                }
438
            }
439
        }
440
441
        return $attachmentObjects;
442
    }
443
444
    /**
445
     * Parse a given options for loading a collection of attachments.
446
     *
447
     * @param  array $options A list of options.
448
     *    Option keys not present in {@see self::getDefaultAttachmentOptions() default options}
449
     *    are rejected.
450
     * @return array
451
     */
452
    protected function parseAttachmentOptions(array $options)
453
    {
454
        $defaults = $this->getDefaultAttachmentOptions();
455
456
        $options = array_intersect_key($options, $defaults);
457
        $options = array_filter($options, [ $this, 'filterAttachmentOption' ], ARRAY_FILTER_USE_BOTH);
458
        $options = array_replace($defaults, $options);
459
460
        return $options;
461
    }
462
463
    /**
464
     * Parse a given options for loading a collection of attachments.
465
     *
466
     * @param  mixed  $val The option value.
467
     * @param  string $key The option key.
468
     * @return boolean Return TRUE if the value is preserved. Otherwise FALSE.
469
     */
470
    protected function filterAttachmentOption($val, $key)
471
    {
472
        if ($val === null) {
473
            return false;
474
        }
475
476
        switch ($key) {
477
            case 'isActive':
478
                return is_bool($val);
479
480
            case 'before':
481
            case 'after':
482
                return is_callable($val);
483
        }
484
485
        return true;
486
    }
487
488
    /**
489
     * Retrieve the default options for loading a collection of attachments.
490
     *
491
     * @return array
492
     */
493
    protected function getDefaultAttachmentOptions()
494
    {
495
        return [
496
            'group'    => 0,
497
            'type'     => 0,
498
            'before'   => null,
499
            'after'    => null,
500
            'isActive' => true
501
        ];
502
    }
503
504
505
506
    // Abstract Methods
507
    // =========================================================================
508
509
    /**
510
     * Retrieve the object's unique ID.
511
     *
512
     * @return mixed
513
     */
514
    abstract public function id();
515
516
    /**
517
     * Retrieve the object model factory.
518
     *
519
     * @return \Charcoal\Factory\FactoryInterface
520
     */
521
    abstract public function modelFactory();
522
523
    /**
524
     * Retrieve the model collection loader.
525
     *
526
     * @return \Charcoal\Loader\CollectionLoader
527
     */
528
    abstract public function collectionLoader();
529
}
530