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

Boundary   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 95.24%

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 0
dl 0
loc 67
ccs 20
cts 21
cp 0.9524
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __toString() 0 4 1
A newRandomBoundary() 0 4 1
A assert() 0 6 2
A validate() 0 17 4
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
}