Passed
Push — ft/field-contract ( 898325 )
by Ben
10:44
created

FieldName::withBrackets()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 0
1
<?php declare(strict_types=1);
2
3
namespace Thinktomorrow\Chief\Fields;
4
5
class FieldName
6
{
7
    /** @var string */
8
    private $name;
9
10
    /** @var null|string */
11
    private $localizedFormat;
12
13
    /** @var bool */
14
    private $withBrackets = false;
15
16
    final private function __construct(string $name)
17
    {
18
        $this->name = $this->replaceBracketsByDots($name);
19
    }
20
21
    public static function fromString(string $name)
22
    {
23
        return new static($name);
24
    }
25
26
    public function get(?string $locale = null): string
27
    {
28
        $name = $this->name;
29
30
        if($locale) {
31
            $name = $this->getLocalized($name, $locale);
32
        }
33
34
        if($this->withBrackets) {
35
            $name = $this->replaceDotsByBrackets($name);
36
        }
37
38
        return $name;
39
    }
40
41
    public function localizedFormat(string $localizedFormat): self
42
    {
43
        $this->validateLocalizedFormat($localizedFormat);
44
45
        $this->localizedFormat = $localizedFormat;
46
47
        return $this;
48
    }
49
50
    public function withBrackets(): self
51
    {
52
        $this->withBrackets = true;
53
54
        return $this;
55
    }
56
57
    private function getLocalized(string $name, string $locale)
58
    {
59
        if(isset($this->localizedFormat)) {
60
            $name = str_replace(':name', $name, $this->localizedFormat);
61
        }
62
63
        return str_replace(':locale', $locale, $name);
64
    }
65
66
    /**
67
     * @param string $format
68
     */
69
    private function validateLocalizedFormat(string $format): void
70
    {
71
        if (false === strpos($format, ':locale')) {
72
            throw new \InvalidArgumentException('Invalid format for fieldname. Please provide a :locale placeholder.');
73
        }
74
    }
75
76
    private function replaceDotsByBrackets(string $value): string
77
    {
78
        if(false === strpos($value, '.')) return $value;
79
80
        $value = str_replace('.', '][', $value) . ']';
81
82
        return substr_replace($value, '', strpos($value, ']'), 1);
83
    }
84
85
    private function replaceBracketsByDots(string $value): string
86
    {
87
        return str_replace(['[', ']'], ['.', ''], $value);
88
    }
89
}
90