Completed
Push — master ( d0a237...a1b9c8 )
by Freek
9s
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
class Compiler
6
{
7
    /** @var \Spatie\BladeX\BladeX */
8
    protected $bladeX;
9
10
    public function __construct(BladeX $bladeX)
11
    {
12
        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...
13
    }
14
15
    public function compile(string $viewContents): string
16
    {
17
        return array_reduce(
18
            $this->bladeX->registeredComponents(),
19
            [$this, 'parseComponentHtml'],
20
            $viewContents
21
        );
22
    }
23
24
    protected function parseComponentHtml(string $viewContents, Component $component)
25
    {
26
        $viewContents = $this->parseSlots($viewContents);
27
28
        $viewContents = $this->parseSelfClosingTags($viewContents, $component);
29
30
        $viewContents = $this->parseOpeningTags($viewContents, $component);
31
32
        $viewContents = $this->parseClosingTags($viewContents, $component);
33
34
        return $viewContents;
35
    }
36
37 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...
38
    {
39
        $prefix = $this->bladeX->getPrefix();
40
41
        $pattern = "/<\s*{$prefix}{$component->tag}\s*(?<attributes>.*)\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
        $prefix = $this->bladeX->getPrefix();
53
54
        $pattern = "/<\s*{$prefix}{$component->tag}(?<attributes>(?:\s+[\w\-:]+=(?:\\\"[^\\\"]+\\\"|\'[^\']+\'|[^\'\\\"=<>]+))*\s*)(?<![\/=\-])>/";
55
56
        return preg_replace_callback($pattern, function (array $matches) use ($component) {
57
            $attributes = $this->getAttributesFromAttributeString($matches['attributes']);
58
59
            return $this->componentStartString($component, $attributes);
60
        }, $viewContents);
61
    }
62
63
    protected function parseClosingTags(string $viewContents, Component $component): string
64
    {
65
        $prefix = $this->bladeX->getPrefix();
66
67
        $pattern = "/<\/\s*{$prefix}{$component->tag}[^>]*>/";
68
69
        return preg_replace($pattern, $this->componentEndString($component), $viewContents);
70
    }
71
72
    protected function componentString(Component $component, array $attributes = []): string
73
    {
74
        return $this->componentStartString($component, $attributes).$this->componentEndString($component);
75
    }
76
77
    protected function componentStartString(Component $component, array $attributes = []): string
78
    {
79
        $attributesString = $this->attributesToString($attributes);
80
81
        $componentAttributeString = "[{$attributesString}]";
82
83
        if ($component->view === 'bladex::context') {
84
            return " @php(app(Spatie\BladeX\ContextStack::class)->push({$componentAttributeString})) ";
85
        }
86
87
        if ($component->viewModel) {
88
            $componentAttributeString = "
89
                array_merge(
90
                    app(Spatie\BladeX\ContextStack::class)->read(),
91
                    {$componentAttributeString},
92
                    app(
93
                        '{$component->viewModel}',
94
                        array_merge(
95
                            app(Spatie\BladeX\ContextStack::class)->read(),
96
                            {$componentAttributeString}
97
                        )
98
                    )->toArray()
99
                )";
100
        }
101
102
        return " @component(
103
           '{$component->view}',
104
           array_merge(app(Spatie\BladeX\ContextStack::class)->read(),
105
           {$componentAttributeString})
106
        ) ";
107
    }
108
109
    protected function componentEndString(Component $component): string
110
    {
111
        if ($component->view === 'bladex::context') {
112
            return "@php(app(Spatie\BladeX\ContextStack::class)->pop())";
113
        }
114
115
        return ' @endcomponent ';
116
    }
117
118
    protected function getAttributesFromAttributeString(string $attributeString): array
119
    {
120
        $attributeString = $this->parseBindAttributes($attributeString);
121
122
        $pattern = '/(?<attribute>[\w:-]+)(=(?<value>(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+)))?/';
123
124
        if (! preg_match_all($pattern, $attributeString, $matches, PREG_SET_ORDER)) {
125
            return [];
126
        }
127
128
        return collect($matches)->mapWithKeys(function ($match) {
129
            $attribute = camel_case($match['attribute']);
130
            $value = $match['value'] ?? null;
131
132
            if (is_null($value)) {
133
                $value = 'true';
134
                $attribute = str_start($attribute, 'bind:');
135
            }
136
137
            $value = $this->stripQuotes($value);
138
139
            if (starts_with($attribute, 'bind:')) {
140
                $attribute = str_after($attribute, 'bind:');
141
            } else {
142
                $value = str_replace("'", "\\'", $value);
143
                $value = "'{$value}'";
144
            }
145
146
            return [$attribute => $value];
147
        })->toArray();
148
    }
149
150
    protected function parseSlots(string $viewContents): string
151
    {
152
        $openingPattern = '/<\s*slot\s+name=(?<name>(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+))\s*>/';
153
        $viewContents = preg_replace_callback($openingPattern, function ($matches) {
154
            $name = $this->stripQuotes($matches['name']);
155
156
            return " @slot('{$name}') ";
157
        }, $viewContents);
158
159
        $closingPattern = '/<\/\s*slot[^>]*>/';
160
        $viewContents = preg_replace($closingPattern, ' @endslot', $viewContents);
161
162
        return $viewContents;
163
    }
164
165
    protected function isOpeningHtmlTag(string $tagName, string $html): bool
166
    {
167
        return ! ends_with($html, ["</{$tagName}>", '/>']);
168
    }
169
170
    protected function parseBindAttributes(string $attributeString): string
171
    {
172
        return preg_replace("/\s*:([\w-]+)=/m", ' bind:$1=', $attributeString);
173
    }
174
175
    protected function attributesToString(array $attributes): string
176
    {
177
        return collect($attributes)
178
            ->map(function (string $value, string $attribute) {
179
                return "'{$attribute}' => {$value}";
180
            })
181
            ->implode(',');
182
    }
183
184
    protected function stripQuotes(string $string): string
185
    {
186
        if (starts_with($string, ['"', '\''])) {
187
            return substr($string, 1, -1);
188
        }
189
190
        return $string;
191
    }
192
}
193