Completed
Pull Request — master (#42)
by Frederik
03:39
created

NameSectionItem::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
ccs 0
cts 11
cp 0
rs 9.4285
cc 1
eloc 7
nc 1
nop 0
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol\Imap\MessageData;
5
6
final class NameSectionItem implements ItemInterface
7
{
8
9
    /**
10
     * @var string
11
     */
12
    private $name;
13
    /**
14
     * @var array
15
     */
16
    private $sections;
17
18
    /**
19
     * NameSectionItem constructor.
20
     * @param string $name
21
     * @param array $sections
22
     */
23
    public function __construct(string $name, array $sections = [])
24
    {
25
        $this->name = $name;
26
        $this->sections = $sections;
27
    }
28
29
    /**
30
     * @return string
31
     */
32
    public function getName(): string
33
    {
34
        return $this->name;
35
    }
36
37
    /**
38
     * @return string
39
     */
40
    public function __toString(): string
41
    {
42
        return sprintf(
43
            '%s[%s]',
44
            $this->name,
45
            implode(
46
                ' ',
47
                $this->sections
48
            )
49
        );
50
    }
51
52
    public static function fromString(string $nameSectionItem)
53
    {
54
        $result = preg_match('/^([A-Z]+)\[(.*?)\]$/', $nameSectionItem, $matches);
55
        if ($result !== 1) {
56
            throw new \InvalidArgumentException('Not a name section item');
57
        }
58
59
        return new self($matches[1], explode(' ', $matches[2]));
60
    }
61
}