Completed
Pull Request — master (#64)
by Frederik
03:38 queued 01:09
created

CapabilityCommandResponse::isAdvertising()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Protocol\Imap\Response\Command;
5
6
final class CapabilityCommandResponse
7
{
8
    /**
9
     * @var array<int, string>
10
     */
11
    private $advertisements = [];
12
13
    /**
14
     * @param array<int, string> $list
15
     */
16 11
    public function __construct(array $list)
17
    {
18 11
        $this->advertisements = $list;
19 11
    }
20
21
    /**
22
     * @param string $command
23
     * @return bool
24
     */
25 10
    public function isAdvertising(string $command)
26
    {
27 10
        if ($command === '') {
28 1
            return false;
29
        }
30
31 10
        return isset($this->advertisements[$command]);
32
    }
33
34
    /**
35
     * @return string
36
     */
37 1
    public function __toString(): string
38
    {
39 1
        return \sprintf(
40 1
            'CAPABILITY %s',
41 1
            \implode(' ', \array_keys($this->advertisements))
42
        );
43
    }
44
45
    /**
46
     * @param string $response
47
     * @return CapabilityCommandResponse
48
     */
49 12
    public static function fromString(string $response): self
50
    {
51 12
        $command = 'CAPABILITY ';
52 12
        $commandLength = \strlen($command);
53
54 12
        if (\substr($response, 0, $commandLength) !== $command) {
55 1
            throw new \InvalidArgumentException(
56 1
                \sprintf('Expected CAPABILITY command, got %s', $response)
57
            );
58
        }
59
60 11
        $advertisements = \preg_split('/[\s]+/', \substr($response, $commandLength));
61 11
        if ($advertisements === false) {
62
            $advertisements = [];
63
        }
64
65 11
        $list = \array_combine(
66 11
            $advertisements,
67 11
            \array_fill(0, \count($advertisements), true)
68
        );
69
70 11
        if ($list === false) {
71
            throw new \UnexpectedValueException('Cannot create capability list');
72
        }
73
74 11
        return new self($list);
75
    }
76
}
77