Completed
Push — master ( 42e96b...3ef6d5 )
by Michal
17s queued 15s
created

TranslateMacros::install()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Efabrica\Translatte\Latte;
6
7
use Latte\Compiler;
8
use Latte\Engine;
9
use Latte\MacroNode;
10
use Latte\Macros\MacroSet;
11
use Latte\PhpWriter;
12
13
class TranslateMacros extends MacroSet
14
{
15
16
    public static function install(Compiler $compiler): void
17
    {
18
        $me = new static($compiler);
19
20
        $me->addMacro('_', [$me, 'macroTranslate'], [$me, 'macroTranslate']);
21
    }
22
23
    public function macroTranslate(MacroNode $node, PhpWriter $writer)
24
    {
25
        if ($node->closing) {
26
            if (strpos($node->content, '<?php') === FALSE) {
27
                $value = var_export($node->content, TRUE);
28
                $node->content = '';
29
            } else {
30
                $node->openingCode = '<?php ob_start(function () {}) ?>' . $node->openingCode;
31
                $value = 'ob_get_clean()';
32
            }
33
34
            if (!defined(Engine::class . '::VERSION_ID') || Engine::VERSION_ID < 20804) {
35
                return $writer->write('$_fi = new LR\FilterInfo(%var); echo %modifyContent($this->filters->filterContent("translate", $_fi, %raw))', $node->context[0], $value);
36
            }
37
38
            if (Engine::VERSION_ID >= 20900 && Engine::VERSION_ID < 20902) {
39
                return $writer->write('$__fi = new LR\FilterInfo(%var); echo %modifyContent($this->filters->filterContent("translate", $__fi, %raw))', $node->context[0], $value);
40
            }
41
42
            return $writer->write('$ʟ_fi = new LR\FilterInfo(%var); echo %modifyContent($this->filters->filterContent("translate", $ʟ_fi, %raw))', $node->context[0], $value);
43
44
        } elseif ($node->args !== '') {
45
            $node->empty = TRUE;
46
            if ($this->containsOnlyOneWord($node)) {
47
                return $writer->write('echo %modify(call_user_func($this->filters->translate, %node.word))');
48
49
            } else {
50
                return $writer->write('echo %modify(call_user_func($this->filters->translate, %node.word, %node.args))');
51
            }
52
        }
53
    }
54
55
    private function containsOnlyOneWord(MacroNode $node): bool
56
    {
57
        $result = trim($node->tokenizer->joinUntil(',')) === trim($node->args);
58
        $node->tokenizer->reset();
59
        return $result;
60
    }
61
62
}