Cors::handle()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 4
c 2
b 1
f 0
dl 0
loc 8
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
namespace TobyMaxham\Helper\Http\Middleware;
4
5
use Closure;
6
use Illuminate\Http\Request;
7
8
/**
9
 * Class Cors.
10
 *
11
 * @author Tobias Maxham <[email protected]>
12
 */
13
class Cors
14
{
15
    /**
16
     * Handle an incoming request.
17
     *
18
     * @param Request $request
19
     * @param Closure $next
20
     *
21
     * @return mixed
22
     */
23
    public function handle(Request $request, Closure $next)
24
    {
25
        $response = $next($request);
26
        if (! method_exists($response, 'header')) {
27
            return $response;
28
        }
29
30
        return $this->addCorsHeaders($response);
31
    }
32
33
    /**
34
     * @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Http\Response $response
35
     *
36
     * @return \Symfony\Component\HttpFoundation\Response|\Illuminate\Http\Response
37
     */
38
    private function addCorsHeaders($response)
39
    {
40
        if (! $response->headers->has('Access-Control-Allow-Origin')) {
41
            $response = $response->header('Access-Control-Allow-Origin', config('tma-helper.cors.allowedOrigins', 'localhost'))
0 ignored issues
show
Bug introduced by
The method header() does not exist on Symfony\Component\HttpFoundation\Response. It seems like you code against a sub-type of Symfony\Component\HttpFoundation\Response such as Illuminate\Http\Response or Illuminate\Http\JsonResponse or Illuminate\Http\RedirectResponse. ( Ignorable by Annotation )

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

41
            $response = $response->/** @scrutinizer ignore-call */ header('Access-Control-Allow-Origin', config('tma-helper.cors.allowedOrigins', 'localhost'))
Loading history...
42
                ->header('Access-Control-Allow-Methods', config('tma-helper.cors.allowedMethods'));
43
44
            foreach (config('tma-helper.cors.headers', []) as $header => $value) {
45
                $response->header($header, $value);
46
            }
47
        }
48
49
        return $response;
50
    }
51
}
52