Completed
Pull Request — master (#10)
by
unknown
04:25
created

AllowCorsRequests::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Longman\LaravelLodash\Middlewares;
6
7
use Closure;
8
use Illuminate\Http\Request;
9
use Illuminate\Support\Str;
10
use Psr\Log\LoggerInterface;
11
use Symfony\Component\HttpFoundation\Response;
12
13
use const PHP_URL_HOST;
14
15
class AllowCorsRequests
16
{
17
    protected $logger;
18
19 5
    public function __construct(LoggerInterface $logger)
20
    {
21 5
        $this->logger = $logger;
22 5
    }
23
24 5
    public function handle(Request $request, Closure $next)
25
    {
26 5
        if (! $request->headers->has('Origin')) {
27 1
            return $next($request);
28
        }
29
30 4
        $origin = $request->headers->get('Origin', '');
31 4
        $host = $this->parseUrl($origin);
0 ignored issues
show
Bug introduced by
It seems like $origin defined by $request->headers->get('Origin', '') on line 30 can also be of type array 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...
32 4 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...
33 1
            $this->logRequest('Origin is invalid', [
34 1
                'origin' => $origin,
35 1
                'parsed' => $host,
36
            ]);
37
38 1
            return $this->response($request, 'Origin is invalid', Response::HTTP_BAD_REQUEST);
39
        }
40
41 4
        $allowed_origins = config('lodash.cors.allow_origins', []);
42 4
        $current_app = $this->parseUrl((string) config('app.url', ''));
43 4
        if (! empty($host)) {
44 4
            $allowed_origins[] = $current_app;
45
        }
46
47 4
        $found = false;
48 4
        foreach ($allowed_origins as $allowed_origin) {
49 4
            if ($host === $allowed_origin || Str::endsWith($host, '.' . $allowed_origin)) {
50 3
                $found = true;
51 3
                break;
52
            }
53
        }
54
55 4 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...
56 1
            $this->logRequest('Origin is not allowed', [
57 1
                'origin' => $origin,
58 1
                'parsed' => $host,
59
            ]);
60
61 1
            return $this->response($request, 'Origin is not allowed', Response::HTTP_METHOD_NOT_ALLOWED);
62
        }
63
64 3
        if ($request->method() === Request::METHOD_OPTIONS) {
65 1
            $allowed_headers = config('lodash.cors.allow_headers', []);
66 1
            $allowed_methods = config('lodash.cors.allow_methods', []);
67
68 1
            $response = $this->response($request, 'Allowed', Response::HTTP_OK);
69
70 1
            $response->headers->set('Access-Control-Allow-Origin', $origin);
71 1
            $response->headers->set('Access-Control-Allow-Credentials', 'true');
72
73 1
            $response->headers->set('Access-Control-Allow-Methods', implode(',', $allowed_methods));
74 1
            $response->headers->set('Access-Control-Allow-Headers', implode(',', $allowed_headers));
75 1
            $response->headers->set('Access-Control-Max-Age', '1728000');
76
77 1
            return $response;
78
        }
79
80
        /** @var \Illuminate\Http\Response $response */
81 2
        $response = $next($request);
82
83 2
        $response->headers->set('Access-Control-Allow-Origin', $origin);
84 2
        $response->headers->set('Access-Control-Allow-Credentials', 'true');
85
86 2
        return $response;
87
    }
88
89 1
    protected function logRequest(string $message, array $context = []): void
90
    {
91 1
        $this->logger->warning($message, $context);
92 1
    }
93
94 4
    protected function parseUrl(string $url): string
95
    {
96 4
        $host = (string) parse_url($url, PHP_URL_HOST);
97
98 4
        if (Str::startsWith($host, 'www.')) {
99
            $host = str_replace('www.', '', $host);
100
        }
101
102 4
        if (strpos($host, ':') !== false) {
103
            $host = strtok($host, ':');
104
        }
105
106 4
        return $host;
107
    }
108
109 2
    protected function response(Request $request, string $message, int $code): Response
110
    {
111 2
        if ($request->wantsJson()) {
112
            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...
113
        }
114
115 2
        return response($message, $code);
116
    }
117
}
118