Completed
Push — master ( 1b8406...90fba5 )
by Nelson
03:16
created

IntString::getIntValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
/**
3
 * PHP: Nelson Martell Library file
4
 *
5
 * Copyright © 2015-2019 Nelson Martell (http://nelson6e65.github.io)
6
 *
7
 * Licensed under The MIT License (MIT)
8
 * For full copyright and license information, please see the LICENSE
9
 * Redistributions of files must retain the above copyright notice.
10
 *
11
 * @copyright 2015-2019 Nelson Martell
12
 * @link      http://nelson6e65.github.io/php_nml/
13
 * @since     0.1.1
14
 * @license   http://www.opensource.org/licenses/mit-license.php The MIT License (MIT)
15
 * */
16
17
namespace NelsonMartell;
18
19
use InvalidArgumentException;
20
21
use NelsonMartell\Extensions\Text;
22
23
/**
24
 * Representa un elemento mixto, compuesto por un entero y una cadena unidos
25
 * (en ese orden).
26
 * El método IntString::toString obtiene esa cadena compuesta.
27
 *
28
 * @author Nelson Martell <[email protected]>
29
 * @since 0.1.1
30
 *
31
 * @property-read int    $intValue    Gets the integer part.
32
 * @property-read string $stringValue Gets the string part.
33
 * */
34
class IntString extends StrictObject implements IEquatable, IComparable
35
{
36
    /**
37
     * Creates a new IntString instance.
38
     *
39
     * @param int|null     $intValue    Integer part. Default: `0` (zero).
40
     * @param string|null  $stringValue String part. Default: `''` (empty).
41
     *
42
     * @since 1.0.0-dev Allow `null` value for `$intValue`.
43
     */
44 50
    public function __construct($intValue = 0, $stringValue = '')
45
    {
46 50
        if (!(is_integer($intValue) || $intValue === null)) {
0 ignored issues
show
introduced by
The condition $intValue === null is always true.
Loading history...
47
            $args = [
48
                'position' => '1st',
49
                'expected' => typeof(0).'" or "'.typeof(null),
50
                'actual'   => typeof($intValue),
51
            ];
52
53
            $msg  = msg('Invalid argument type.');
54
            $msg .= msg(
55
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
56
                $args
57
            );
58
59
            throw new InvalidArgumentException($msg);
60
        }
61
62 50
        $this->intValue = $intValue;
0 ignored issues
show
Bug introduced by
The property intValue is declared read-only in NelsonMartell\IntString.
Loading history...
63
64 50
        if (!typeof($stringValue)->canBeString()) {
65
            $args = [
66 2
                'position' => '2nd',
67 2
                'expected' => typeof('string').'", "'.typeof(null).'" or "any object convertible to string',
68 2
                'actual'   => typeof($stringValue),
69
            ];
70
71 2
            $msg  = msg('Invalid argument type.');
72 2
            $msg .= msg(
73 2
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
74 2
                $args
75
            );
76
77 2
            throw new InvalidArgumentException($msg);
78
        }
79
80 48
        $this->stringValue = (string) $stringValue;
0 ignored issues
show
Bug introduced by
The property stringValue is declared read-only in NelsonMartell\IntString.
Loading history...
81 48
    }
82
83
    /**
84
     * Convert the object to an instance of ``IntString``.
85
     *
86
     * @param string|IntString $obj Object to convert to ``IntString``.
87
     *
88
     * @return IntString
89
     * @throws InvalidArgumentException if object is not a string or format is invalid.
90
     */
91 37
    public static function parse($obj)
92
    {
93 37
        if ($obj instanceof IntString) {
94
            return $obj;
95
        }
96
97 37
        if (is_integer($obj)) {
0 ignored issues
show
introduced by
The condition is_integer($obj) is always false.
Loading history...
98 19
            return new VersionComponent($obj);
99
        }
100
101
        try {
102 19
            $intValue = (integer) Text::ensureIsString($obj);
103 1
        } catch (InvalidArgumentException $e) {
104
            $args = [
105 1
                'position' => '1st',
106 1
                'expected' => 'string" or "integer',
107 1
                'actual'   => typeof($obj),
108
            ];
109
110 1
            $msg  = msg('Invalid argument type.');
111 1
            $msg .= msg(
112 1
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
113 1
                $args
114
            );
115
116 1
            throw new InvalidArgumentException($msg, 1, $e);
117
        }
118
119 18
        $stringValue = ltrim($obj, "${intValue}");
120
121
        // Validate that 0 (zero) is not interpreted as '' (empty string)
122 18
        if ($stringValue === $obj) {
123 3
            $msg  = msg('Invalid argument value.');
124 3
            $msg .= msg(' "{0}" (string) must to start with an integer.', $obj);
125
126 3
            throw new InvalidArgumentException($msg);
127
        }
128
129 15
        return new IntString($intValue, $stringValue);
130
    }
131
132
    /**
133
     * Integer part of the instance.
134
     *
135
     * @var int
136
     */
137
    private $intValue;
138
139
    /**
140
     * String part of the instance.
141
     *
142
     * @var string
143
     */
144
    private $stringValue;
145
146
    /**
147
     * Getter for $intValue property.
148
     *
149
     * @return int
150
     */
151 137
    protected function getIntValue()
152
    {
153 137
        return $this->intValue;
154
    }
155
156
    /**
157
     * Getter for $stringValue property.
158
     *
159
     * @return int
160
     */
161 116
    protected function getStringValue()
162
    {
163 116
        return $this->stringValue;
164
    }
165
166
    /**
167
     * {@inheritDoc}
168
     */
169 30
    public function toString()
170
    {
171 30
        return $this->getIntValue().$this->getStringValue();
172
    }
173
174
    /**
175
     * Indicates whether the specified object is equal to the current instance.
176
     *
177
     * @param IntString|mixed $other
178
     *
179
     * @return bool
180
     */
181 15
    public function equals($other)
182
    {
183 15
        if ($other instanceof IntString) {
184
            if ($this->getIntValue() === $other->getIntValue()) {
185
                if ($this->getIntValue() === $other->getStringValue()) {
186
                    return true;
187
                }
188
            }
189
        }
190
191 15
        return false;
192
    }
193
194
195
    /**
196
     * Determina la posición relativa de esta instancia con respecto al
197
     * objeto especificado.
198
     * Nota: Cualquier objeto que no sea instancia de IntString se
199
     * considerará menor.
200
     *
201
     * @param IntString|mixed $other Objeto con el que se va a comparar.
202
     *
203
     * @return int Cero (0), si esta instancia es igual a $other; mayor
204
     *   a cero (>0), si es mayor a $other; menor a cero (<0), si es menor.
205
     * */
206
    public function compareTo($other)
207
    {
208
        $r = $this->equals($other) ? 0 : 9999;
209
210
        if ($r != 0) {
211
            if ($other instanceof IntString) {
212
                $r = $this->intValue - $other->intValue;
213
214
                if ($r == 0) {
215
                    $r = strnatcmp($this->stringValue, $other->stringValue);
216
                }
217
            } else {
218
                $r = 1;
219
            }
220
        }
221
222
        return $r;
223
    }
224
}
225