AbstractRenderer::setPreprocessor()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace SeoHelper\Renderer;
4
5
use Closure;
6
7
abstract class AbstractRenderer implements RendererInterface
8
{
9
    protected $types = [];
10
11
    protected $preprocessors = [];
12
13 45
    final public function init()
14
    {
15 45
        $this->initPreprocessors();
16 45
    }
17
18
    /**
19
     * @return array
20
     */
21 15
    public function getTypes()
22
    {
23 15
        return array_keys($this->types);
24
    }
25
26
    /**
27
     * @param string $type
28
     * @param string $key
29
     * @param mixed $value
30
     * @return string|array|boolean rendered item(s) or false on failure
31
     */
32 45
    public function render($type, $key, $value)
33
    {
34 45
        $pattern = $this->getPattern($type);
35 45
        if (!$pattern) {
36 6
            return false;
37
        }
38 39
        $finalValue = $this->preprocessValue($key, $value);
39 39
        if (!is_array($finalValue)) {
40 27
            return str_replace(['{$key}', '{$value}'], [$key, $finalValue], $pattern);
41
        }
42 18
        $items = [];
43 18
        foreach ($finalValue as $val) {
44 18
            $items[] = str_replace(['{$key}', '{$value}'], [$key, $val], $pattern);
45 6
        }
46 18
        return $items;
47
    }
48
49
    /**
50
     * @param string $type
51
     * @param Closure $closure function with one argument: $value
52
     * @return AbstractRenderer
53
     */
54 45
    public function setPreprocessor($type, Closure $closure)
55
    {
56 45
        $this->preprocessors[$type] = $closure;
57 45
        return $this;
58
    }
59
60 45
    protected function getPattern($type)
61
    {
62 45
        return isset($this->types[$type]) ? $this->types[$type] : null;
63
    }
64
65 15
    protected function preprocessValue($key, $value)
66
    {
67 15
        $preprocessor = isset($this->preprocessors[$key]) ? $this->preprocessors[$key] : null;
68 15
        if (!$preprocessor) {
69 3
            return $value;
70
        }
71 12
        return $preprocessor($value);
72
    }
73
74
    abstract protected function initPreprocessors();
75
}
76