Completed
Pull Request — master (#48)
by Frederik
02:13
created

Boundary::isClosing()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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