Passed
Push — master ( 209660...779a56 )
by Nelson
02:44
created

IntString::__construct()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.8849

Importance

Changes 0
Metric Value
cc 4
eloc 22
nc 3
nop 2
dl 0
loc 37
rs 9.568
c 0
b 0
f 0
ccs 13
cts 21
cp 0.619
crap 4.8849
1
<?php
2
/**
3
 * PHP: Nelson Martell Library file
4
 *
5
 * Content:
6
 * - Class definition:  [NelsonMartell]  IntString
7
 *
8
 * Copyright © 2015-2017 Nelson Martell (http://nelson6e65.github.io)
9
 *
10
 * Licensed under The MIT License (MIT)
11
 * For full copyright and license information, please see the LICENSE
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright 2015-2017 Nelson Martell
15
 * @link      http://nelson6e65.github.io/php_nml/
16
 * @since     0.1.1
17
 * @license   http://www.opensource.org/licenses/mit-license.php The MIT License (MIT)
18
 * */
19
20
namespace NelsonMartell;
21
22
use NelsonMartell\Extensions\Text;
23
use \InvalidArgumentException;
24
25
/**
26
 * Representa un elemento mixto, compuesto por un entero y una cadena unidos
27
 * (en ese orden).
28
 * El método IntString::toString obtiene esa cadena compuesta.
29
 *
30
 * @author Nelson Martell <[email protected]>
31
 * @since 0.1.1
32
 *
33
 * @property-read int    $stringValue Gets the integer part.
34
 * @property-read string $stringValue Gets the string part.
35
 * */
36
class IntString extends StrictObject implements IEquatable, IComparable
37
{
38
    /**
39
     * Creates a new IntString instance.
40
     *
41
     * @param int|null     $intValue    Integer part. Default: `0` (zero).
42
     * @param string|null  $stringValue String part. Default: `''` (empty).
43
     *
44
     * @since 1.0.0-dev Allow `null` value for `$intValue`.
45
     */
46 50
    public function __construct($intValue = 0, $stringValue = '')
47
    {
48 50
        if (!(is_integer($intValue) || $intValue === null)) {
0 ignored issues
show
introduced by
The condition $intValue === null is always true.
Loading history...
49
            $args = [
50
                'position' => '1st',
51
                'expected' => typeof(0).'" or "'.typeof(null),
52
                'actual'   => typeof($intValue),
53
            ];
54
55
            $msg = msg('Invalid argument type.');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 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...
56
            $msg .= msg(
57
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
58
                $args
59
            );
60
61
            throw new InvalidArgumentException($msg);
62
        }
63
64 50
        $this->intValue = $intValue;
65
66 50
        if (!typeof($stringValue)->canBeString()) {
67
            $args = [
68 2
                'position' => '2nd',
69 2
                'expected' => typeof('string').'", "'.typeof(null).'" or "any object convertible to string',
1 ignored issue
show
Coding Style introduced by
This line exceeds maximum limit of 100 characters; contains 108 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
70 2
                'actual'   => typeof($stringValue),
71
            ];
72
73 2
            $msg = msg('Invalid argument type.');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 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...
74 2
            $msg .= msg(
75 2
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
76 2
                $args
77
            );
78
79 2
            throw new InvalidArgumentException($msg);
80
        }
81
82 48
        $this->stringValue = (string) $stringValue;
0 ignored issues
show
Bug introduced by
The property stringValue is declared read-only in NelsonMartell\IntString.
Loading history...
83 48
    }
84
85
    /**
86
     * Convert the object to an instance of ``IntString``.
87
     *
88
     * @param string|IntString $obj Object to convert to ``IntString``.
89
     *
90
     * @return IntString
91
     * @throws InvalidArgumentException if object is not a string or format is invalid.
92
     */
93 37
    public static function parse($obj)
94
    {
95 37
        if ($obj instanceof IntString) {
96
            return $obj;
97
        }
98
99 37
        if (is_integer($obj)) {
0 ignored issues
show
introduced by
The condition is_integer($obj) is always false.
Loading history...
100 19
            return new VersionComponent($obj);
101
        }
102
103
        try {
104 19
            $intValue = (integer) Text::ensureIsString($obj);
105 1
        } catch (InvalidArgumentException $e) {
106
            $args = [
107 1
                'position' => '1st',
108 1
                'expected' => 'string" or "integer',
109 1
                'actual'   => typeof($obj),
110
            ];
111
112 1
            $msg = msg('Invalid argument type.');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 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...
113 1
            $msg .= msg(
114 1
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
115 1
                $args
116
            );
117
118 1
            throw new InvalidArgumentException($msg, 1, $e);
119
        }
120
121 18
        $stringValue = ltrim($obj, "$intValue");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $intValue instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
122
123
        // Validate that 0 (zero) is not interpreted as '' (empty string)
124 18
        if ($stringValue === $obj) {
125 3
            $msg = msg('Invalid argument value.');
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 2 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...
126 3
            $msg .= msg(' "{0}" (string) must to start with an integer.', $obj);
127
128 3
            throw new InvalidArgumentException($msg);
129
        }
130
131 15
        return new IntString($intValue, $stringValue);
132
    }
133
134
    /**
135
     * Integer part of the instance.
136
     *
137
     * @var int
138
     */
139
    private $intValue;
140
141
    /**
142
     * String part of the instance.
143
     *
144
     * @var string
145
     */
146
    private $stringValue;
147
148
    /**
149
     * Getter for $intValue property.
150
     *
151
     * @return int
152
     */
153 137
    protected function getIntValue()
154
    {
155 137
        return $this->intValue;
156
    }
157
158
    /**
159
     * Getter for $stringValue property.
160
     *
161
     * @return int
162
     */
163 116
    protected function getStringValue()
164
    {
165 116
        return $this->stringValue;
166
    }
167
168
    /**
169
     * {@inheritDoc}
170
     */
171 30
    public function toString()
172
    {
173 30
        return $this->getIntValue().$this->getStringValue();
174
    }
175
176
    /**
177
     * Indica si el objeto especificado es igual a la instancia actual.
178
     *
179
     * @param IntString|mixed $other
180
     *
181
     * @return bool
182
     */
183 15
    public function equals($other)
184
    {
185 15
        if ($other instanceof IntString) {
186
            if ($this->getIntValue() === $other->getIntValue()) {
187
                if ($this->getIntValue() === $other->getStringValue()) {
188
                    return true;
189
                }
190
            }
191
        }
192
193 15
        return false;
194
    }
195
196
197
    /**
198
     * Determina la posición relativa de esta instancia con respecto al
199
     * objeto especificado.
200
     * Nota: Cualquier objeto que no sea instancia de IntString se
201
     * considerará menor.
202
     *
203
     * @param IntString|mixed $other Objeto con el que se va a comparar.
204
     *
205
     * @return int Cero (0), si esta instancia es igual a $other; mayor
206
     *   a cero (>0), si es mayor a $other; menor a cero (<0), si es menor.
207
     * */
208
    public function compareTo($other)
209
    {
210
        $r = $this->equals($other) ? 0 : 9999;
211
212
        if ($r != 0) {
213
            if ($other instanceof IntString) {
214
                $r = $this->intValue - $other->intValue;
215
216
                if ($r == 0) {
217
                    $r = strnatcmp($this->stringValue, $other->stringValue);
218
                }
219
            } else {
220
                $r = 1;
221
            }
222
        }
223
224
        return $r;
225
    }
226
}
227