Xray::getBaseView()   A
last analyzed

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 0
1
<?php
2
3
namespace BeyondCode\ViewXray;
4
5
use View;
6
7
class Xray
8
{
9
    protected $baseView;
10
11
    protected $viewId = 0;
12
13
    public function boot()
14
    {
15
        View::composer('*', function ($view) {
16
            if (is_null($this->baseView)) {
17
                $this->baseView = clone $view;
18
            }
19
20
            if ($this->isEnabledForView($view->getName())) {
21
                $this->modifyView($view);
22
            }
23
        });
24
    }
25
26
    public function isEnabled()
27
    {
28
        return config('xray.enabled');
29
    }
30
31
    public function modifyView($view)
32
    {
33
        $viewContent = file_get_contents($view->getPath());
34
35
        $file = tempnam(sys_get_temp_dir(), $view->name());
36
37
        $re = '/(@section\(([^))]+)\)+)(.*?)(@endsection|@show|@overwrite)/s';
38
        $viewContent = preg_replace_callback($re, function ($matches) use ($view) {
39
            ++$this->viewId;
40
            $sectionName = str_replace(["'", '"'], '', $matches[2]);
41
            return $matches[1] . '<!--XRAY START ' . $this->viewId . ' ' . $view->getName() . '@section:' . $sectionName . ' ' . $view->getPath() . '-->' . $matches[3] . '<!--XRAY END ' . $this->viewId . '-->' . $matches[4];
42
        }, $viewContent);
43
44
        $viewContent = '<!--XRAY START ' . $this->viewId . ' ' . $view->getName() . ' ' . $view->getPath() . '-->' . PHP_EOL . $viewContent . PHP_EOL . '<!--XRAY END ' . $this->viewId . '-->';
45
46
        file_put_contents($file, $viewContent);
47
48
        $view->setPath($file);
49
50
        ++$this->viewId;
51
    }
52
53
    public function getBaseView()
54
    {
55
        return $this->baseView;
56
    }
57
58
    protected function isEnabledForView(string $viewName): bool
59
    {
60
        return ! in_array($viewName, config('xray.excluded', []));
61
    }
62
63
}
64