Completed
Push — dev ( 2d24b0...5cd7c1 )
by Zach
06:05
created

HasBlocks   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 65
Duplicated Lines 100 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 65
loc 65
c 0
b 0
f 0
rs 10
wmc 6
lcom 1
cbo 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
getFromRelationshipByName() 1 1 ?
A blocks() 4 4 1
A hasBlocks() 4 4 1
A block() 4 4 1
A blockText() 12 12 3

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
namespace Larafolio\Models\ContentTraits;
4
5
use Larafolio\Models\TextBlock;
6
7 View Code Duplication
trait HasBlocks
8
{
9
    /**
10
     * Get a model from a relationship by model name.
11
     *
12
     * @param string $relationship Name of relationship.
13
     * @param string $name         Name of model to get.
14
     *
15
     * @return \Illuminate\Database\Eloquent\Model|null
16
     */
17
    abstract protected function getFromRelationshipByName($relationship, $name);
18
19
    /**
20
     * A resource has many text blocks.
21
     *
22
     * @return MorphMany
23
     */
24
    public function blocks()
25
    {
26
        return $this->morphMany(TextBlock::class, 'resource');
27
    }
28
29
    /**
30
     * Return true if project has blocks.
31
     *
32
     * @return bool
33
     */
34
    public function hasBlocks()
35
    {
36
        return !$this->blocks->isEmpty();
37
    }
38
39
    /**
40
     * Get a text block by name, if exists.
41
     *
42
     * @param string $name Name of text block to get.
43
     *
44
     * @return Larafolio\Models\TextBlock|null
45
     */
46
    public function block($name)
47
    {
48
        return $this->getFromRelationshipByName('blocks', $name);
49
    }
50
51
    /**
52
     * Get block text by block name, if block exists.
53
     *
54
     * @param string $name      Name of text block to get.
55
     * @param bool   $formatted If true, return formmated text.
56
     *
57
     * @return string|null
58
     */
59
    public function blockText($name, $formatted = true)
60
    {
61
        if (!$block = $this->block($name)) {
62
            return;
63
        }
64
65
        if ($formatted) {
66
            return $block->formattedText();
67
        }
68
69
        return $block->text();
70
    }
71
}
72