Partial::fromString()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.9332
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\MessageData;
5
6
final class Partial
7
{
8
    /**
9
     * @var int
10
     */
11
    private $firstByte;
12
13
    /**
14
     * @var int
15
     */
16
    private $lastByte;
17
18
    /**
19
     * @param int $firstByte
20
     * @param int $lastByte
21
     */
22 9
    public function __construct(int $firstByte, int $lastByte)
23
    {
24 9
        if ($firstByte < 0 || $lastByte < $firstByte) {
25 2
            throw new \InvalidArgumentException(
26 2
                'Last byte must be greater than first byte, and first byte must be greater than zero'
27
            );
28
        }
29
30 7
        $this->firstByte = $firstByte;
31 7
        $this->lastByte = $lastByte;
32 7
    }
33
34
    /**
35
     * @return string
36
     */
37 6
    public function __toString(): string
38
    {
39 6
        return \sprintf(
40 6
            '<%s>',
41 6
            $this->firstByte === $this->lastByte ? $this->firstByte : $this->firstByte . '.' . $this->lastByte
42
        );
43
    }
44
45
    /**
46
     * @param string $partial
47
     * @return Partial
48
     */
49 4
    public static function fromString(string $partial): self
50
    {
51 4
        $result = \preg_match('/^<([0-9]+)(\.([0-9]+))?>$/', $partial, $matches);
52
53 4
        if ($result !== 1) {
54 1
            throw new \InvalidArgumentException('String is not a partial');
55
        }
56
57 3
        return new self((int)$matches[1], (int)($matches[3] ?? (int)$matches[1]));
58
    }
59
}
60