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

RoutingServiceProvider   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 41
ccs 0
cts 25
cp 0
rs 10
wmc 5
lcom 1
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A boot() 0 4 1
B extendRouter() 0 27 4
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