Completed
Push — master ( a4fd9c...40658a )
by Julito
13:50
created

ResourceNode   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 505
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 106
dl 0
loc 505
rs 8.48
c 1
b 0
f 0
wmc 49

34 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __toString() 0 3 1
A hasResourceFile() 0 3 1
A setResourceType() 0 5 1
A getResourceLinks() 0 3 1
A isCourseNode() 0 3 1
A isIllustrationNode() 0 3 1
A getResourceFile() 0 3 1
A getCourse() 0 3 1
A isResourceFileAVideo() 0 10 3
A getResourceType() 0 3 1
A getPathForDisplay() 0 3 1
A getChildren() 0 3 1
A getParent() 0 3 1
A convertPathForDisplay() 0 22 3
A isResourceFileAnImage() 0 10 3
A getPathForCreationLog() 0 3 1
A getCreator() 0 3 1
A getThumbnail() 0 29 4
A getId() 0 3 1
A setCreator() 0 5 1
A hasEditableContent() 0 10 3
A getPath() 0 3 1
A setParent() 0 5 1
A hasSession() 0 12 1
A setSlug() 0 9 2
A setResourceLinks() 0 5 1
A getLevel() 0 3 1
A getSlug() 0 3 1
A setId() 0 5 1
A setPathForCreationLog() 0 3 1
A getPathForDisplayRemoveBase() 0 5 1
A getIcon() 0 15 4
A setResourceFile() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like ResourceNode 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.

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 ResourceNode, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Entity\Resource;
5
6
use Chamilo\CoreBundle\Entity\Course;
7
use Chamilo\CoreBundle\Entity\Session;
8
use Chamilo\UserBundle\Entity\User;
9
use Doctrine\Common\Collections\ArrayCollection;
10
use Doctrine\Common\Collections\Criteria;
11
use Doctrine\ORM\Mapping as ORM;
12
use Gedmo\Mapping\Annotation as Gedmo;
13
use Gedmo\Timestampable\Traits\TimestampableEntity;
14
use Symfony\Component\Routing\RouterInterface;
15
use Symfony\Component\Validator\Constraints as Assert;
16
17
/**
18
 * Base entity for all resources.
19
 *
20
 * @ORM\Entity(repositoryClass="Chamilo\CoreBundle\Repository\ResourceNodeRepository")
21
 *
22
 * @ORM\Table(name="resource_node")
23
 *
24
 * @Gedmo\Tree(type="materializedPath")
25
 */
26
class ResourceNode
27
{
28
    use TimestampableEntity;
29
30
    public const PATH_SEPARATOR = '`';
31
32
    /**
33
     * @ORM\Id
34
     * @ORM\Column(type="integer")
35
     * @ORM\GeneratedValue(strategy="AUTO")
36
     */
37
    protected $id;
38
39
    /**
40
     * @Assert\NotBlank()
41
     *
42
     * @Gedmo\TreePathSource
43
     * @ORM\Column(name="slug", type="string", length=255, nullable=true)
44
     */
45
    protected $slug;
46
47
    /**
48
     * @ORM\ManyToOne(targetEntity="Chamilo\CoreBundle\Entity\Resource\ResourceType", inversedBy="resourceNodes")
49
     * @ORM\JoinColumn(name="resource_type_id", referencedColumnName="id", nullable=false)
50
     */
51
    protected $resourceType;
52
53
    /**
54
     * @ORM\OneToMany(targetEntity="Chamilo\CoreBundle\Entity\Resource\ResourceLink", mappedBy="resourceNode",
55
     *                                                                                cascade={"remove"})
56
     */
57
    protected $resourceLinks;
58
59
    /**
60
     * @var ResourceFile
61
     *
62
     * @ORM\OneToOne(targetEntity="Chamilo\CoreBundle\Entity\Resource\ResourceFile", inversedBy="resourceNode", orphanRemoval=true)
63
     * @ORM\JoinColumn(name="resource_file_id", referencedColumnName="id", onDelete="CASCADE")
64
     */
65
    protected $resourceFile;
66
67
    /**
68
     * @ORM\ManyToOne(
69
     *     targetEntity="Chamilo\UserBundle\Entity\User", inversedBy="resourceNodes"
70
     * )
71
     * @ORM\JoinColumn(name="creator_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
72
     */
73
    protected $creator;
74
75
    /**
76
     * @Gedmo\TreeParent
77
     *
78
     * @ORM\ManyToOne(
79
     *     targetEntity="Chamilo\CoreBundle\Entity\Resource\ResourceNode",
80
     *     inversedBy="children"
81
     * )
82
     * @ORM\JoinColumns({@ORM\JoinColumn(onDelete="CASCADE")})
83
     */
84
    protected $parent;
85
86
    /**
87
     * @Gedmo\TreeLevel
88
     *
89
     * @ORM\Column(name="level", type="integer", nullable=true)
90
     */
91
    protected $level;
92
93
    /**
94
     * @var ResourceNode[]
95
     *
96
     * @ORM\OneToMany(
97
     *     targetEntity="Chamilo\CoreBundle\Entity\Resource\ResourceNode",
98
     *     mappedBy="parent"
99
     * )
100
     * @ORM\OrderBy({"id" = "ASC"})
101
     */
102
    protected $children;
103
104
    /**
105
     * @Gedmo\TreePath(separator="`")
106
     *
107
     * @ORM\Column(name="path", type="string", length=3000, nullable=true)
108
     */
109
    protected $path;
110
111
    /**
112
     * Shortcut to access Course resource from ResourceNode.
113
     *
114
     * @ORM\OneToOne(targetEntity="Chamilo\CoreBundle\Entity\Course", mappedBy="resourceNode")
115
     */
116
    protected $course;
117
118
    /**
119
     * Shortcut to access Course resource from ResourceNode.
120
     *
121
     * @ORM\OneToOne(targetEntity="Chamilo\CoreBundle\Entity\Illustration", mappedBy="resourceNode")
122
     */
123
    protected $illustration;
124
125
    //protected $pathForCreationLog = '';
126
127
    /**
128
     * Constructor.
129
     */
130
    public function __construct()
131
    {
132
        $this->children = new ArrayCollection();
0 ignored issues
show
Documentation Bug introduced by
It seems like new Doctrine\Common\Collections\ArrayCollection() of type Doctrine\Common\Collections\ArrayCollection is incompatible with the declared type Chamilo\CoreBundle\Entity\Resource\ResourceNode[] of property $children.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
133
    }
134
135
    /**
136
     * @return string
137
     */
138
    public function __toString()
139
    {
140
        return (string) $this->getPathForDisplay();
141
    }
142
143
    /**
144
     * @return Course
145
     */
146
    public function getCourse(): ?Course
147
    {
148
        return $this->course;
149
    }
150
151
    public function isCourseNode(): bool
152
    {
153
        return null !== $this->course;
154
    }
155
156
    public function isIllustrationNode(): bool
157
    {
158
        return null !== $this->illustration;
159
    }
160
161
    /**
162
     * Returns the resource id.
163
     *
164
     * @return int
165
     */
166
    public function getId()
167
    {
168
        return $this->id;
169
    }
170
171
    /**
172
     * @param int $id
173
     *
174
     * @return $this
175
     */
176
    public function setId($id)
177
    {
178
        $this->id = $id;
179
180
        return $this;
181
    }
182
183
    /**
184
     * Returns the resource creator.
185
     *
186
     * @return User
187
     */
188
    public function getCreator(): ?User
189
    {
190
        return $this->creator;
191
    }
192
193
    public function setCreator(User $creator = null)
194
    {
195
        $this->creator = $creator;
196
197
        return $this;
198
    }
199
200
    /**
201
     * Returns the children resource instances.
202
     *
203
     * @return ArrayCollection
204
     */
205
    public function getChildren()
206
    {
207
        return $this->children;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->children returns the type Chamilo\CoreBundle\Entity\Resource\ResourceNode[] which is incompatible with the documented return type Doctrine\Common\Collections\ArrayCollection.
Loading history...
208
    }
209
210
    /**
211
     * Sets the parent resource.
212
     *
213
     * @param ResourceNode $parent
214
     *
215
     * @return $this
216
     */
217
    public function setParent(ResourceNode $parent = null)
218
    {
219
        $this->parent = $parent;
220
221
        return $this;
222
    }
223
224
    /**
225
     * Returns the parent resource.
226
     *
227
     * @return ResourceNode
228
     */
229
    public function getParent()
230
    {
231
        return $this->parent;
232
    }
233
234
    /**
235
     * Return the lvl value of the resource in the tree.
236
     *
237
     * @return int
238
     */
239
    public function getLevel()
240
    {
241
        return $this->level;
242
    }
243
244
    /**
245
     * Returns the "raw" path of the resource
246
     * (the path merge names and ids of all items).
247
     * Eg.: "Root-1/subdir-2/file.txt-3/".
248
     *
249
     * @return string
250
     */
251
    public function getPath()
252
    {
253
        return $this->path;
254
    }
255
256
    /**
257
     * Returns the path cleaned from its ids.
258
     * Eg.: "Root/subdir/file.txt".
259
     *
260
     * @return string
261
     */
262
    public function getPathForDisplay()
263
    {
264
        return self::convertPathForDisplay($this->path);
265
    }
266
267
    /**
268
     * @return string
269
     */
270
    public function getPathForDisplayRemoveBase(string $base)
271
    {
272
        $path = str_replace($base, '', $this->path);
273
274
        return self::convertPathForDisplay($path);
275
    }
276
277
    /**
278
     * @return mixed
279
     */
280
    public function getSlug()
281
    {
282
        return $this->slug;
283
    }
284
285
    /**
286
     * @param mixed $slug
287
     *
288
     * @return ResourceNode
289
     */
290
    public function setSlug($slug)
291
    {
292
        if (strpos(self::PATH_SEPARATOR, $slug) !== false) {
293
            throw new \InvalidArgumentException('Invalid character "'.self::PATH_SEPARATOR.'" in resource name.');
294
        }
295
296
        $this->slug = $slug;
297
298
        return $this;
299
    }
300
301
    /**
302
     * Convert a path for display: remove ids.
303
     *
304
     * @param string $path
305
     *
306
     * @return string
307
     */
308
    public static function convertPathForDisplay($path)
309
    {
310
        /*$pathForDisplay = preg_replace(
311
            '/-\d+'.self::PATH_SEPARATOR.'/',
312
            ' / ',
313
            $path
314
        );
315
        if ($pathForDisplay !== null && strlen($pathForDisplay) > 0) {
316
            $pathForDisplay = substr_replace($pathForDisplay, '', -3);
317
        }
318
        */
319
        $pathForDisplay = preg_replace(
320
            '/-\d+'.self::PATH_SEPARATOR.'/',
321
            '/',
322
            $path
323
        );
324
325
        if ($pathForDisplay !== null && strlen($pathForDisplay) > 0) {
326
            $pathForDisplay = substr_replace($pathForDisplay, '', -1);
327
        }
328
329
        return $pathForDisplay;
330
    }
331
332
    /**
333
     * This is required for logging the resource path at the creation.
334
     * Do not use this function otherwise.
335
     */
336
    public function setPathForCreationLog($path)
337
    {
338
        $this->pathForCreationLog = $path;
0 ignored issues
show
Bug Best Practice introduced by
The property pathForCreationLog does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
339
    }
340
341
    /**
342
     * This is required for logging the resource path at the creation.
343
     * Do not use this function otherwise.
344
     *
345
     * @return type
346
     */
347
    public function getPathForCreationLog()
348
    {
349
        return $this->pathForCreationLog;
350
    }
351
352
    /**
353
     * @return ResourceType
354
     */
355
    public function getResourceType()
356
    {
357
        return $this->resourceType;
358
    }
359
360
    /**
361
     * @param ResourceType $resourceType
362
     *
363
     * @return ResourceNode
364
     */
365
    public function setResourceType($resourceType)
366
    {
367
        $this->resourceType = $resourceType;
368
369
        return $this;
370
    }
371
372
    /**
373
     * @return ArrayCollection|ResourceLink[]
374
     */
375
    public function getResourceLinks()
376
    {
377
        return $this->resourceLinks;
378
    }
379
380
    /**
381
     * @param mixed $resourceLinks
382
     *
383
     * @return ResourceNode
384
     */
385
    public function setResourceLinks($resourceLinks)
386
    {
387
        $this->resourceLinks = $resourceLinks;
388
389
        return $this;
390
    }
391
392
    /**
393
     * @param Session $session
394
     *
395
     * @return ArrayCollection
396
     */
397
    public function hasSession(Session $session = null)
398
    {
399
        $links = $this->getResourceLinks();
400
        $criteria = Criteria::create();
401
402
        $criteria->andWhere(
403
            Criteria::expr()->eq('session', $session)
404
        );
405
406
        $result = $links->matching($criteria);
407
408
        return $result;
409
    }
410
411
    /**
412
     * @return bool
413
     */
414
    public function hasResourceFile()
415
    {
416
        return $this->resourceFile !== null;
417
    }
418
419
    /**
420
     * @return ResourceFile
421
     */
422
    public function getResourceFile(): ?ResourceFile
423
    {
424
        return $this->resourceFile;
425
    }
426
427
    /**
428
     * @return bool
429
     */
430
    public function hasEditableContent()
431
    {
432
        if ($this->hasResourceFile()) {
433
            $mimeType = $this->getResourceFile()->getMimeType();
434
            if (strpos($mimeType, 'text') !== false) {
435
                return true;
436
            }
437
        }
438
439
        return false;
440
    }
441
442
    /**
443
     * @return bool
444
     */
445
    public function isResourceFileAnImage()
446
    {
447
        if ($this->hasResourceFile()) {
448
            $mimeType = $this->getResourceFile()->getMimeType();
449
            if (strpos($mimeType, 'image') !== false) {
450
                return true;
451
            }
452
        }
453
454
        return false;
455
    }
456
457
    /**
458
     * @return bool
459
     */
460
    public function isResourceFileAVideo()
461
    {
462
        if ($this->hasResourceFile()) {
463
            $mimeType = $this->getResourceFile()->getMimeType();
464
            if (strpos($mimeType, 'video') !== false) {
465
                return true;
466
            }
467
        }
468
469
        return false;
470
    }
471
472
    public function setResourceFile(ResourceFile $resourceFile): ResourceNode
473
    {
474
        $this->resourceFile = $resourceFile;
475
476
        return $this;
477
    }
478
479
    /**
480
     * @return string
481
     */
482
    public function getIcon()
483
    {
484
        $class = 'fa fa-folder';
485
        if ($this->hasResourceFile()) {
486
            $class = 'far fa-file';
487
488
            if ($this->isResourceFileAnImage()) {
489
                $class = 'far fa-file-image';
490
            }
491
            if ($this->isResourceFileAVideo()) {
492
                $class = 'far fa-file-video';
493
            }
494
        }
495
496
        return '<i class="'.$class.'"></i>';
497
    }
498
499
    /**
500
     * @return string
501
     */
502
    public function getThumbnail(RouterInterface $router)
503
    {
504
        $size = 'fa-3x';
505
        $class = "fa fa-folder $size";
506
        if ($this->hasResourceFile()) {
507
            $class = "far fa-file $size";
508
509
            if ($this->isResourceFileAnImage()) {
510
                $class = "far fa-file-image $size";
511
512
                $params = [
513
                    'id' => $this->getId(),
514
                    'tool' => $this->getResourceType()->getTool(),
515
                    'type' => $this->getResourceType()->getName(),
516
                    'filter' => 'editor_thumbnail',
517
                ];
518
                $url = $router->generate(
519
                    'chamilo_core_resource_view',
520
                    $params
521
                );
522
523
                return "<img src='$url'/>";
524
            }
525
            if ($this->isResourceFileAVideo()) {
526
                $class = "far fa-file-video $size";
527
            }
528
        }
529
530
        return '<i class="'.$class.'"></i>';
531
    }
532
533
}
534