Passed
Push — master ( 5b9b0c...e86726 )
by Nelson
02:47
created

StrictObject::compare()   D

Complexity

Conditions 20
Paths 19

Size

Total Lines 68
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 38
CRAP Score 20.1568

Importance

Changes 0
Metric Value
cc 20
eloc 48
nc 19
nop 2
dl 0
loc 68
ccs 38
cts 41
cp 0.9268
crap 20.1568
rs 4.1666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * PHP: Nelson Martell Library file
4
 *
5
 * Copyright © 2014-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 2014-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 NelsonMartell\Extensions\Arrays;
20
use NelsonMartell\Extensions\Numbers;
21
22
/**
23
 * Base class that encapsulates strict properties and other basic features.
24
 *
25
 *
26
 * @author Nelson Martell <[email protected]>
27
 * @since  0.1.1
28
 * @see    PropertiesHandler
29
 * */
30
class StrictObject implements IComparer, IStrictPropertiesContainer, IConvertibleToString
31
{
32
    use PropertiesHandler;
33
34
    /**
35
     * Constructor.
36
     */
37 388
    public function __construct()
38
    {
39 388
    }
40
41
    /**
42
     * Convierte esta instancia en su representación de cadena.
43
     * Para modificar el funcionamiento de esta función, debe reemplazarse
44
     * la función ObjectClass::toString()
45
     *
46
     * @return string
47
     * @see    StrictObject::toString()
48
     * */
49 34
    final public function __toString()
50
    {
51
        //$args = null;
52
        //list($args) = func_get_args();
53 34
        return $this->toString();
54
    }
55
56
    /**
57
     * Convierte la instancia actual en su representación de cadena.
58
     *
59
     * @return string
60
     * */
61
    public function toString()
62
    {
63
        $type = typeof($this);
64
65
        if (defined('CODE_ANALYSIS')) {
66
            if ($type->name != 'NelsonMartell\StrictObject') {
67
                $args = [
68
                    'access'     => 'public',
69
                    'base_class' => __CLASS__,
70
                    'class'      => $type->name,
71
                    'function'   => __FUNCTION__,
72
                ];
73
74
                $msg = msg('Using default "{base_class}::{function}" ({access}) method.', $args);
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...
75
                $msg .= msg(
76
                    ' You can replace (override) its behavior by creating "{class}::{function}" ({access}) method.',
77
                    $args
78
                );
79
80
                trigger_error($msg, E_USER_NOTICE);
81
            }
82
        }
83
84
        return '{ '.$type.' }';
85
    }
86
87
    /**
88
     * Indicates whether the specified object is equal to the current instance.
89
     *
90
     * @param mixed $other Another object to compare equality.
91
     *
92
     * @return bool Retuns default behaviour of `==`. ***This method must be overridden***.
93
     * */
94
    public function equals($other)
95
    {
96
        if (defined('CODE_ANALYSIS')) {
97
            if ($this instanceof IEquatable) {
98
                $type = typeof($this);
99
100
                $args = [
101
                    'access'     => 'public',
102
                    'base_class' => __CLASS__,
103
                    'class'      => $type->name,
104
                    'function'   => __FUNCTION__,
105
                ];
106
107
                $msg = msg(
108
                    'You implemented IEquatable, but using default "{base_class}::{function}" ({access}) method.',
109
                    $args
110
                );
111
112
                $msg .= msg(
113
                    ' You can replace (override) its behavior by creating "{class}::{function}" ({access}) method.',
114
                    $args
115
                );
116
117
                trigger_error($msg, E_USER_NOTICE);
118
            }
119
        }
120
121
        return $this == $other;
122
    }
123
124
    /**
125
     * Determines the relative position of the object on the left with respect to the one on the right.
126
     *
127
     * This method is compatible with core types and other types. You can implement `NelsonMartell\IComparable`
128
     * in order to improve the beaviout for other classes.
129
     *
130
     * This method can be used as sorting function for `usort()` function.
131
     *
132
     * **Notes:**
133
     * - Comparison is made in natural way if they are of the same type. If not, is used the PHP standard
134
     * comparison.
135
     * - If ``$left`` and ``$right`` are arrays, comparison is made by first by 'key' (as strings) and then by
136
     *   'values' (using this method recursively).
137
     *
138
     * **Override:**
139
     * You can override this method to implement a contextual sorting behaviour for `usort()` function.
140
     * If you only need to compare instances of your class with other objects, implement `NelsonMartell\IComparable`
141
     * instead.
142
     *
143
     * @param mixed $left  Left object.
144
     * @param mixed $right Right object.
145
     *
146
     * @return int|null
147
     *   Returns:
148
     *   - ``= 0`` if $left is considered equivalent to $other;
149
     *   - ``> 0`` if $left is considered greater than $other;
150
     *   - ``< 0`` if $left is considered less than $other;
151
     *   - ``null`` if $left can't be compared to $other .
152
     *
153
     * @see \strnatcmp()
154
     * @see \usort()
155
     * @see Arrays::compare()
156
     * @see IComparable
157
     * @see IComparable::compareTo()
158
     * @see IComparer::compare()
159
     * @see Numbers::compare()
160
     * */
161 110
    public static function compare($left, $right)
162
    {
163 110
        $r = null;
164
165 110
        if ($left instanceof IComparable) {
166 9
            $r = $left->compareTo($right);
167 104
        } elseif ($right instanceof IComparable) {
168 12
            $r = $right->compareTo($left);
169
170 12
            if ($r !== null) {
171 12
                $r *= -1; // Invert result
172
            }
173
        } else {
174 96
            $ltype = typeof($left);
175 96
            $rtype = typeof($right);
176
177
            // If they are of the same type.
178 96
            if ($ltype->equals($rtype)) {
179 62
                switch ($ltype->name) {
180 62
                    case 'string':
181 22
                        $r = strnatcmp($left, $right);
182 22
                        break;
183
184 48
                    case 'boolean':
185 4
                        $r = (int) $left - (int) $right;
186 4
                        break;
187
188 44
                    case 'integer':
189 26
                    case 'float':
190 26
                    case 'double':
191 22
                        $r = Numbers::compare($left, $right);
192 22
                        break;
193
194 22
                    case 'array':
195 14
                        $r = Arrays::compare($left, $right);
196 14
                        break;
197
198
                    default:
199 8
                        if ($left == $right) {
200 4
                            $r = 0;
201
                        } else {
202 62
                            $r = ($left > $right) ? +1 : -1;
203
                        }
204
                }
205
            } else {
206 34
                if ($ltype->isCustom()) {
207 8
                    if ($rtype->isCustom()) {
208 2
                        $r = ($ltype == $rtype) ? 0 : null;
209
                    } else {
210 8
                        $r = 1;
211
                    }
212 26
                } elseif ($rtype->isCustom()) {
213 6
                    $r = -1;
214
                } else {
215 20
                    if (is_numeric($left) || is_numeric($right)) {
216 20
                        $r = Numbers::compare($left, $right);
217
                    } else {
218
                        if ($left == $right) {
219
                            $r = 0;
220
                        } else {
221
                            $r = null;
222
                        }
223
                    }
224
                }
225
            }
226
        }
227
228 110
        return $r;
229
    }
230
}
231