throwExceptionIfInvalid()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
/**
3
 * File containing the {@see Mailcode_Parser_Safeguard_DelimiterValidator} class.
4
 *
5
 * @package Mailcode
6
 * @subpackage Parser
7
 * @see Mailcode_Parser_Safeguard_DelimiterValidator
8
 */
9
10
declare(strict_types=1);
11
12
namespace Mailcode;
13
14
use AppUtils\OperationResult;
15
use stdClass;
16
17
/**
18
 * Utility class used to validate a safeguard placeholder delimiter
19
 * string, to ensure it conforms to the placeholder requirements.
20
 *
21
 * @package Mailcode
22
 * @subpackage Parser
23
 * @author Sebastian Mordziol <[email protected]>
24
 */
25
class Mailcode_Parser_Safeguard_DelimiterValidator extends OperationResult
26
{
27
    public const ERROR_EMPTY_DELIMITER = 73601;
28
    public const ERROR_DELIMITER_TOO_SHORT = 73602;
29
    public const ERROR_DELIMITER_URLENCODE_INCOMPATIBLE = 73603;
30
31
    /**
32
     * @var string
33
     */
34
    private $delimiter;
35
36
    public function __construct(string $delimiter)
37
    {
38
        parent::__construct(new stdClass());
39
40
        $this->delimiter = $delimiter;
41
42
        $this->validate();
43
    }
44
45
    private function validate() : OperationResult
46
    {
47
        if(empty($this->delimiter))
48
        {
49
            return $this->makeError(
50
                'Delimiters may not be empty.',
51
                self::ERROR_EMPTY_DELIMITER
52
            );
53
        }
54
55
        if(strlen($this->delimiter) < 2)
56
        {
57
            return $this->makeError(
58
                'The delimiter must have at least 2 characters in length.',
59
                self::ERROR_DELIMITER_TOO_SHORT
60
            );
61
        }
62
63
        $encoded = urlencode($this->delimiter);
64
65
        if($encoded !== $this->delimiter)
66
        {
67
            return $this->makeError(
68
                'The delimiter is not URL encoding neutral: it must not be modified by a urlencode() call.',
69
                self::ERROR_DELIMITER_URLENCODE_INCOMPATIBLE
70
            );
71
        }
72
73
        return $this;
74
    }
75
76
    public function throwExceptionIfInvalid() : void
77
    {
78
        if($this->isValid()) {
79
            return;
80
        }
81
82
        throw new Mailcode_Exception(
83
            $this->getErrorMessage(),
84
            'Delimiter: ['.$this->delimiter.']',
85
            $this->getCode()
86
        );
87
    }
88
}
89