MessageProcessor::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
3
4
namespace SirSova\Webhooks;
5
6
use Illuminate\Contracts\Bus\Dispatcher;
7
use Illuminate\Contracts\Bus\QueueingDispatcher;
8
use SirSova\Webhooks\Contracts\SubscriberRepository;
9
use SirSova\Webhooks\Contracts\MessageProcessor as ProcessorContract;
10
use SirSova\Webhooks\Jobs\ProcessWebhook;
11
12
class MessageProcessor implements ProcessorContract
13
{
14
    /**
15
     * @var SubscriberRepository
16
     */
17
    private $subscriberRepository;
18
    /**
19
     * @var Dispatcher
20
     */
21
    private $dispatcher;
22
    /**
23
     * @var string|null
24
     */
25
    private $queue;
26
    
27
    public function __construct(SubscriberRepository $subscriberRepository, Dispatcher $dispatcher, ?string $queue = null)
28
    {
29
        $this->subscriberRepository = $subscriberRepository;
30
        $this->dispatcher = $dispatcher;
31
        $this->queue = $queue;
32
    }
33
34
    /**
35
     * @param Message $message
36
     *
37
     * @return void
38
     */
39
    public function process(Message $message): void
40
    {
41
        $subscribers = $this->subscriberRepository->findAllByEvent($message->type(), true);
42
        
43
        foreach ($subscribers as $subscriber) {
44
            $job = new ProcessWebhook(new Webhook($message, $subscriber->url()));
45
46
            if ($this->dispatcher instanceof QueueingDispatcher && $this->queue) {
47
                $job->onQueue($this->queue);
48
                $this->dispatcher->dispatchToQueue($job);
49
            } else {
50
                $this->dispatcher->dispatch($job);
51
            }
52
        }
53
    }
54
}
55