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

HasBlocks::hasBlocks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 4
Ratio 100 %

Importance

Changes 0
Metric Value
nc 1
dl 4
loc 4
c 0
b 0
f 0
cc 1
eloc 2
nop 0
rs 10
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