Completed
Push — master ( 110493...8c0c1c )
by Avtandil
02:46
created

AllowCorsRequests::handle()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 64
Code Lines 38

Duplication

Lines 16
Ratio 25 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 38
nc 20
nop 2
dl 16
loc 64
ccs 0
cts 49
cp 0
crap 72
rs 6.8232
c 1
b 0
f 0

How to fix   Long Method   

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
 * This file is part of the Laravel Lodash package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
declare(strict_types=1);
11
12
namespace Longman\LaravelLodash\Middlewares;
13
14
use Closure;
15
use Illuminate\Http\Request;
16
use Psr\Log\LoggerInterface;
17
use Symfony\Component\HttpFoundation\Response;
18
19
class AllowCorsRequests
20
{
21
    protected $logger;
22
23
    public function __construct(LoggerInterface $logger)
24
    {
25
        $this->logger = $logger;
26
    }
27
28
    public function handle(Request $request, Closure $next)
29
    {
30
        if (! $request->headers->has('Origin')) {
31
            return $next($request);
32
        }
33
34
        $origin = $request->headers->get('Origin', '');
35
        $host = $this->parseUrl($origin);
0 ignored issues
show
Bug introduced by
It seems like $origin defined by $request->headers->get('Origin', '') on line 34 can also be of type array<integer,string>; however, Longman\LaravelLodash\Mi...orsRequests::parseUrl() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
36 View Code Duplication
        if (empty($host)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
37
            $this->logRequest('Origin is invalid', [
38
                'origin' => $origin,
39
                'parsed' => $host,
40
            ]);
41
42
            return $this->response($request, 'Origin is invalid', Response::HTTP_BAD_REQUEST);
43
        }
44
45
        $allowed_origins = config('lodash.cors.allow_origins', []);
46
        $current_app = $this->parseUrl(config('app.url', ''));
47
        if (! empty($host)) {
48
            $allowed_origins[] = $current_app;
49
        }
50
51
        $found = false;
52
        foreach ($allowed_origins as $allowed_origin) {
53
            if ($host === $allowed_origin) {
54
                $found = true;
55
                break;
56
            }
57
        }
58
59 View Code Duplication
        if (! $found) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
60
            $this->logRequest('Origin is not allowed', [
61
                'origin' => $origin,
62
                'parsed' => $host,
63
            ]);
64
65
            return $this->response($request, 'Origin is not allowed', Response::HTTP_METHOD_NOT_ALLOWED);
66
        }
67
68
        if ($request->method() === Request::METHOD_OPTIONS) {
69
            $allowed_headers = config('lodash.cors.allow_headers');
70
            $allowed_methods = config('lodash.cors.allow_methods');
71
72
            $response = $this->response($request, 'Allowed', Response::HTTP_OK);
73
74
            $response->headers->set('Access-Control-Allow-Origin', $origin);
75
            $response->headers->set('Access-Control-Allow-Credentials', 'true');
76
77
            $response->headers->set('Access-Control-Allow-Methods', implode(',', $allowed_methods));
78
            $response->headers->set('Access-Control-Allow-Headers', implode(',', $allowed_headers));
79
            $response->headers->set('Access-Control-Max-Age', '1728000');
80
81
            return $response;
82
        }
83
84
        /** @var \Illuminate\Http\Response $response */
85
        $response = $next($request);
86
87
        $response->headers->set('Access-Control-Allow-Origin', $origin);
88
        $response->headers->set('Access-Control-Allow-Credentials', 'true');
89
90
        return $response;
91
    }
92
93
    protected function logRequest(string $message, array $context = [])
94
    {
95
        $this->logger->warning($message, $context);
96
    }
97
98
    protected function parseUrl(string $url): string
99
    {
100
        $host = parse_url($url, PHP_URL_HOST);
101
102
        if (starts_with($host, 'www.')) {
0 ignored issues
show
Security Bug introduced by
It seems like $host defined by parse_url($url, PHP_URL_HOST) on line 100 can also be of type false; however, starts_with() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
103
            $host = str_replace('www.', '', $host);
104
        }
105
106
        return $host ?? '';
107
    }
108
109
    protected function response(Request $request, string $message, int $code): Response
110
    {
111
        if ($request->wantsJson()) {
112
            return response()->json(['message' => $message], $code);
113
        }
114
115
        return response($message, $code);
116
    }
117
}
118