Completed
Pull Request — master (#4)
by Neo
02:47
created

AllowCorsRequests   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 103
Duplicated Lines 15.53 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 16
loc 103
ccs 0
cts 55
cp 0
rs 10
c 0
b 0
f 0
wmc 16
lcom 1
cbo 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B handle() 16 64 9
A logRequest() 0 4 1
A parseUrl() 0 14 3
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> or null; 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 || ends_with($host, '.' . $allowed_origin)) {
0 ignored issues
show
Deprecated Code introduced by
The function ends_with() has been deprecated with message: Str::endsWith() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
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 = []): void
94
    {
95
        $this->logger->warning($message, $context);
96
    }
97
98
    protected function parseUrl(string $url): string
99
    {
100
        $host = (string) parse_url($url, PHP_URL_HOST);
101
102
        if (starts_with($host, 'www.')) {
0 ignored issues
show
Deprecated Code introduced by
The function starts_with() has been deprecated with message: Str::startsWith() should be used directly instead. Will be removed in Laravel 5.9.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
103
            $host = str_replace('www.', '', $host);
104
        }
105
106
        if (strpos($host, ':') !== false) {
107
            $host = strtok($host, ':');
108
        }
109
110
        return $host;
111
    }
112
113
    protected function response(Request $request, string $message, int $code): Response
114
    {
115
        if ($request->wantsJson()) {
116
            return response()->json(['message' => $message], $code);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
117
        }
118
119
        return response($message, $code);
120
    }
121
}
122