CharacterCollection   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 51
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A __toString() 0 13 3
A add() 0 12 3
A get() 0 8 2
1
<?php
2
3
namespace JeroenDesloovere\CharacterCollection;
4
5
class CharacterCollection
6
{
7
    /** @var array */
8
    private $characters;
9
10
    public function __construct(string $sentence)
11
    {
12
        /** @var array $characters */
13
        $characters = str_split($sentence);
14
15
        foreach ($characters as $position => $character) {
16
            $this->add($position, $character);
17
        }
18
    }
19
20
    public function __toString(): string
21
    {
22
        $sentences = [];
23
        foreach ($this->characters as $position => $character) {
24
            foreach ($character->getPositions() as $position) {
25
                $sentences[$position] = $character->getValue();
26
            }
27
        }
28
29
        ksort($sentences);
30
31
        return implode($sentences);
32
    }
33
34
    public function add(int $position, string $character): void
35
    {
36
        if ($character === '') {
37
            return;
38
        }
39
40
        if (!isset($this->characters[$character])) {
41
            $this->characters[$character] = new Character($character);
42
        }
43
44
        $this->characters[$character]->addPosition($position);
45
    }
46
47
    public function get(string $character): Character
48
    {
49
        if (!array_key_exists($character, $this->characters)) {
50
            throw Exception::characterNotFound($character);
51
        }
52
53
        return $this->characters[$character];
54
    }
55
}
56