This repository has been archived by the owner on Mar 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
FakeIdServiceProvider.php
95 lines (81 loc) · 3.19 KB
/
FakeIdServiceProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php namespace Propaganistas\LaravelFakeId;
use Closure;
use Illuminate\Support\ServiceProvider;
use Jenssegers\Optimus\Optimus;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class FakeIdServiceProvider extends ServiceProvider
{
/**
* Boots the service provider.
*
* @return void
*/
public function boot()
{
// Publish config.
$this->publishes([
__DIR__ . '/../config/config.php' => config_path('fakeid.php'),
], 'config');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
// Merge default config.
$this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'fakeid');
// Register setup command.
$this->app->singleton('fakeid.command.setup', function ($app) {
return new Commands\FakeIdSetupCommand();
});
$this->commands('fakeid.command.setup');
// Register FakeId driver.
$this->app->singleton('Jenssegers\Optimus\Optimus', function ($app) {
return new Optimus(
$app['config']['fakeid.prime'],
$app['config']['fakeid.inverse'],
$app['config']['fakeid.random']
);
});
$this->app->alias('Jenssegers\Optimus\Optimus', 'optimus');
$this->app->alias('Jenssegers\Optimus\Optimus', 'fakeid');
$this->registerRouterMacro();
}
/**
* Register the custom router macro.
*/
protected function registerRouterMacro()
{
$this->app['router']->macro('fakeIdModel', function ($key, $class, Closure $callback = null) {
$this->bind($key, function ($value) use ($key, $class, $callback) {
if (is_null($value)) {
return;
}
// For model binders, we will attempt to retrieve the models using the first
// method on the model instance. If we cannot retrieve the models we'll
// throw a not found exception otherwise we will return the instance.
$instance = $this->container->make($class);
// Decode FakeId first if applicable.
if (in_array('Propaganistas\LaravelFakeId\FakeIdTrait', class_uses_recursive($class))) {
try {
$value = $this->container->make('fakeid')->decode($value);
} catch (\InvalidArgumentException $e) {
throw config('app.debug') ? $e : new NotFoundHttpException;
}
}
if ($model = $instance->where($instance->getRouteKeyName(), $value)->first()) {
return $model;
}
// If a callback was supplied to the method we will call that to determine
// what we should do when the model is not found. This just gives these
// developer a little greater flexibility to decide what will happen.
if ($callback instanceof Closure) {
return call_user_func($callback, $value);
}
throw new NotFoundHttpException;
});
});
}
}