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

Partial::fromString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 6
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
     * @var int
14
     */
15
    private $lastByte;
16
17
    /**
18
     * @param int $firstByte
19
     * @param int $lastByte
20
     */
21
    public function __construct(int $firstByte, int $lastByte)
22
    {
23
        $this->firstByte = $firstByte;
24
        $this->lastByte = $lastByte;
25
    }
26
27
    /**
28
     * @return string
29
     */
30
    public function __toString(): string
31
    {
32
        if ($this->firstByte === -1 && $this->lastByte === -1) {
33
            return '';
34
        }
35
36
        return sprintf(
37
            '<%s>',
38
            $this->firstByte === $this->lastByte ? $this->firstByte : $this->firstByte . '.' . $this->lastByte
39
        );
40
    }
41
42
    /**
43
     * @return Partial
44
     */
45
    public static function full(): self
46
    {
47
        return new self(-1, -1);
48
    }
49
50
    /**
51
     * @param string $partial
52
     * @return Partial
53
     */
54
    public static function fromString(string $partial): self
55
    {
56
        $result = preg_match('/^<([0-9]+)\.([0-9]+)$/', $partial, $matches);
57
58
        if ($result !== 1) {
59
            throw new \InvalidArgumentException('String is not a partial');
60
        }
61
62
        return new self((int)$matches[1], (int)$matches[2]);
63
    }
64
}