Completed
Pull Request — master (#28)
by
unknown
19:22
created

RenderBlock::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Modules\Block\Http\Middleware;
4
5
use Illuminate\Http\Response;
6
use Modules\Block\Repositories\BlockRepository;
7
8
class RenderBlock
9
{
10
    /** @var BlockRepository */
11
    private $blockRepository;
12
13
    public function __construct(BlockRepository $blockRepository)
14
    {
15
        $this->blockRepository = $blockRepository;
16
    }
17
18
    public function handle($request, \Closure $next)
19
    {
20
        /** @var Response $response */
21
        $response = $next($request);
22
23
        // do not render galleries on backend
24
        if (app('asgard.onBackend') === true) {
25
            return $response;
26
        }
27
28
        // if this is not a standard Response, return right away
29
        if(!$response instanceof Response) {
30
            return $response;
31
        }
32
33
        $response->setContent($this->replaceShortcodes($response->getContent()));
34
35
        return $response;
36
    }
37
38
    /**
39
     * replaces all block shortcodes from the response HTML with the actual block body
40
     * @param string $html
41
     * @return string
42
     */
43
    private function replaceShortcodes($html)
44
    {
45
        preg_match_all('/\[\[BLOCK\((.*)\)\]\]/U', $html, $matches);
46
        $replaceBlocks = [];
47
        foreach ($matches[1] as $blockIndex => $blockName) {
48
            // prevent loading same block twice
49
            if (isset($replaceBlocks[$matches[0][$blockIndex]])) {
50
                continue;
51
            }
52
53
            $replaceBlocks[$matches[0][$blockIndex]] = $this->blockRepository->get($blockName);
54
        }
55
56
        return str_replace(array_keys($replaceBlocks), $replaceBlocks, $html);
57
58
    }
59
}
60