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

AllowCorsRequests   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 99
Duplicated Lines 16.16 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 16
loc 99
ccs 0
cts 72
cp 0
rs 10
c 1
b 0
f 0
wmc 14
lcom 1
cbo 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C handle() 16 64 8
A logRequest() 0 4 1
A parseUrl() 0 10 2
A response() 0 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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