Completed
Pull Request — master (#90)
by
unknown
03:46 queued 02:26
created

Compiler::parseComponentHtml()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Spatie\BladeX;
4
5
use Illuminate\Support\Str;
6
7
class Compiler
8
{
9
    /** @var \Spatie\BladeX\BladeX */
10
    protected $bladeX;
11
12
    public function __construct(BladeX $bladeX)
13
    {
14
        return $this->bladeX = $bladeX;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
15
    }
16
17
    public function compile(string $viewContents): string
18
    {
19
        return array_reduce(
20
            $this->bladeX->registeredComponents(),
21
            [$this, 'parseComponentHtml'],
22
            $viewContents
23
        );
24
    }
25
26
    protected function parseComponentHtml(string $viewContents, Component $component)
27
    {
28
        $viewContents = $this->parseSlots($viewContents);
29
30
        $viewContents = $this->parseSelfClosingTags($viewContents, $component);
31
32
        $viewContents = $this->parseOpeningTags($viewContents, $component);
33
34
        $viewContents = $this->parseClosingTags($viewContents, $component);
35
36
        return $viewContents;
37
    }
38
39 View Code Duplication
    protected function parseSelfClosingTags(string $viewContents, Component $component): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
40
    {
41
        $pattern = "/<\s*{$component->getTag()}\s*(?<attributes>(?:\s+[\w\-:]+(=(?:\\\"[^\\\"]+\\\"|\'[^\']+\'|[^\'\\\"=<>]+))?)*\s*)\/>/";
42
43
        return preg_replace_callback($pattern, function (array $matches) use ($component) {
44
            $attributes = $this->getAttributesFromAttributeString($matches['attributes']);
45
46
            return $this->componentString($component, $attributes);
47
        }, $viewContents);
48
    }
49
50 View Code Duplication
    protected function parseOpeningTags(string $viewContents, Component $component): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
    {
52
        $pattern = "/<\s*{$component->getTag()}(?<attributes>(?:\s+[\w\-:]+(=(?:\\\"[^\\\"]*\\\"|\'[^\']*\'|[^\'\\\"=<>]+))?)*\s*)(?<![\/=\-])>/";
53
54
        return preg_replace_callback($pattern, function (array $matches) use ($component) {
55
            $attributes = $this->getAttributesFromAttributeString($matches['attributes']);
56
57
            return $this->componentStartString($component, $attributes);
58
        }, $viewContents);
59
    }
60
61
    protected function parseClosingTags(string $viewContents, Component $component): string
62
    {
63
        $pattern = "/<\/\s*{$component->getTag()}\s*>/";
64
65
        return preg_replace($pattern, $this->componentEndString($component), $viewContents);
66
    }
67
68
    protected function componentString(Component $component, array $attributes = []): string
69
    {
70
        return $this->componentStartString($component, $attributes).$this->componentEndString($component);
71
    }
72
73
    protected function componentStartString(Component $component, array $attributes = []): string
74
    {
75
        $attributesString = $this->attributesToString($attributes);
76
77
        $componentAttributeString = "[{$attributesString}]";
78
79
        if ($component->view === 'bladex::context') {
80
            return " @php(app(Spatie\BladeX\ContextStack::class)->push({$componentAttributeString})) ";
81
        }
82
83
        if ($component->viewModel) {
84
            $componentAttributeString = "
85
                array_merge(
86
                    app(Spatie\BladeX\ContextStack::class)->read(),
87
                    {$componentAttributeString},
88
                    app(
89
                        '{$component->viewModel}',
90
                        array_merge(
91
                            app(Spatie\BladeX\ContextStack::class)->read(),
92
                            {$componentAttributeString}
93
                        )
94
                    )->toArray()
95
                )";
96
        }
97
98
        return " @component(
99
           '{$component->view}',
100
           array_merge(app(Spatie\BladeX\ContextStack::class)->read(),
101
           {$componentAttributeString})
102
        ) ";
103
    }
104
105
    protected function componentEndString(Component $component): string
106
    {
107
        if ($component->view === 'bladex::context') {
108
            return "@php(app(Spatie\BladeX\ContextStack::class)->pop())";
109
        }
110
111
        return ' @endcomponent ';
112
    }
113
114
    protected function getAttributesFromAttributeString(string $attributeString): array
115
    {
116
        $attributeString = $this->parseBindAttributes($attributeString);
117
118
        $pattern = '/(?<attribute>[\w:-]+)(=(?<value>(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+)))?/';
119
120
        if (! preg_match_all($pattern, $attributeString, $matches, PREG_SET_ORDER)) {
121
            return [];
122
        }
123
124
        return collect($matches)->mapWithKeys(function ($match) {
125
            $attribute = Str::camel($match['attribute']);
126
            $value = $match['value'] ?? null;
127
128
            if (is_null($value)) {
129
                $value = 'true';
130
                $attribute = Str::start($attribute, 'bind:');
131
            }
132
133
            $value = $this->stripQuotes($value);
134
135
            if (Str::startsWith($attribute, 'bind:')) {
136
                $attribute = Str::after($attribute, 'bind:');
137
                $value = $this->compileEchoes($value);
138
            } else {
139
                $value = str_replace("'", "\\'", $value);
140
                $value = "'{$value}'";
141
            }
142
143
            return [$attribute => $value];
144
        })->toArray();
145
    }
146
147
    protected function parseSlots(string $viewContents): string
148
    {
149
        $openingPattern = '/<\s*slot\s+name=(?<name>(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+))\s*>/';
150
        $viewContents = preg_replace_callback($openingPattern, function ($matches) {
151
            $name = $this->stripQuotes($matches['name']);
152
153
            return " @slot('{$name}') ";
154
        }, $viewContents);
155
156
        $closingPattern = '/<\/\s*slot[^>]*>/';
157
        $viewContents = preg_replace($closingPattern, ' @endslot', $viewContents);
158
159
        return $viewContents;
160
    }
161
162
    protected function parseBindAttributes(string $attributeString): string
163
    {
164
        return preg_replace("/\s*:([\w-]+)(=)|\s*([\w-]+)(=[\'\"]?\s*(?:{{|{!!))/m", ' bind:$1$3$2$4', $attributeString);
165
    }
166
167
    protected function attributesToString(array $attributes): string
168
    {
169
        return collect($attributes)
170
            ->map(function (string $value, string $attribute) {
171
                return "'{$attribute}' => {$value}";
172
            })
173
            ->implode(',');
174
    }
175
176
    protected function stripQuotes(string $string): string
177
    {
178
        if (Str::startsWith($string, ['"', '\''])) {
179
            return substr($string, 1, -1);
180
        }
181
182
        return $string;
183
    }
184
185
    protected function compileEchoes(string $value): string
186
    {
187
        if (preg_match('/\s*{{\s*(.*?)\s*}}\s*/', $value, $echoMatch)) {
188
            return 'e('.$echoMatch[1].')';
189
        } elseif (preg_match('/\s*{!!\s*(.*?)\s*!!}\s*/', $value, $unescapedEchoMatch)) {
190
            return $unescapedEchoMatch[1];
191
        }
192
193
        return $value;
194
    }
195
}
196