Passed
Push — master ( 8c805d...5e8702 )
by Sebastian
02:45
created

validate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 35
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 17
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 35
rs 9.3888
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
    const ERROR_EMPTY_DELIMITER = 73601;
28
    const ERROR_INVALID_DELIMITER = 73602;
29
    const ERROR_DELIMITER_TOO_SHORT = 73603;
30
    const ERROR_NUMBERS_IN_DELIMITER = 73604;
31
32
    /**
33
     * @var string
34
     */
35
    private $delimiter;
36
37
    public function __construct(string $delimiter)
38
    {
39
        parent::__construct(new stdClass());
40
41
        $this->delimiter = $delimiter;
42
43
        $this->validate();
44
    }
45
46
    private function validate() : OperationResult
47
    {
48
        if(empty($this->delimiter))
49
        {
50
            return $this->makeError(
51
                'Delimiters may not be empty.',
52
                self::ERROR_EMPTY_DELIMITER
53
            );
54
        }
55
56
        if(strlen($this->delimiter) < 2)
57
        {
58
            return $this->makeError(
59
                'The delimiter must have at least 2 characters in length.',
60
                self::ERROR_DELIMITER_TOO_SHORT
61
            );
62
        }
63
64
        if(!preg_match('/\A[^0-9*].*[^0-9*]\z/x', $this->delimiter))
65
        {
66
            return $this->makeError(
67
                'The delimiter may not begin or end with a number.',
68
                self::ERROR_NUMBERS_IN_DELIMITER
69
            );
70
        }
71
72
        if(strstr($this->delimiter, '*') !== false)
73
        {
74
            return $this->makeError(
75
                'The delimiter may not contain the * character.',
76
                self::ERROR_INVALID_DELIMITER
77
            );
78
        }
79
80
        return $this;
81
    }
82
83
    public function throwExceptionIfInvalid() : void
84
    {
85
        if($this->isValid()) {
86
            return;
87
        }
88
89
        throw new Mailcode_Exception(
90
            $this->getErrorMessage(),
91
            'Delimiter: ['.$this->delimiter.']',
92
            $this->getCode()
93
        );
94
    }
95
}
96