Completed
Push — master ( 17e079...5b9b0c )
by Nelson
03:33
created

StrictObject::compare()   C

Complexity

Conditions 16
Paths 16

Size

Total Lines 62
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 21.7471

Importance

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