Completed
Push — master ( f08c31...be488a )
by Dmitry
03:45
created

Api::index()   F

Complexity

Conditions 14
Paths 942

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
dl 0
loc 67
ccs 0
cts 57
cp 0
rs 2.4644
c 0
b 0
f 0
cc 14
nc 942
nop 0
crap 210

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
namespace Basis\Controller;
4
5
use Basis\Application;
6
use Basis\Context;
7
use Basis\Event;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Basis\Controller\Event.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Basis\Service;
9
use Basis\Toolkit;
10
use Exception;
11
use OpenTelemetry\Tracing\Tracer;
12
use OpenTelemetry\Transport;
13
use OpenTelemetry\Exporter;
14
15
class Api
16
{
17
    use Toolkit;
18
19
    public function __process()
20
    {
21
        return $this->index();
22
    }
23
24
    public function index()
25
    {
26
        if (!array_key_exists('rpc', $_REQUEST)) {
27
            return [
28
                'success' => false,
29
                'message' => 'No rpc defined',
30
            ];
31
        }
32
        $data = json_decode($_REQUEST['rpc']);
33
34
        if (!$data) {
35
            return [
36
                'success' => false,
37
                'message' => 'Invalid rpc format',
38
            ];
39
        }
40
41
        $tracer = $this->get(Tracer::class);
42
        if ($data->context) {
43
            $this->get(Context::class)->apply($data->context);
44
        }
45
46
        $request = is_array($data) ? $data : [$data];
47
48
        $response = [];
49
        foreach ($request as $rpc) {
50
            $result = $this->process($rpc);
51
            if (is_null($result)) {
52
                $result = [];
53
            }
54
            if (property_exists($rpc, 'tid')) {
55
                $result['tid'] = $rpc->tid;
56
            }
57
            $response[] = $result;
58
        }
59
60
        try {
61
            if ($this->get(Event::class)->hasChanges()) {
62
                $active = $tracer->getActiveSpan();
63
                foreach ($tracer->getSpans() as $candidate) {
64
                    if ($candidate->getParentSpanContext() == $active->getSpanContext()) {
65
                        $last = $candidate;
66
                        break;
67
                    }
68
                }
69
                $last->setInterval($last->getStart(), 0);
0 ignored issues
show
Bug introduced by
The variable $last does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
70
                $tracer->setActive($last);
71
72
                $changesSpan = $tracer->createSpan('event.changes');
73
                $this->get(Event::class)->fireChanges($request[0]->job);
74
                $changesSpan->end();
75
76
                $last->end();
77
            }
78
        } catch (Exception $e) {
79
            return ['success' => false, 'message' => 'Fire changes failure: '.$e->getMessage()];
80
        }
81
82
        try {
83
            $response[0]['timing'] = microtime(true) - $tracer->getActiveSpan()->getStart();
84
            $this->get(Exporter::class)->flush($tracer, $this->get(Transport::class));
85
        } catch (Exception $e) {
86
            // no traces is not a problem
87
        }
88
89
        return is_array($data) ? $response : $response[0];
90
    }
91
92
    private function process($rpc)
93
    {
94
        if (!property_exists($rpc, 'job')) {
95
            return [
96
                'success' => false,
97
                'message' => 'Invalid rpc format: no job',
98
            ];
99
        }
100
101
        if (!property_exists($rpc, 'params')) {
102
            return [
103
                'success' => false,
104
                'message' => 'Invalid rpc format: no params',
105
            ];
106
        }
107
108
        try {
109
            $params = is_object($rpc->params) ? get_object_vars($rpc->params) : [];
110
            $data = $this->dispatch(strtolower($rpc->job), $params);
111
            $data = $this->removeSystemObjects($data);
112
113
            return [
114
                'success' => true,
115
                'data' => $data,
116
            ];
117
        } catch (Exception $e) {
118
            $error = [
119
                'success' => false,
120
                'message' => $e->getMessage(),
121
                'service' => $this->get(Service::class)->getName(),
122
                'trace' => explode(PHP_EOL, $e->getTraceAsString()),
123
            ];
124
            if (property_exists($e, 'remoteTrace')) {
125
                $error['remoteTrace'] = $e->remoteTrace;
0 ignored issues
show
Bug introduced by
The property remoteTrace does not seem to exist in Exception.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
126
            }
127
            return $error;
128
        }
129
    }
130
131
    private function removeSystemObjects($data)
132
    {
133
        if (!$data) {
134
            return [];
135
        }
136
137
        if (is_object($data)) {
138
            $data = get_object_vars($data);
139
        }
140
141
        foreach ($data as $k => $v) {
142
            if (is_array($v) || is_object($v)) {
143
                if ($v instanceof Application) {
144
                    unset($data[$k]);
145
                } else {
146
                    $data[$k] = $this->removeSystemObjects($v);
147
                }
148
            }
149
        }
150
151
        return $data;
152
    }
153
}
154