Passed
Push — master ( 72c793...7f699f )
by Kirill
03:22
created

ContextProcessor   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 24
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A process() 0 5 1
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Views\Processor;
13
14
use Spiral\Views\ContextInterface;
15
use Spiral\Views\ProcessorInterface;
16
use Spiral\Views\ViewSource;
17
18
/**
19
 * Replaces all context values in a view source based on given pattern (by default @{name|default}).
20
 */
21
final class ContextProcessor implements ProcessorInterface
22
{
23
    // Context injection pattern @{key|default}
24
    private const PATTERN = '/@\\{(?P<name>[a-z0-9_\\.\\-]+)(?: *\\| *(?P<default>[^}]+))?}/i';
25
26
    /** @var string */
27
    private $pattern = '';
28
29
    /**
30
     * @param string $pattern
31
     */
32
    public function __construct(string $pattern = null)
33
    {
34
        $this->pattern = $pattern ?? static::PATTERN;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function process(ViewSource $source, ContextInterface $context): ViewSource
41
    {
42
        return $source->withCode(preg_replace_callback($this->pattern, function ($matches) use ($source, $context) {
0 ignored issues
show
Unused Code introduced by
The import $source is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
43
            return $context->resolveValue($matches[1]);
44
        }, $source->getCode()));
45
    }
46
}
47