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

Boundary   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 96%

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 0
dl 0
loc 83
ccs 24
cts 25
cp 0.96
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __toString() 0 4 1
A isOpening() 0 4 1
A isClosing() 0 4 1
A newRandom() 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
     * @param string $identifier
15
     */
16 25
    public function __construct(string $identifier)
17
    {
18 25
        $this->assert($identifier);
19
20 19
        $this->identifier = $identifier;
21 19
    }
22
23
    /**
24
     * @return string
25
     */
26 16
    public function __toString(): string
27
    {
28 16
        return $this->identifier;
29
    }
30
31
    /**
32
     * @param string $line
33
     * @return bool
34
     */
35 5
    public function isOpening(string $line): bool
36
    {
37 5
        return '--' . $this->identifier === $line;
38
    }
39
40
    /**
41
     * @param string $line
42
     * @return bool
43
     */
44 5
    public function isClosing(string $line): bool
45
    {
46 5
        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 25
    private function assert(string $value): void
61
    {
62 25
        if ($this->validate($value) === false) {
63 6
            throw new \InvalidArgumentException('Invalid header value ' . $value);
64
        }
65 19
    }
66
67
    /**
68
     * @param string $value
69
     * @return bool
70
     */
71 25
    private function validate(string $value): bool
72
    {
73 25
        if ($value === '') {
74
            return false;
75
        }
76
77 25
        $length = \strlen($value);
78 25
        if ($length > 70) {
79 1
            return false;
80
        }
81
82 24
        if ($value[$length - 1] === ' ') {
83 1
            return false;
84
        }
85
86 23
        return \preg_match('/[^A-Za-z0-9\'\,\(\)\+\_\,\-\.\/\:\=\? ]/', $value) !== 1;
87
    }
88
}
89