Completed
Pull Request — master (#6)
by Hannes
03:12 queued 01:23
created

SpaceshipOperatorReplacer   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 7

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 2
lcom 0
cbo 7
dl 0
loc 31
rs 10
c 1
b 0
f 1

1 Method

Rating   Name   Duplication   Size   Complexity  
B leaveNode() 0 25 2
1
<?php
2
3
namespace Spatie\Php7to5;
4
5
use PhpParser\Node;
6
use PhpParser\Node\Expr;
7
use PhpParser\Node\Expr\BinaryOp\Equal;
8
use PhpParser\Node\Expr\BinaryOp\Smaller;
9
use PhpParser\Node\Expr\BinaryOp\Spaceship;
10
use PhpParser\Node\Expr\Ternary;
11
use PhpParser\Node\Expr\UnaryMinus;
12
use PhpParser\Node\Scalar\LNumber;
13
use PhpParser\NodeVisitorAbstract;
14
15
class SpaceshipOperatorReplacer extends NodeVisitorAbstract
16
{
17
    /**
18
     * @inheritdoc
19
     */
20
    public function leaveNode(Node $node)
21
    {
22
        if (!$node instanceof Spaceship) {
23
            return;
24
        }
25
26
        /**
27
         * Replacing
28
         * $a <=> $b
29
         * with
30
         * $a < $b ? -1 : ($a == $b ? 0 : 1)
31
         */
32
33
        $attributes = $node->getAttributes();
34
35
        $smaller = new UnaryMinus(new LNumber(1, $attributes), $attributes);
36
        $equal = new LNumber(0, $attributes);
37
        $larger = new LNumber(1, $attributes);
38
39
        $isEqual = new Equal($node->left, $node->right, $attributes);
40
        $isSmaller = new Smaller($node->left, $node->right, $attributes);
41
42
        $else = new Ternary($isEqual, $equal, $larger, $attributes);
43
        return new Ternary($isSmaller, $smaller, $else, $attributes);
44
    }
45
}
46