Completed
Pull Request — master (#39)
by guillaume
03:03
created

ProcessEventCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 13
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 5
crap 2
1
<?php
2
3
namespace Itkg\DelayEventBundle\Command;
4
5
use Itkg\DelayEventBundle\Handler\LockHandlerInterface;
6
use Itkg\DelayEventBundle\Model\Event;
7
use Itkg\DelayEventBundle\Processor\EventProcessor;
8
use Itkg\DelayEventBundle\Repository\EventRepository;
9
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
14
/**
15
 * Class ProcessEventCommand
16
 */
17
class ProcessEventCommand extends ContainerAwareCommand
18
{
19
    /**
20
     * @var EventRepository
21
     */
22
    private $eventRepository;
23
24
    /**
25
     * @var EventProcessor
26
     */
27
    private $eventProcessor;
28
29
    /**
30
     * @var LockHandlerInterface
31
     */
32
    private $lockHandler;
33
34
    /**
35
     * @var array
36
     */
37
    private $channels;
38
39
    /**
40
     * ProcessEventCommand constructor.
41
     *
42
     * @param EventRepository      $eventRepository
43
     * @param EventProcessor       $eventProcessor
44
     * @param LockHandlerInterface $lockHandler
45
     * @param array                $channels
46
     * @param null|string          $name
47
     */
48
    public function __construct(
49
        EventRepository $eventRepository,
50
        EventProcessor $eventProcessor,
51
        LockHandlerInterface $lockHandler,
52
        array $channels = [],
53
        $name = null
54
    ) {
55
        $this->eventRepository = $eventRepository;
56
        $this->eventProcessor = $eventProcessor;
57
        $this->lockHandler = $lockHandler;
58
        $this->channels = $channels;
59
60
        parent::__construct($name);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 View Code Duplication
    protected function configure()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
    {
68
        $this
69
            ->setName('itkg_delay_event:process')
70
            ->setDescription('Process async events')
71
            ->addOption(
72
                'channel',
73
                'c',
74
                InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED,
75
                'Specify the channels to process (default: [\'default\'])',
76
                ['default']
77
            );
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    protected function execute(InputInterface $input, OutputInterface $output)
84
    {
85
        $channels = $input->getOption('channel');
86
87
        foreach ($channels as $channel) {
88
            if (!isset($this->channels[$channel])) {
89
                $output->writeln(
90
                    sprintf(
91
                        '<error>Channel <info>%s</info> is not configured.</error>',
92
                        $channel
93
                    )
94
                );
95
96
                continue;
97
            }
98
99
            if ($this->lockHandler->isLocked($channel)) {
100
                $output->writeln(
101
                    sprintf(
102
                        'Command is locked by another process for channel <info>%s</info>.',
103
                        $channel
104
                    )
105
                );
106
107
                continue;
108
            }
109
110
            $output->writeln(
111
                sprintf(
112
                    'Process events for channel <info>%s</info>',
113
                    $channel
114
                )
115
            );
116
117
            $this->lockHandler->lock($channel);
118
119
            $processedEventsCount = 0;
120
            $commandStartTime = time();
121
            $event = null;
122
123
            try {
124
                while (!$this->isLimitReached(
125
                    $commandStartTime,
126
                    $processedEventsCount,
127
                    $this->channels[$channel]['duration_limit_per_run'],
128
                    $this->channels[$channel]['events_limit_per_run'])
129
                ) {
130
                    if (!$this->lockHandler->isLocked($channel)) {
131
                        $output->writeln(
132
                            sprintf(
133
                                '<error>Lock for channel <info>%s</info> has been released outside of the process.</error>',
134
                                $channel
135
                            )
136
                        );
137
138
                        break;
139
                    }
140
141
                    $event = $this->eventRepository->findFirstTodoEvent(
142
                        false,
143
                        $this->channels[$channel]['include'],
144
                        $this->channels[$channel]['exclude']
145
                    );
146
147
                    if (!$event instanceof Event) {
148
                        break;
149
                    }
150
151
                    $event->setDelayed(false);
152
                    $this->eventProcessor->process($event);
153
                    $processedEventsCount++;
154
                }
155
            } catch (\Exception $e) {
156
                if ($event instanceof Event) {
157
                    $output->writeln(
158
                        sprintf(
159
                            '<info>[%s]</info> <error> An error occurred while processing event "%s".</error>',
160
                            $channel,
161
                            $event->getOriginalName()
162
                        )
163
                    );
164
                }
165
166
                $output->writeln(sprintf('<info>[%s]</info> <error>%s</error>', $channel, $e->getMessage()));
167
                $output->writeln($e->getTraceAsString());
168
            }
169
170
            $this->lockHandler->release($channel);
171
        }
172
    }
173
174
    /**
175
     * @param int $commandStartTime
176
     * @param int $processedEventsCount
177
     * @param int $maxDurationPerRun
178
     * @param int $maxProcessedEventPerRun
179
     */
180
    private function isLimitReached($commandStartTime, $processedEventsCount, $maxDurationPerRun, $maxProcessedEventPerRun)
181
    {
182
        return (($maxProcessedEventPerRun !== null && $processedEventsCount >= $maxProcessedEventPerRun)
183
            || ($maxDurationPerRun !== null && (time() - $commandStartTime) >= $maxDurationPerRun));
184
    }
185
}
186