Completed
Pull Request — master (#416)
by Colin
05:36
created

RedirectOnOldSlug::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 2
eloc 9
nc 2
nop 2
1
<?php namespace Cviebrock\EloquentSluggable\Middleware;
2
3
use Illuminate\Http\RedirectResponse;
4
use Illuminate\Http\Request;
5
use Illuminate\Routing\RouteUrlGenerator;
6
use Illuminate\Support\Facades\DB;
7
8
class RedirectOnOldSlug
9
{
10
    /**
11
     * Handle an incoming request.
12
     *
13
     * @param  \Illuminate\Http\Request $request
14
     * @param  \Closure                 $next
15
     *
16
     * @return mixed
17
     * @throws \Illuminate\Routing\Exceptions\UrlGenerationException
18
     */
19
    public function handle(Request $request, \Closure $next)
20
    {
21
        $route = $request->route();
22
        if ($oldSlug = $this->findOldSlug($route->parameter('slug'))) {
23
            $currentSlug = $this->findSlugFrom($oldSlug);
24
            $path = $this->routeGenerator($request)->to(
25
                $request->route(),
0 ignored issues
show
Documentation introduced by
$request->route() is of type object|string, but the function expects a object<Illuminate\Routing\Route>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
26
                array_merge($route->parameters(), ['slug' => $currentSlug])
27
            );
28
29
            return new RedirectResponse($path);
30
        }
31
32
        return $next($request);
33
    }
34
35
    private function findOldSlug($slug)
36
    {
37
        return DB::table('old_slugs')->where('slug', $slug)->first();
38
    }
39
40
    private function findSlugFrom($oldSlug)
41
    {
42
        return app($oldSlug->model)->find($oldSlug->entity_id)->slug;
43
    }
44
45
    private function routeGenerator($request)
46
    {
47
        return new RouteUrlGenerator(app('url'), $request);
48
    }
49
}
50