|
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
|
39 |
|
return str_replace(['{$key}', '{$value}'], [$key, $finalValue], $pattern); |
|
41
|
|
|
} |
|
42
|
6 |
|
$items = []; |
|
43
|
6 |
|
foreach ($finalValue as $val) { |
|
44
|
6 |
|
$items[] = str_replace(['{$key}', '{$value}'], [$key, $val], $pattern); |
|
45
|
2 |
|
} |
|
46
|
6 |
|
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
|
|
|
abstract protected function initPreprocessors(); |
|
66
|
|
|
|
|
67
|
39 |
|
private function preprocessValue($key, $value) |
|
68
|
|
|
{ |
|
69
|
39 |
|
$preprocessor = isset($this->preprocessors[$key]) ? $this->preprocessors[$key] : null; |
|
70
|
39 |
|
if (!$preprocessor) { |
|
71
|
9 |
|
return $value; |
|
72
|
|
|
} |
|
73
|
36 |
|
return $preprocessor($value); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|