Passed
Push — master ( b19e7d...24f7a7 )
by Hirofumi
06:21
created

SendFreshNotificationsHandler::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Shippinno\Notification\Application\Command;
5
6
use Psr\Log\LoggerAwareTrait;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
use Shippinno\Notification\Domain\Model\Notification;
10
use Shippinno\Notification\Domain\Model\NotificationIsFreshSpecification;
11
use Shippinno\Notification\Domain\Model\NotificationRepository;
12
use Shippinno\Notification\Domain\Model\SendNotification as SendNotificationService;
13
14
class SendFreshNotificationsHandler
15
{
16
    use LoggerAwareTrait;
17
18
    /**
19
     * @var NotificationRepository
20
     */
21
    protected $notificationRepository;
22
23
    /**
24
     * @var SendNotificationService
25
     */
26
    protected $sendNotificationService;
27
28
    /**
29
     * @param NotificationRepository $notificationRepository
30
     * @param SendNotificationService $sendNotificationService
31
     * @param LoggerInterface|null $logger
32
     */
33 1
    public function __construct(
34
        NotificationRepository $notificationRepository,
35
        SendNotificationService $sendNotificationService,
36
        LoggerInterface $logger = null
37
    ) {
38 1
        $this->notificationRepository = $notificationRepository;
39 1
        $this->sendNotificationService = $sendNotificationService;
40 1
        $this->logger = is_null($logger) ? new NullLogger : $logger;
41 1
    }
42
43
    /**
44
     * @param SendFreshNotifications $command
45
     */
46 1
    public function handle(SendFreshNotifications $command): void
47
    {
48 1
        $specification = new NotificationIsFreshSpecification;
49 1
        if (!is_null($command->specification())) {
50 1
            $specification = $specification->and($command->specification());
51
        }
52 1
        $notifications = $this->notificationRepository->query(
53 1
            $specification,
54 1
            ['notificationId' => 'ASC'],
55 1
            100
56
        );
57 1
        $this->logger->debug(sprintf('Sending %s fresh notifications.', count($notifications)));
58 1
        $sent = 0;
59 1
        foreach ($notifications as $notification) {
60 1
            $this->send($notification);
61
        }
62 1
        $this->logger->debug(sprintf('Sent %s notifications successfully.', $sent));
63 1
    }
64
65
    /**
66
     * @param Notification $notification
67
     */
68 1
    protected function send(Notification $notification): void
69
    {
70 1
        $this->sendNotificationService->execute($notification);
71 1
        $this->notificationRepository->persist($notification);
72 1
    }
73
}
74