Passed
Pull Request — 2.x (#586)
by Bekzat
04:25
created

HasBlocks::blocks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
namespace A17\Twill\Models\Behaviors;
4
5
use A17\Twill\Models\Block;
6
7
trait HasBlocks
8
{
9
    public function blocks()
10
    {
11
        return $this->morphMany(Block::class, 'blockable')->orderBy(config('twill.blocks_table', 'twill_blocks') . '.position', 'asc');
0 ignored issues
show
Bug introduced by
It seems like morphMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

11
        return $this->/** @scrutinizer ignore-call */ morphMany(Block::class, 'blockable')->orderBy(config('twill.blocks_table', 'twill_blocks') . '.position', 'asc');
Loading history...
12
    }
13
14
    public function renderBlocks($renderChilds = true, $blockViewMappings = [], $data = [])
15
    {
16
        return $this->blocks->where('parent_id', null)->map(function ($block) use ($blockViewMappings, $renderChilds, $data) {
17
            if ($renderChilds) {
18
                $childBlocks = $this->blocks->where('parent_id', $block->id);
19
20
                $renderedChildViews = $childBlocks->map(function ($childBlock) use ($blockViewMappings, $data) {
21
                    $view = $this->getBlockView($childBlock->type, $blockViewMappings);
22
                    return view($view, $data)->with('block', $childBlock)->render();
23
                })->implode('');
24
            }
25
26
            $block->childs = $this->blocks->where('parent_id', $block->id);
27
28
            $view = $this->getBlockView($block->type, $blockViewMappings);
29
30
            return view($view, $data)->with('block', $block)->render() . ($renderedChildViews ?? '');
0 ignored issues
show
Bug introduced by
Are you sure view($view, $data)->with...ock', $block)->render() of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

30
            return /** @scrutinizer ignore-type */ view($view, $data)->with('block', $block)->render() . ($renderedChildViews ?? '');
Loading history...
31
        })->implode('');
32
    }
33
34
    private function getBlockView($blockType, $blockViewMappings = [])
35
    {
36
        $view = config('twill.block_editor.block_views_path') . '.' . $blockType;
37
38
        if (array_key_exists($blockType, $blockViewMappings)) {
39
            $view = $blockViewMappings[$blockType];
40
        }
41
42
        return $view;
43
    }
44
}
45