StringType::validate()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.439
cc 6
eloc 15
nc 6
nop 1
1
<?php
2
/**
3
 * Copyright (c) 2014-2016 Ryan Parman.
4
 *
5
 * Permission is hereby granted, free of charge, to any person obtaining a copy
6
 * of this software and associated documentation files (the "Software"), to deal
7
 * in the Software without restriction, including without limitation the rights
8
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
 * copies of the Software, and to permit persons to whom the Software is
10
 * furnished to do so, subject to the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be included in
13
 * all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
 * THE SOFTWARE.
22
 *
23
 * http://opensource.org/licenses/MIT
24
 */
25
26
namespace Skyzyx\StrongTypes;
27
28
use \InvalidArgumentException;
29
use \LengthException;
30
use \UnexpectedValueException;
31
32
class StringType extends AbstractShape implements StringInterface, SingleValueInterface
33
{
34
    /** @var integer */
35
    protected $min = 0;
36
37
    /** @var integer */
38
    protected $max = \PHP_INT_MAX;
39
40
    /** @var callable */
41
    protected $callback;
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function __construct($value = null)
47
    {
48
        mb_internal_encoding('UTF-8');
49
        parent::__construct($value);
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public static function fromBytes($value)
56
    {
57
        return new static(
58
            sprintf("%s",
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
59
                preg_replace_callback('/\\\\x([[:xdigit:]]+)/i', function($matches) {
60
                    return hex2bin($matches[1]);
61
                }, $value)
62
            )
63
        );
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public static function fromUnicode($value)
70
    {
71
        return new static(
72
            html_entity_decode(
73
                preg_replace('/\\\\u([[:xdigit:]]+)/i', '&#x\1;', $value)
74
            )
75
        );
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function validate(callable $callback = null)
82
    {
83
        $this->callback = $callback ?: function ($string) {
84
            return strlen($string);
85
        };
86
87
        if ($this->value !== null && !is_string($this->value)) {
88
            throw new UnexpectedValueException(
89
                sprintf(self::TYPE_EXCEPTION_MESSAGE, get_called_class(), 'string', Util::getClassOrType($this->value))
90
            );
91
        }
92
93
        $callback = $this->callback;
94
        $length = $callback($this->value);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 3 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
95
96
        if ($length < $this->min || $length > $this->max) {
97
            throw new LengthException(
98
                sprintf('The length of the %s object is %s, but MUST be between %s and %s.',
99
                    get_called_class(),
100
                    $length,
101
                    $this->min,
102
                    $this->max
103
                )
104
            );
105
        }
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function setMinLength($length)
112
    {
113
        $this->validateAsInteger($length);
114
        $this->min = $length;
115
116
        return $this;
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function setMaxLength($length)
123
    {
124
        $this->validateAsInteger($length);
125
        $this->max = $length;
126
127
        return $this;
128
    }
129
130
    /**
131
     * {@inheritdoc}
132
     */
133
    public function setExactLength($length)
134
    {
135
        $this->validateAsInteger($length);
136
        $this->min = $length;
137
        $this->max = $length;
138
139
        return $this;
140
    }
141
142
    /**
143
     * {@inheritdoc}
144
     */
145
    public function getLength()
146
    {
147
        $callback = $this->callback;
148
149
        return $callback($this->value);
150
    }
151
152
    /**
153
     * Validates that the parameter was an integer.
154
     *
155
     * @param  integer $param The value to check.
156
     * @return void
157
     *
158
     * @throws InvalidArgumentException
159
     */
160
    protected function validateAsInteger($param)
161
    {
162
        if (!is_int($param)) {
163
            throw new InvalidArgumentException(
164
                sprintf('The parameter was expecting an integer, but instead received a value of type %s.',
165
                    Util::getClassOrType($param)
166
                )
167
            );
168
        }
169
    }
170
}
171