|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace SeoHelper\Renderer; |
|
6
|
|
|
|
|
7
|
|
|
use Closure; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractRenderer implements RendererInterface |
|
10
|
|
|
{ |
|
11
|
|
|
protected array $types = []; |
|
12
|
|
|
|
|
13
|
45 |
|
protected array $preprocessors = []; |
|
14
|
|
|
|
|
15
|
45 |
|
final public function init(): void |
|
16
|
45 |
|
{ |
|
17
|
|
|
$this->initPreprocessors(); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
public function getTypes(): array |
|
21
|
15 |
|
{ |
|
22
|
|
|
return array_keys($this->types); |
|
23
|
15 |
|
} |
|
24
|
|
|
|
|
25
|
|
|
public function render(string $type, string $key, mixed $value): string|array|null |
|
26
|
|
|
{ |
|
27
|
|
|
$pattern = $this->getPattern($type); |
|
28
|
|
|
if (!$pattern) { |
|
29
|
|
|
return null; |
|
30
|
|
|
} |
|
31
|
|
|
$finalValue = $this->preprocessValue($key, $value); |
|
32
|
45 |
|
if (!is_array($finalValue)) { |
|
33
|
|
|
return str_replace(['{$key}', '{$value}'], [$key, $finalValue], $pattern); |
|
34
|
45 |
|
} |
|
35
|
45 |
|
$items = []; |
|
36
|
6 |
|
foreach ($finalValue as $val) { |
|
37
|
|
|
$items[] = str_replace(['{$key}', '{$value}'], [$key, $val], $pattern); |
|
38
|
39 |
|
} |
|
39
|
39 |
|
return $items; |
|
40
|
27 |
|
} |
|
41
|
|
|
|
|
42
|
18 |
|
public function setPreprocessor(string $type, Closure $closure): static |
|
43
|
18 |
|
{ |
|
44
|
18 |
|
$this->preprocessors[$type] = $closure; |
|
45
|
6 |
|
return $this; |
|
46
|
18 |
|
} |
|
47
|
|
|
|
|
48
|
|
|
protected function getPattern($type): ?string |
|
49
|
|
|
{ |
|
50
|
|
|
return $this->types[$type] ?? null; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
protected function preprocessValue($key, $value) |
|
54
|
45 |
|
{ |
|
55
|
|
|
$preprocessor = $this->preprocessors[$key] ?? null; |
|
56
|
45 |
|
if (!$preprocessor) { |
|
57
|
45 |
|
return $value; |
|
58
|
|
|
} |
|
59
|
|
|
return $preprocessor($value); |
|
60
|
45 |
|
} |
|
61
|
|
|
|
|
62
|
45 |
|
abstract protected function initPreprocessors(): void; |
|
63
|
|
|
} |
|
64
|
|
|
|