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

PartialItem::__toString()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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