ExtendsTag::hasIncludes()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 0
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Template
5
 *
6
 * Platine Template is a template engine that has taken a lot of inspiration from Django.
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Template
11
 * Copyright (c) 2014 Guz Alexander, http://guzalexander.com
12
 * Copyright (c) 2011, 2012 Harald Hanek, http://www.delacap.com
13
 * Copyright (c) 2006 Mateo Murphy
14
 *
15
 * Permission is hereby granted, free of charge, to any person obtaining a copy
16
 * of this software and associated documentation files (the "Software"), to deal
17
 * in the Software without restriction, including without limitation the rights
18
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
 * copies of the Software, and to permit persons to whom the Software is
20
 * furnished to do so, subject to the following conditions:
21
 *
22
 * The above copyright notice and this permission notice shall be included in all
23
 * copies or substantial portions of the Software.
24
 *
25
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
 * SOFTWARE.
32
 */
33
34
/**
35
 *  @file ExtendsTag.php
36
 *
37
 *  The "extends" Template tag class
38
 *
39
 *  @package    Platine\Template\Tag
40
 *  @author Platine Developers Team
41
 *  @copyright  Copyright (c) 2020
42
 *  @license    http://opensource.org/licenses/MIT  MIT License
43
 *  @link   https://www.platine-php.com
44
 *  @version 1.0.0
45
 *  @filesource
46
 */
47
48
declare(strict_types=1);
49
50
namespace Platine\Template\Tag;
51
52
use Platine\Template\Exception\ParseException;
53
use Platine\Template\Parser\AbstractTag;
54
use Platine\Template\Parser\Context;
55
use Platine\Template\Parser\Document;
56
use Platine\Template\Parser\Lexer;
57
use Platine\Template\Parser\Parser;
58
use Platine\Template\Parser\Token;
59
60
/**
61
 * @class ExtendsTag
62
 * @package Platine\Template\Tag
63
 */
64
class ExtendsTag extends AbstractTag
65
{
66
    /**
67
     * The name of the template
68
     * @var string
69
     */
70
    protected string $templateName;
71
72
    /**
73
     * The Document that represents the extends template
74
     * @var Document
75
     */
76
    protected Document $document;
77
78
    /**
79
     * The source template Hash
80
     * @var string
81
     */
82
    protected string $hash;
83
84
    /**
85
    * {@inheritdoc}
86
    */
87
    public function __construct(string $markup, array &$tokens, Parser $parser)
88
    {
89
        $lexer = new Lexer('/("[^"]+"|\'[^\']+\')?/');
90
        if ($lexer->match($markup) && $lexer->isMatchNotNull(1)) {
91
            $this->templateName = substr(
92
                $lexer->getStringMatch(1),
93
                1,
94
                strlen($lexer->getStringMatch(1)) - 2
95
            );
96
        } else {
97
            throw new ParseException(sprintf(
98
                'Syntax Error in "%s" - Valid syntax: extends "template name"',
99
                'extends'
100
            ));
101
        }
102
103
        parent::__construct($markup, $tokens, $parser);
104
    }
105
106
    /**
107
    * {@inheritdoc}
108
    */
109
    public function parse(array &$tokens): void
110
    {
111
        $source = $this->parser->getLoader()->read($this->templateName);
112
        $mainTokens = $this->parser->tokenize($source);
113
114
        $lexerExtends = new Lexer(
115
            '/^' . Token::BLOCK_OPEN
116
            . '\s*extends (.*)?'
117
            . Token::BLOCK_CLOSE . '$/'
118
        );
119
120
        $match = null;
121
        foreach ($mainTokens as $mainToken) {
122
            if ($lexerExtends->match($mainToken)) {
123
                $match = $lexerExtends->getStringMatch(1);
124
                break;
125
            }
126
        }
127
128
        $result = [];
129
        if ($match !== null) {
130
            $result = array_merge($mainTokens, $tokens);
131
        } else {
132
            $childrenTokens = $this->findBlocks($tokens);
133
134
            $lexerBlockStart = new Lexer(
135
                '/^' . Token::BLOCK_OPEN
136
                . '\s*block (\w+)\s*(.*)?'
137
                . Token::BLOCK_CLOSE . '$/'
138
            );
139
140
            $lexerBlockEnd = new Lexer(
141
                '/^' . Token::BLOCK_OPEN
142
                . '\s*endblock\s*?'
143
                . Token::BLOCK_CLOSE . '$/'
144
            );
145
146
            $name = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $name is dead and can be removed.
Loading history...
147
            $keep = false;
148
            $count = count($mainTokens);
149
            for ($i = 0; $i < $count; $i++) {
150
                if ($lexerBlockStart->match($mainTokens[$i])) {
151
                    $name = $lexerBlockStart->getStringMatch(1);
152
                    if (isset($childrenTokens[$name])) {
153
                        $keep = true;
154
                        array_push($result, $mainTokens[$i]);
155
                        foreach ($childrenTokens[$name] as $item) {
156
                            array_push($result, $item);
157
                        }
158
                    }
159
                }
160
161
                if (!$keep) {
162
                    array_push($result, $mainTokens[$i]);
163
                }
164
165
                if ($lexerBlockEnd->match($mainTokens[$i]) && $keep) {
166
                    $keep = false;
167
                    array_push($result, $mainTokens[$i]);
168
                }
169
            }
170
        }
171
172
        $cache = $this->parser->getTemplate()->getCache();
173
        $this->hash = md5($this->templateName);
174
175
        /** @var Document|false $document */
176
        $document = $cache->read($this->hash, true);
177
178
        if ($document === false || ($document->hasIncludes())) {
179
            $this->document = new Document($result, $this->parser);
180
            $cache->write($this->hash, $this->document, true);
181
        } else {
182
            $this->document = $document;
183
        }
184
    }
185
186
187
    /**
188
    * {@inheritdoc}
189
    */
190
    public function render(Context $context): string
191
    {
192
        $context->push();
193
        $result = $this->document->render($context);
194
        $context->pop();
195
196
        return $result;
197
    }
198
199
    /**
200
     * Check for cached includes;
201
     * if there are - do not use cache
202
     * @return bool
203
     */
204
    public function hasIncludes(): bool
205
    {
206
        if ($this->document->hasIncludes()) {
207
            return true;
208
        }
209
210
        $cache = $this->parser->getTemplate()->getCache();
211
        $hash = md5($this->templateName);
212
        if ($cache->exists($hash) && $this->hash === $hash) {
213
            return false;
214
        }
215
216
        return true;
217
    }
218
219
    /**
220
     * Find all defined blocks
221
     * @param array<int, mixed> $tokens
222
     * @return array<string, array<string>>
223
     */
224
    protected function findBlocks(array $tokens): array
225
    {
226
        $lexerBlockStart = new Lexer(
227
            '/^' . Token::BLOCK_OPEN
228
            . '\s*block (\w+)\s*(.*)?'
229
            . Token::BLOCK_CLOSE . '$/'
230
        );
231
232
        $lexerBlockEnd = new Lexer(
233
            '/^' . Token::BLOCK_OPEN
234
            . '\s*endblock\s*?'
235
            . Token::BLOCK_CLOSE . '$/'
236
        );
237
238
        $result = [];
239
        $name = null;
240
        foreach ($tokens as $token) {
241
            if ($lexerBlockStart->match($token)) {
242
                $name = $lexerBlockStart->getStringMatch(1);
243
                $result[$name] = [];
244
            } elseif ($lexerBlockEnd->match($token)) {
245
                $name = null;
246
            } else {
247
                if ($name !== null) {
248
                    array_push($result[$name], $token);
249
                }
250
            }
251
        }
252
253
        return $result;
254
    }
255
}
256