/
RuleFactory.php
112 lines (87 loc) · 2.84 KB
/
RuleFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
namespace Astrotomic\Translatable\Validation;
use InvalidArgumentException;
use Astrotomic\Translatable\Locales;
use Illuminate\Contracts\Config\Repository;
class RuleFactory
{
const FORMAT_ARRAY = 1;
const FORMAT_KEY = 2;
/**
* @var int
*/
protected $format;
/**
* @var string
*/
protected $prefix;
/**
* @var string
*/
protected $suffix;
/**
* @var null|array
*/
protected $locales = null;
public function __construct(Repository $config, ?int $format = null, ?string $prefix = null, ?string $suffix = null)
{
$this->format = $format ?? $config->get('translatable.rule_factory.format');
$this->prefix = $prefix ?? $config->get('translatable.rule_factory.prefix');
$this->suffix = $suffix ?? $config->get('translatable.rule_factory.suffix');
}
public static function make(array $rules, ?int $format = null, ?string $prefix = null, ?string $suffix = null, ?array $locales = null): array
{
$factory = app()->make(static::class, compact('format', 'prefix', 'suffix'));
$factory->setLocales($locales);
return $factory->parse($rules);
}
public function setLocales(?array $locales = null): self
{
/** @var Locales */
$helper = app(Locales::class);
if (is_null($locales)) {
$this->locales = $helper->all();
return $this;
}
foreach ($locales as $locale) {
if (! $helper->has($locale)) {
throw new InvalidArgumentException(sprintf('The locale [%s] is not defined in available locales.', $locale));
}
}
$this->locales = $locales;
return $this;
}
public function parse(array $input): array
{
$rules = [];
foreach ($input as $key => $value) {
if (! $this->isTranslatable($key)) {
$rules[$key] = $value;
continue;
}
foreach ($this->locales as $locale) {
$rules[$this->formatKey($locale, $key)] = $value;
}
}
return $rules;
}
protected function formatKey(string $locale, string $key): string
{
switch ($this->format) {
case self::FORMAT_ARRAY:
return preg_replace($this->getPattern(), $locale.'.$1', $key);
case self::FORMAT_KEY:
return preg_replace($this->getPattern(), '$1:'.$locale, $key);
}
}
protected function getPattern(): string
{
$prefix = preg_quote($this->prefix);
$suffix = preg_quote($this->suffix);
return '/'.$prefix.'([^\.'.$prefix.$suffix.']+)'.$suffix.'/';
}
protected function isTranslatable(string $key): bool
{
return strpos($key, $this->prefix) !== false && strpos($key, $this->suffix) !== false;
}
}