Passed
Push — master ( b5d6f6...ea35d6 )
by Biao
03:50
created

HttpRequestCollector::findRouteUri()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 9
eloc 18
c 2
b 0
f 0
nc 8
nop 1
dl 0
loc 26
rs 8.0555
1
<?php
2
0 ignored issues
show
Coding Style introduced by
Missing file doc comment
Loading history...
3
namespace Hhxsv5\LaravelS\Components\Prometheus\Collectors;
4
5
use Closure;
6
use Hhxsv5\LaravelS\Components\MetricCollector;
7
use Illuminate\Http\Request;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Request was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
class HttpRequestCollector extends MetricCollector
0 ignored issues
show
Coding Style introduced by
Missing doc comment for class HttpRequestCollector
Loading history...
10
{
11
    protected $routes          = [];
12
    protected $routesByUses    = [];
13
    protected $routesByClosure = [];
14
15
    public function __construct(array $config)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
16
    {
17
        parent::__construct($config);
18
19
        $routes = method_exists(app(), 'getRoutes') ? app()->getRoutes() : app('router')->getRoutes();
0 ignored issues
show
Bug introduced by
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

19
        $routes = method_exists(/** @scrutinizer ignore-call */ app(), 'getRoutes') ? app()->getRoutes() : app('router')->getRoutes();
Loading history...
20
        if ($routes instanceof \Illuminate\Routing\RouteCollection) { // Laravel
0 ignored issues
show
Bug introduced by
The type Illuminate\Routing\RouteCollection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
            foreach ($routes->getRoutes() as $route) {
22
                $method = $route->methods()[0];
23
                $uri = '/' . ltrim($route->uri(), '/');
24
                $this->routes[$method . $uri] = $uri;
25
26
                $action = $route->getAction();
27
                if (is_string($action['uses'])) { // Uses
28
                    $this->routesByUses[$method . $action['uses']] = $uri;
29
                } elseif ($action['uses'] instanceof Closure) {  // Closure
30
                    $objectId = spl_object_hash($action['uses']);
31
                    $this->routesByClosure[$method . $objectId] = $uri;
32
                }
33
            }
34
        } elseif (is_array($routes)) { // Lumen
35
            $this->routes = $routes;
36
            foreach ($routes as $route) {
37
                if (isset($route['action']['uses'])) { // Uses
38
                    $this->routesByUses[$route['method'] . $route['action']['uses']] = $route['uri'];
39
                }
40
                if (isset($route['action'][0]) && $route['action'][0] instanceof Closure) { // Closure
41
                    $objectId = spl_object_hash($route['action'][0]);
42
                    $this->routesByClosure[$route['method'] . $objectId] = $route['uri'];
43
                }
44
            }
45
        }
46
    }
47
48
    public function collect(array $params = [])
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function collect()
Loading history...
49
    {
50
        if (!$this->config['enable']) {
51
            return;
52
        }
53
54
        /**@var \Illuminate\Http\Request $request */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
55
        /**@var \Illuminate\Http\Response $response */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
56
        list($request, $response) = $params;
57
58
        $status = $response->getStatusCode();
59
        if (isset($this->config['ignored_http_codes'][$status])) {
60
            // Ignore the requests.
61
            return;
62
        }
63
64
        $uri = $this->findRouteUri($request);
65
        $cost = microtime(true) - $request->server('REQUEST_TIME_FLOAT');
66
67
        // Http Request Stats
68
        $requestLabels = http_build_query([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
69
            'method' => $request->getMethod(),
70
            'uri'    => $uri,
71
            'status' => $status,
72
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
73
74
        // Key Format: prefix+metric_name+metric_type+metric_labels
75
        $countKey = implode($this->config['apcu_key_separator'], [$this->config['apcu_key_prefix'], 'http_server_requests_seconds_count', 'summary', $requestLabels]);
76
        $sumKey = implode($this->config['apcu_key_separator'], [$this->config['apcu_key_prefix'], 'http_server_requests_seconds_sum', 'summary', $requestLabels]);
77
        apcu_inc($countKey, 1, $success, $this->config['apcu_key_max_age']);
78
        apcu_inc($sumKey, round($cost * 1000000), $success, $this->config['apcu_key_max_age']); // Time unit: μs
0 ignored issues
show
Bug introduced by
round($cost * 1000000) of type double is incompatible with the type integer expected by parameter $step of apcu_inc(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

78
        apcu_inc($sumKey, /** @scrutinizer ignore-type */ round($cost * 1000000), $success, $this->config['apcu_key_max_age']); // Time unit: μs
Loading history...
79
    }
80
81
    protected function findRouteUri(Request $request)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function findRouteUri()
Loading history...
82
    {
83
        $method = $request->getMethod();
84
        $uri = $request->getPathInfo();
85
        $key = $method . $uri;
86
        if (isset($this->routes[$key])) {
87
            return $uri;
88
        }
89
90
        $route = $request->route();
91
        if ($route instanceof \Illuminate\Routing\Route) { // Laravel
0 ignored issues
show
Bug introduced by
The type Illuminate\Routing\Route was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
92
            $uri = $route->uri();
93
        } elseif (is_array($route)) { // Lumen
94
            if (isset($route[1]['uses'])) {
95
                $key = $method . $route[1]['uses'];
96
                if (isset($this->routesByUses[$key])) {
97
                    $uri = $this->routesByUses[$key];
98
                }
99
            } elseif (isset($route[1][0]) && $route[1][0] instanceof Closure) {
100
                $key = $method . spl_object_hash($route[1][0]);
101
                if (isset($this->routesByClosure[$key])) {
102
                    $uri = $this->routesByClosure[$key];
103
                }
104
            }
105
        }
106
        return $uri;
107
    }
108
}