-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathServiceProvider.php
105 lines (89 loc) · 2.43 KB
/
ServiceProvider.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
96
97
98
99
100
101
102
103
104
105
<?php
/*
* This file is part of ibrand/laravel-shopping-cart.
*
* (c) iBrand <https://www.ibrand.cc>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace iBrand\Shoppingcart;
use iBrand\Shoppingcart\Storage\SessionStorage;
use Illuminate\Support\ServiceProvider as LaravelServiceProvider;
/**
* Service provider for Laravel.
*/
class ServiceProvider extends LaravelServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Boot the provider.
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->registerMigrations();
}
//
//publish a config file
$this->publishes([
__DIR__.'/config.php' => config_path('ibrand/cart.php'),
]);
}
/**
* Register the service provider.
*/
public function register()
{
// merge configs
$this->mergeConfigFrom(
__DIR__.'/config.php', 'ibrand.cart'
);
$this->app->singleton(Cart::class, function ($app) {
$storage = config('ibrand.cart.storage');
$cart = new Cart(new $storage(), $app['events']);
if (SessionStorage::class == $storage) {
return $cart;
}
//The below code is used of database storage
$currentGuard = null;
$user = null;
$guards = array_keys(config('auth.guards'));
foreach ($guards as $guard) {
if ($user = auth($guard)->user()) {
$currentGuard = $guard;
break;
}
}
if ($user) {
//The cart name like `cart.{guard}.{user_id}`: cart.api.1
$cart->name($currentGuard.'.'.$user->id);
}else{
throw new Exception('Invalid auth.');
}
return $cart;
});
$this->app->alias(Cart::class, 'cart');
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return [Cart::class, 'cart'];
}
/**
* load migration files.
*/
protected function registerMigrations()
{
return $this->loadMigrationsFrom(__DIR__.'/../migrations');
}
}