Passed
Branch master (283c0c)
by Nelson
02:38
created

IntString::toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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     v0.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
 * */
32
class IntString extends Object implements IEquatable, IComparable
33
{
34
    /**
35
     * @param int|null     $intValue    Integer part. Default: ``0`` (zero).
36
     * @param string|null  $stringValue String part. Default: ``''`` (empty).
37
     */
38 49
    public function __construct($intValue = 0, $stringValue = '')
39
    {
40 49
        unset($this->IntValue, $this->StringValue);
41
42 49 View Code Duplication
        if (!(is_integer($intValue) || $intValue === null)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
            $args = [
44
                'position' => '1st',
45
                'expected' => typeof(0).'" or "'.typeof(null),
46
                'actual'   => typeof($intValue),
47
            ];
48
49
            $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...
50
            $msg .= msg(
51
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
52
                $args
53
            );
54
55
            throw new InvalidArgumentException($msg);
56
        }
57
58 49 View Code Duplication
        if (!typeof($stringValue)->canBeString()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
59
            $args = [
60 2
                'position' => '2nd',
61 2
                'expected' => typeof('string').'", "'.typeof(null).'" or "any object convertible to string',
62 2
                'actual'   => typeof($stringValue),
63
            ];
64
65 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...
66 2
            $msg .= msg(
67 2
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
68 2
                $args
69
            );
70
71 2
            throw new InvalidArgumentException($msg);
72
        }
73
74 47
        $this->intValue = (integer) $intValue;
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 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...
75 47
        $this->stringValue = (string) $stringValue;
76 47
    }
77
78
    /**
79
     * Convert the object to an instance of ``IntString``.
80
     *
81
     * @param string|IntString $obj Object to convert to ``IntString``.
82
     *
83
     * @return IntString
84
     * @throws InvalidArgumentException if object is not a string or format is invalid.
85
     */
86 36
    public static function parse($obj)
87
    {
88 36
        if ($obj instanceof IntString) {
89
            return $obj;
90
        }
91
92 36
        if (is_integer($obj)) {
93 19
            return new VersionComponent($obj);
94
        }
95
96
        try {
97 18
            $intValue = (integer) Text::ensureIsString($obj);
98 1
        } catch (InvalidArgumentException $e) {
99
            $args = [
100 1
                'position' => '1st',
101 1
                'expected' => 'string" or "integer',
102 1
                'actual'   => typeof($obj),
103
            ];
104
105 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...
106 1
            $msg .= msg(
107 1
                ' {position} parameter must to be an instance of "{expected}"; "{actual}" given.',
108 1
                $args
109
            );
110
111 1
            throw new InvalidArgumentException($msg, 1, $e);
112
        }
113
114 17
        $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...
115
116
        // Validate that 0 (zero) is not interpreted as '' (empty string)
117 17
        if ($stringValue === $obj) {
118 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...
119 3
            $msg .= msg(' "{0}" (string) must to start with an integer.', $obj);
120
121 3
            throw new InvalidArgumentException($msg);
122
        }
123
124 14
        return new IntString($intValue, $stringValue);
125
    }
126
127
    protected $intValue;
128
    protected $stringValue;
129
130
    /**
131
     * @var int
132
     */
133
    public $IntValue;
134 14
    public function getIntValue()
135
    {
136 14
        return $this->intValue;
137
    }
138
139
    /**
140
     * @var string
141
     */
142
    public $StringValue;
143 100
    public function getStringValue()
144
    {
145 100
        return $this->stringValue;
146
    }
147
148 30
    public function toString()
149
    {
150 30
        return $this->IntValue.$this->StringValue;
151
    }
152
153 15
    public function equals($other)
154
    {
155 15
        if ($other instanceof IntString) {
156
            if ($this->IntValue === $other->IntValue) {
157
                if ($this->StringValue === $other->StringValue) {
158
                    return true;
159
                }
160
            }
161
        }
162
163 15
        return false;
164
    }
165
166
167
    /**
168
     * Determina la posición relativa de esta instancia con respecto al
169
     * objeto especificado.
170
     * Nota: Cualquier objeto que no sea instancia de IntString se
171
     * considerará menor.
172
     *
173
     * @param IntString|mixed $other Objeto con el que se va a comparar.
174
     *
175
     * @return int Cero (0), si esta instancia es igual a $other; mayor
176
     *   a cero (>0), si es mayor a $other; menor a cero (<0), si es menor.
177
     * */
178
    public function compareTo($other)
179
    {
180
        $r = $this->equals($other) ? 0 : 9999;
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $r. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
181
182
        if ($r != 0) {
183
            if ($other instanceof IntString) {
184
                $r = $this->IntValue - $other->IntValue;
185
186
                if ($r == 0) {
187
                    $r = strnatcmp($this->StringValue, $other->StringValue);
188
                }
189
            } else {
190
                $r = 1;
191
            }
192
        }
193
194
        return $r;
195
    }
196
}
197