Completed
Push — master ( beda1e...cc5077 )
by Nicolas
14s queued 10s
created

RenderBlock::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
cc 3
nc 3
nop 2
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 replace shortcodes and render blocks 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) {
0 ignored issues
show
Bug introduced by
The class Illuminate\Http\Response does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
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