1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Karma\FormatterProviders; |
6
|
|
|
|
7
|
|
|
use Karma\Formatter; |
8
|
|
|
use Karma\FormatterProvider; |
9
|
|
|
use Karma\FormattersDefinition; |
10
|
|
|
use Karma\Formatters\Raw; |
11
|
|
|
use Karma\Formatters\Rules; |
12
|
|
|
|
13
|
|
|
class ProfileProvider implements FormatterProvider |
14
|
|
|
{ |
15
|
|
|
private ?string |
|
|
|
|
16
|
|
|
$defaultFormatterName; |
17
|
|
|
private array |
18
|
|
|
$formatters, |
19
|
|
|
$fileExtensionFormatters; |
20
|
|
|
|
21
|
15 |
|
public function __construct(FormattersDefinition $definition) |
22
|
|
|
{ |
23
|
15 |
|
$this->formatters = [ |
24
|
15 |
|
FormattersDefinition::DEFAULT_FORMATTER_NAME => new Raw(), |
25
|
|
|
]; |
26
|
|
|
|
27
|
15 |
|
$this->fileExtensionFormatters = []; |
28
|
|
|
|
29
|
15 |
|
$this->defaultFormatterName = $definition->getDefaultFormatterName(); |
30
|
15 |
|
$this->parseFormatters($definition->getFormatters()); |
31
|
13 |
|
$this->fileExtensionFormatters = array_map('trim', $definition->getFileExtensionFormatters()); |
32
|
13 |
|
} |
33
|
|
|
|
34
|
15 |
|
private function parseFormatters($content): void |
35
|
|
|
{ |
36
|
15 |
|
if(! is_array($content)) |
37
|
|
|
{ |
38
|
1 |
|
throw new \InvalidArgumentException('Syntax error in profile [formatters]'); |
39
|
|
|
} |
40
|
|
|
|
41
|
14 |
|
foreach($content as $name => $rules) |
42
|
|
|
{ |
43
|
3 |
|
if(! is_array($rules)) |
44
|
|
|
{ |
45
|
1 |
|
throw new \InvalidArgumentException('Syntax error in profile [formatters]'); |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
$this->formatters[trim($name)] = new Rules($rules); |
49
|
|
|
} |
50
|
13 |
|
} |
51
|
|
|
|
52
|
10 |
|
public function hasFormatter(?string $index): bool |
53
|
|
|
{ |
54
|
10 |
|
return isset($this->formatters[$index]); |
55
|
|
|
} |
56
|
|
|
|
57
|
10 |
|
public function getFormatter(?string $fileExtension, ?string $index = null): Formatter |
58
|
|
|
{ |
59
|
10 |
|
$formatter = $this->formatters[$this->getDefaultFormatterName()]; |
60
|
|
|
|
61
|
10 |
|
if($index === null) |
62
|
|
|
{ |
63
|
10 |
|
if(isset($this->fileExtensionFormatters[$fileExtension])) |
64
|
|
|
{ |
65
|
1 |
|
$index = $this->fileExtensionFormatters[$fileExtension]; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
10 |
|
if($this->hasFormatter($index)) |
70
|
|
|
{ |
71
|
2 |
|
$formatter = $this->formatters[$index]; |
72
|
|
|
} |
73
|
|
|
|
74
|
10 |
|
return $formatter; |
75
|
|
|
} |
76
|
|
|
|
77
|
10 |
|
private function getDefaultFormatterName(): string |
78
|
|
|
{ |
79
|
10 |
|
$name = FormattersDefinition::DEFAULT_FORMATTER_NAME; |
80
|
|
|
|
81
|
10 |
|
if($this->hasFormatter($this->defaultFormatterName)) |
82
|
|
|
{ |
83
|
10 |
|
$name = $this->defaultFormatterName; |
84
|
|
|
} |
85
|
|
|
|
86
|
10 |
|
return $name; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|