Api::index()   F
last analyzed

Complexity

Conditions 18
Paths 4342

Size

Total Lines 75

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 0
Metric Value
dl 0
loc 75
ccs 0
cts 64
cp 0
rs 0.7
c 0
b 0
f 0
cc 18
nc 4342
nop 0
crap 342

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
                if ($last) {
70
                    $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...
71
                    $tracer->setActive($last);
72
                }
73
74
                $changesSpan = $tracer->createSpan('event.changes');
75
                $this->get(Event::class)->fireChanges($request[0]->job);
76
                $changesSpan->end();
77
78
                if ($last) {
79
                    $last->end();
80
                }
81
            }
82
        } catch (Exception $e) {
83
            return ['success' => false, 'message' => 'Fire changes failure: '.$e->getMessage()];
84
        }
85
86
        try {
87
            $response[0]['timing'] = microtime(true) - $tracer->getActiveSpan()->getStart();
88
            if ($this->get(Service::class)->getName() != 'audit') {
89
                if ($response[0]['timing'] >= 0.05) {
90
                    $this->get(Exporter::class)->flush($tracer, $this->get(Transport::class));
91
                }
92
            }
93
        } catch (Exception $e) {
94
            // no traces is not a problem
95
        }
96
97
        return is_array($data) ? $response : $response[0];
98
    }
99
100
    private function process($rpc)
101
    {
102
        if (!property_exists($rpc, 'job')) {
103
            return [
104
                'success' => false,
105
                'message' => 'Invalid rpc format: no job',
106
            ];
107
        }
108
109
        if (!property_exists($rpc, 'params')) {
110
            return [
111
                'success' => false,
112
                'message' => 'Invalid rpc format: no params',
113
            ];
114
        }
115
116
        try {
117
            $params = is_object($rpc->params) ? get_object_vars($rpc->params) : [];
118
            $data = $this->dispatch(strtolower($rpc->job), $params);
119
            $data = $this->removeSystemObjects($data);
120
121
            return [
122
                'success' => true,
123
                'data' => $data,
124
            ];
125
        } catch (Exception $e) {
126
            $error = [
127
                'success' => false,
128
                'message' => $e->getMessage(),
129
                'service' => $this->get(Service::class)->getName(),
130
                'trace' => explode(PHP_EOL, $e->getTraceAsString()),
131
            ];
132
            if (property_exists($e, 'remoteTrace')) {
133
                $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...
134
            }
135
            return $error;
136
        }
137
    }
138
139
    private function removeSystemObjects($data)
140
    {
141
        if (!$data) {
142
            return [];
143
        }
144
145
        if (is_object($data)) {
146
            $data = get_object_vars($data);
147
        }
148
149
        foreach ($data as $k => $v) {
150
            if (is_array($v) || is_object($v)) {
151
                if ($v instanceof Application) {
152
                    unset($data[$k]);
153
                } else {
154
                    $data[$k] = $this->removeSystemObjects($v);
155
                }
156
            }
157
        }
158
159
        return $data;
160
    }
161
}
162