Completed
Push — master ( 9c04b9...73f018 )
by Marcel
06:33
created

CaptainHookServiceProvider::handleEvent()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 2
Metric Value
c 5
b 0
f 2
dl 0
loc 10
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace Mpociot\CaptainHook;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\ClientInterface;
7
use Illuminate\Support\Facades\Event;
8
use Illuminate\Support\ServiceProvider;
9
use Mpociot\CaptainHook\Commands\AddWebhook;
10
use Illuminate\Foundation\Bus\DispatchesJobs;
11
use Mpociot\CaptainHook\Commands\ListWebhooks;
12
use Mpociot\CaptainHook\Commands\DeleteWebhook;
13
use Mpociot\CaptainHook\Jobs\TriggerWebhooksJob;
14
15
/**
16
 * This file is part of CaptainHook arrrrr.
17
 *
18
 * @license MIT
19
 */
20
class CaptainHookServiceProvider extends ServiceProvider
21
{
22
    use DispatchesJobs;
23
24
    /**
25
     * The registered event listeners.
26
     *
27
     * @var array
28
     */
29
    protected $listeners;
30
31
    /**
32
     * All registered webhooks.
33
     * @var array
34
     */
35
    protected $webhooks = [];
36
37
    /**
38
     * @var Client
39
     */
40
    protected $client;
41
42
    /**
43
     * @var \Illuminate\Contracts\Cache\Repository
44
     */
45
    protected $cache;
46
47
    /**
48
     * @var \Illuminate\Contracts\Config\Repository
49
     */
50
    protected $config;
51
52
    /**
53
     * Bootstrap.
54
     */
55
    public function boot()
56
    {
57
        $this->client = new Client();
58
        $this->cache = app('Illuminate\Contracts\Cache\Repository');
59
        $this->config = app('Illuminate\Contracts\Config\Repository');
60
        $this->publishMigration();
61
        $this->publishConfig();
62
        $this->publishSparkResources();
63
        $this->listeners = collect($this->config->get('captain_hook.listeners', []))->values();
0 ignored issues
show
Documentation Bug introduced by
It seems like collect($this->config->g...s', array()))->values() of type object<Illuminate\Support\Collection> is incompatible with the declared type array of property $listeners.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
64
        $this->registerEventListeners();
65
        $this->registerRoutes();
66
    }
67
68
    /**
69
     * Register the service provider.
70
     *
71
     * @return void
72
     */
73
    public function register()
74
    {
75
        $this->registerCommands();
76
    }
77
78
    /**
79
     * Publish migration.
80
     */
81
    protected function publishMigration()
82
    {
83
        $migrations = [
84
            __DIR__.'/../../database/2015_10_29_000000_captain_hook_setup_table.php' => database_path('/migrations/'.date('Y_m_d').'_000000_captain_hook_setup_table.php'),
85
            __DIR__.'/../../database/2015_10_29_000001_captain_hook_setup_logs_table.php' => database_path('/migrations/'.date('Y_m_d').'_000001_captain_hook_setup_logs_table.php'),
86
        ];
87
88
        foreach ($migrations as $migration => $toPath) {
89
            preg_match('/_captain_hook_.*\.php/', $migration, $match);
90
            $published_migration = glob(database_path('/migrations/*'.$match[0]));
91
            if (count($published_migration) !== 0) {
92
                unset($migrations[$migration]);
93
            }
94
        }
95
96
        $this->publishes($migrations, 'migrations');
97
    }
98
99
    /**
100
     * Publish configuration file.
101
     */
102
    protected function publishConfig()
103
    {
104
        $this->publishes([
105
            __DIR__.'/../../config/config.php' => config_path('captain_hook.php'),
106
        ]);
107
    }
108
109
    protected function publishSparkResources()
110
    {
111
        $this->loadViewsFrom(__DIR__.'/../../resources/views/', 'captainhook');
112
113
        $this->publishes([
114
            __DIR__.'/../../resources/assets/js/' => base_path('resources/assets/js/components/'),
115
            __DIR__ . '/../../resources/views/' => base_path('resources/views/vendor/captainhook/settings/'),
116
        ], 'spark-resources');
117
    }
118
119
    /**
120
     * Register all active event listeners.
121
     */
122
    protected function registerEventListeners()
123
    {
124
        foreach ($this->listeners as $eventName) {
125
            $this->app[ 'events' ]->listen($eventName, [$this, 'handleEvent']);
126
        }
127
    }
128
129
    /**
130
     * @param array $listeners
131
     */
132
    public function setListeners($listeners)
133
    {
134
        $this->listeners = $listeners;
135
136
        $this->registerEventListeners();
137
    }
138
139
    /**
140
     * @param array $webhooks
141
     */
142
    public function setWebhooks($webhooks)
143
    {
144
        $this->webhooks = $webhooks;
145
        $this->getCache()->rememberForever(Webhook::CACHE_KEY, function () {
146
            return $this->webhooks;
147
        });
148
    }
149
150
    /**
151
     * @return \Illuminate\Support\Collection
152
     */
153
    public function getWebhooks()
154
    {
155
        if (! $this->getCache()->has(Webhook::CACHE_KEY)) {
156
            $this->getCache()->rememberForever(Webhook::CACHE_KEY, function () {
157
                return Webhook::all();
158
            });
159
        }
160
161
        return collect($this->getCache()->get(Webhook::CACHE_KEY));
162
    }
163
164
    /**
165
     * @return \Illuminate\Contracts\Cache\Repository
166
     */
167
    public function getCache()
168
    {
169
        return $this->cache;
170
    }
171
172
    /**
173
     * @param \Illuminate\Contracts\Cache\Repository $cache
174
     */
175
    public function setCache($cache)
176
    {
177
        $this->cache = $cache;
178
    }
179
180
    /**
181
     * @param ClientInterface $client
182
     */
183
    public function setClient($client)
184
    {
185
        $this->client = $client;
0 ignored issues
show
Documentation Bug introduced by
$client is of type object<GuzzleHttp\ClientInterface>, but the property $client was declared to be of type object<GuzzleHttp\Client>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
186
    }
187
188
    /**
189
     * @param \Illuminate\Contracts\Config\Repository $config
190
     */
191
    public function setConfig($config)
192
    {
193
        $this->config = $config;
194
    }
195
196
    /**
197
     * Event listener.
198
     *
199
     * @param $eventData
200
     */
201
    public function handleEvent($eventData)
202
    {
203
        $eventName = Event::firing();
204
        $webhooks = $this->getWebhooks()->where('event', $eventName);
205
        $webhooks = $webhooks->filter($this->config->get('captain_hook.filter', null));
206
207
        if (! $webhooks->isEmpty()) {
208
            $this->dispatch(new TriggerWebhooksJob($webhooks, $eventData));
209
        }
210
    }
211
212
    /**
213
     * Register the artisan commands.
214
     */
215
    protected function registerCommands()
216
    {
217
        $this->app[ 'hook.list' ] = $this->app->share(function () {
218
            return new ListWebhooks();
219
        });
220
221
        $this->app[ 'hook.add' ] = $this->app->share(function () {
222
            return new AddWebhook();
223
        });
224
225
        $this->app[ 'hook.delete' ] = $this->app->share(function () {
226
            return new DeleteWebhook();
227
        });
228
229
        $this->commands(
230
            'hook.list',
231
            'hook.add',
232
            'hook.delete'
233
        );
234
    }
235
    /**
236
     * Register predefined routes used for Spark
237
     */
238
    protected function registerRoutes()
239
    {
240
        if (class_exists('Laravel\Spark\Providers\AppServiceProvider')) {
241
            include __DIR__ . '/../../routes.php';
242
        }
243
    }
244
}
245