Completed
Push — master ( fbfec6...5d8274 )
by Elf
05:33
created

RoutingServiceProvider::extendRouter()   B

Complexity

Conditions 4
Paths 1

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 27
ccs 0
cts 21
cp 0
crap 20
rs 8.5806
1
<?php
2
3
namespace ElfSundae\Laravel\Support\Providers;
4
5
use Closure;
6
use Illuminate\Support\ServiceProvider;
7
use Illuminate\Database\Eloquent\ModelNotFoundException;
8
9
class RoutingServiceProvider extends ServiceProvider
10
{
11
    /**
12
     * Bootstrap the service provider.
13
     */
14
    public function boot()
15
    {
16
        $this->extendRouter();
17
    }
18
19
    /**
20
     * Extend router.
21
     */
22
    public function extendRouter()
23
    {
24
        $router = $this->app->make('router');
25
26
        $router->macro(
27
            'modelWithHashid',
28
            function ($key, $class, Closure $callback = null) use ($router) {
29
                $router->bind($key, function ($value) use ($router, $class, $callback) {
30
                    if (is_null($value)) {
31
                        return;
32
                    }
33
34
                    $instance = $router->container->make($class);
35
36
                    if ($model = $instance->where($instance->getRouteKeyName(), $instance->getKeyForHashid($value))->first()) {
37
                        return $model;
38
                    }
39
40
                    if ($callback instanceof Closure) {
41
                        return call_user_func($callback, $value);
42
                    }
43
44
                    throw (new ModelNotFoundException)->setModel($class);
45
                });
46
            }
47
        );
48
    }
49
}
50