Completed
Push — master ( 789708...940c54 )
by Frederik
02:07
created

Boundary::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.0218

Importance

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