Completed
Push — master ( b1115e...998ae3 )
by ignace nyamagana
22:33 queued 07:16
created

LatinLetter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
/**
4
 * League.Period (https://period.thephpleague.com)
5
 *
6
 * (c) Ignace Nyamagana Butera <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace League\Period\Chart\Label;
15
16
use function preg_match;
17
use function trim;
18
19
final class LatinLetter implements LabelGenerator
20
{
21
    /**
22
     * @var string
23
     */
24
    private $str;
25
26
    /**
27
     * New instance.
28
     */
29
    public function __construct(string $str = 'A')
30
    {
31
        $this->str = $this->filterLetter($str);
32
    }
33
34
    public function filterLetter(string $str): string
35
    {
36
        $str = trim($str);
37
        if ('' === $str) {
38
            return '0';
39
        }
40
41
        if (1 !== preg_match('/^[A-Za-z]+$/', $str)) {
42
            return 'A';
43
        }
44
45
        return $str;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function format(string $label): string
52
    {
53
        return $label;
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function generate(int $nbLabels): \Iterator
60
    {
61
        if (0 >= $nbLabels) {
62
            $nbLabels = 0;
63
        }
64
65
        $count = 0;
66
        $letter = $this->str;
67
        while ($count < $nbLabels) {
68
            yield $count => $letter++;
69
70
            ++$count;
71
        }
72
    }
73
74
    /**
75
     * Returns the starting Letter.
76
     */
77
    public function startingAt(): string
78
    {
79
        return $this->str;
80
    }
81
82
    /**
83
     * Return an instance with the starting Letter.
84
     *
85
     * This method MUST retain the state of the current instance, and return
86
     * an instance that contains the starting Letter.
87
     */
88
    public function startsWith(string $str): self
89
    {
90
        $str = $this->filterLetter($str);
91
        if ($str === $this->str) {
92
            return $this;
93
        }
94
95
        $clone = clone $this;
96
        $clone->str = $str;
97
98
        return $clone;
99
    }
100
}
101