Completed
Pull Request — master (#42)
by Frederik
02:56
created

SectionList::__toString()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 0
crap 12
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol\Imap\MessageData;
5
6
/**
7
 * Class SectionList
8
 * @package Genkgo\Mail\Protocol\Imap\MessageData
9
 */
10
final class SectionList
11
{
12
    /**
13
     * @var array
14
     */
15
    private $sections = [];
16
17
    /**
18
     * @var bool
19
     */
20
    private $forceBrackets = false;
21
22
    /**
23
     * SectionList constructor.
24
     * @param array $sections
25
     */
26
    public function __construct(array $sections = [])
27
    {
28
        $this->sections = $sections;
29
    }
30
31
    /**
32
     * @return string
33
     */
34
    public function __toString(): string
35
    {
36
        if ($this->forceBrackets === false && empty($this->sections)) {
37
            return '';
38
        }
39
40
        return sprintf(
41
            '[%s]',
42
            implode(' ', $this->sections)
43
        );
44
    }
45
46
    /**
47
     * @return SectionList
48
     */
49
    public static function newEmpty(): self
50
    {
51
        $list = new self();
52
        $list->forceBrackets = true;
53
        return $list;
54
    }
55
56
    /**
57
     * @param string $sections
58
     * @return SectionList
59
     */
60
    public static function fromString(string $sections): self
61
    {
62
        $result = preg_match('/^\[(.*?)\]$/', $sections, $matches);
63
        if ($result !== 1) {
64
            throw new \InvalidArgumentException('No section list');
65
        }
66
67
        $sectionList = new self(array_filter(explode(' ', $matches[1])));
68
69
        if (empty($sectionList->sections)) {
70
            $sectionList->forceBrackets = true;
71
        }
72
73
        return $sectionList;
74
    }
75
76
}