Passed
Pull Request — master (#8)
by Victor
03:41
created

PatchingCompiler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 8
dl 0
loc 37
rs 10
c 0
b 0
f 0
ccs 8
cts 8
cp 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A raw() 0 3 1
A write() 0 5 1
A patch() 0 8 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Shoot\Shoot\Twig;
5
6
use Twig_Compiler as Compiler;
7
8
/**
9
 * This compiler patches a few crucial lines in some core Twig classes. It allows Shoot to be used with extend, embed,
10
 * and blocks. Out of all hacks to make that work, this one seemed to be the most straightforward.
11
 *
12
 * @internal
13
 */
14
final class PatchingCompiler extends Compiler
15
{
16
    /**
17
     * @param mixed $string
18
     *
19
     * @return Compiler
20
     */
21 7
    public function raw($string)
22
    {
23 7
        return parent::raw($this->patch($string));
24
    }
25
26
    /**
27
     * @param mixed[] ...$strings
28
     *
29
     * @return Compiler
30
     */
31 7
    public function write(...$strings)
32
    {
33 7
        $strings = array_map([$this, 'patch'], $strings);
34
35 7
        return parent::write(...$strings);
36
    }
37
38
    /**
39
     * @param mixed $string
40
     *
41
     * @return mixed
42
     */
43 7
    private function patch($string)
44
    {
45 7
        static $patterns = [
46
            '/(->display\()\$context(, array_merge\(\$this->blocks, \$blocks\)\);\n)/',
47
            '/(\$this->displayBlock\(\'[^\']+\', )\$context(, \$blocks\);\n)/',
48
        ];
49
50 7
        return !is_string($string) ? $string : preg_replace($patterns, '$1array_merge($originalContext, $context)$2', $string);
51
    }
52
}
53