Boundary::assert()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
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\Mime;
5
6
final class Boundary
7
{
8
    /**
9
     * @var string
10
     */
11
    private $identifier;
12
13
    /**
14
     * @param string $identifier
15
     */
16 42
    public function __construct(string $identifier)
17
    {
18 42
        $this->assert($identifier);
19
20 36
        $this->identifier = $identifier;
21 36
    }
22
23
    /**
24
     * @return string
25
     */
26 33
    public function __toString(): string
27
    {
28 33
        return $this->identifier;
29
    }
30
31
    /**
32
     * @param string $line
33
     * @return bool
34
     */
35 19
    public function isOpening(string $line): bool
36
    {
37 19
        return '--' . $this->identifier === $line;
38
    }
39
40
    /**
41
     * @param string $line
42
     * @return bool
43
     */
44 19
    public function isClosing(string $line): bool
45
    {
46 19
        return '--' . $this->identifier . '--' === $line;
47
    }
48
49
    /**
50
     * @return Boundary
51
     */
52 16
    public static function newRandom()
53
    {
54 16
        return new self('GenkgoMailV2Part' . \bin2hex(\random_bytes(6)));
55
    }
56
57
    /**
58
     * @param string $value
59
     */
60 42
    private function assert(string $value): void
61
    {
62 42
        if ($this->validate($value) === false) {
63 6
            throw new \InvalidArgumentException('Invalid header value ' . $value);
64
        }
65 36
    }
66
67
    /**
68
     * @param string $value
69
     * @return bool
70
     */
71 42
    private function validate(string $value): bool
72
    {
73 42
        if ($value === '') {
74
            return false;
75
        }
76
77 42
        $length = \strlen($value);
78 42
        if ($length > 70) {
79 1
            return false;
80
        }
81
82 41
        if ($value[$length - 1] === ' ') {
83 1
            return false;
84
        }
85
86 40
        return \preg_match('/[^A-Za-z0-9\'\,\(\)\+\_\,\-\.\/\:\=\? ]/', $value) !== 1;
87
    }
88
}
89