ConsumerHandlerCommand::getBackend()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.9617
c 0
b 0
f 0
cc 6
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\NotificationBundle\Command;
15
16
use Sonata\NotificationBundle\Backend\BackendInterface;
17
use Sonata\NotificationBundle\Backend\QueueDispatcherInterface;
18
use Sonata\NotificationBundle\Consumer\ConsumerInterface;
19
use Sonata\NotificationBundle\Event\IterateEvent;
20
use Sonata\NotificationBundle\Exception\HandlingException;
21
use Sonata\NotificationBundle\Model\MessageInterface;
22
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
23
use Symfony\Component\Console\Input\InputInterface;
24
use Symfony\Component\Console\Input\InputOption;
25
use Symfony\Component\Console\Output\OutputInterface;
26
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
27
28
class ConsumerHandlerCommand extends ContainerAwareCommand
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...d\ContainerAwareCommand has been deprecated with message: since Symfony 4.2, use {@see Command} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
29
{
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function configure(): void
34
    {
35
        $this->setName('sonata:notification:start');
36
        $this->setDescription('Listen for incoming messages');
37
        $this->addOption('iteration', 'i', InputOption::VALUE_OPTIONAL, 'Only run n iterations before exiting', false);
38
        $this->addOption('type', null, InputOption::VALUE_OPTIONAL, 'Use a specific backed based on a message type, "all" with doctrine backend will handle all notifications no matter their type', null);
39
        $this->addOption('show-details', 'd', InputOption::VALUE_OPTIONAL, 'Show consumers return details', true);
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function execute(InputInterface $input, OutputInterface $output): void
46
    {
47
        $startDate = new \DateTime();
48
49
        $output->writeln(sprintf('[%s] <info>Checking listeners</info>', $startDate->format('r')));
50
        foreach ($this->getNotificationDispatcher()->getListeners() as $type => $listeners) {
51
            $output->writeln(sprintf(' - %s', $type));
52
            foreach ($listeners as $listener) {
53
                if (!$listener[0] instanceof ConsumerInterface) {
54
                    throw new \RuntimeException(sprintf(
55
                        'The registered service does not implement the ConsumerInterface (class=%s',
56
                        \get_class($listener[0])
57
                    ));
58
                }
59
60
                $output->writeln(sprintf('   > %s', \get_class($listener[0])));
61
            }
62
        }
63
64
        $type = $input->getOption('type');
65
        $showDetails = $input->getOption('show-details');
66
67
        $output->write(sprintf('[%s] <info>Retrieving backend</info> ...', $startDate->format('r')));
68
        $backend = $this->getBackend($type);
69
70
        $output->writeln('');
71
        $output->write(sprintf('[%s] <info>Initialize backend</info> ...', $startDate->format('r')));
72
73
        // initialize the backend
74
        $backend->initialize();
75
76
        $output->writeln(' done!');
77
78
        if (null === $type) {
79
            $output->writeln(sprintf(
80
                '[%s] <info>Starting the backend handler</info> - %s',
81
                $startDate->format('r'),
82
                \get_class($backend)
83
            ));
84
        } else {
85
            $output->writeln(sprintf(
86
                '[%s] <info>Starting the backend handler</info> - %s (type: %s)',
87
                $startDate->format('r'),
88
                \get_class($backend),
89
                $type
90
            ));
91
        }
92
93
        $startMemoryUsage = memory_get_usage(true);
94
        $i = 0;
95
        $iterator = $backend->getIterator();
96
        foreach ($iterator as $message) {
97
            ++$i;
98
99
            if (!$message instanceof MessageInterface) {
100
                throw new \RuntimeException('The iterator must return a MessageInterface instance');
101
            }
102
103
            if (!$message->getType()) {
104
                $output->write('<error>Skipping : no type defined </error>');
105
106
                continue;
107
            }
108
109
            $date = new \DateTime();
110
            $output->write(sprintf('[%s] <info>%s</info> #%s: ', $date->format('r'), $message->getType(), $i));
111
            $memoryUsage = memory_get_usage(true);
112
113
            try {
114
                $start = microtime(true);
115
                $returnInfos = $backend->handle($message, $this->getNotificationDispatcher());
0 ignored issues
show
Bug introduced by
It seems like $this->getNotificationDispatcher() can be null; however, handle() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
116
117
                $currentMemory = memory_get_usage(true);
118
119
                $output->writeln(sprintf(
120
                    '<comment>OK! </comment> - %0.04fs, %ss, %s, %s - %s = %s, %0.02f%%',
121
                    microtime(true) - $start,
122
                    $date->format('U') - $message->getCreatedAt()->format('U'),
123
                    $this->formatMemory($currentMemory - $memoryUsage),
124
                    $this->formatMemory($currentMemory),
125
                    $this->formatMemory($startMemoryUsage),
126
                    $this->formatMemory($currentMemory - $startMemoryUsage),
127
                    ($currentMemory - $startMemoryUsage) / $startMemoryUsage * 100
128
                ));
129
130
                if ($showDetails && null !== $returnInfos) {
131
                    $output->writeln($returnInfos->getReturnMessage());
132
                }
133
            } catch (HandlingException $e) {
134
                $output->writeln(sprintf('<error>KO! - %s</error>', $e->getPrevious()->getMessage()));
135
            } catch (\Exception $e) {
136
                $output->writeln(sprintf('<error>KO! - %s</error>', $e->getMessage()));
137
            }
138
139
            $this->getEventDispatcher()->dispatch(
140
                new IterateEvent($iterator, $backend, $message),
141
                IterateEvent::EVENT_NAME
142
            );
143
144
            if ($input->getOption('iteration') && $i >= (int) $input->getOption('iteration')) {
145
                $output->writeln('End of iteration cycle');
146
147
                return;
148
            }
149
        }
150
    }
151
152
    /**
153
     * @param string $type
154
     * @param string $backend
155
     *
156
     * @throws \RuntimeException
157
     */
158
    protected function throwTypeNotFoundException($type, $backend): void
159
    {
160
        throw new \RuntimeException(
161
            "The requested backend for the type '".$type." 'does not exist. \nMake sure the backend '".
162
            \get_class($backend)."' \nsupports multiple queues and the routing_key is defined. (Currently rabbitmq only)"
163
        );
164
    }
165
166
    /**
167
     * @param $memory
168
     *
169
     * @return string
170
     */
171
    private function formatMemory($memory)
172
    {
173
        if ($memory < 1024) {
174
            return $memory.'b';
175
        } elseif ($memory < 1048576) {
176
            return round($memory / 1024, 2).'Kb';
177
        }
178
179
        return round($memory / 1048576, 2).'Mb';
180
    }
181
182
    /**
183
     * @param string $type
184
     *
185
     * @return BackendInterface
186
     */
187
    private function getBackend($type = null)
188
    {
189
        $backend = $this->getContainer()->get('sonata.notification.backend');
190
191
        if ($type && !\array_key_exists($type, $this->getNotificationDispatcher()->getListeners())) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
192
            throw new \RuntimeException(sprintf('The type `%s` does not exist, available types: %s', $type, implode(', ', array_keys($this->getNotificationDispatcher()->getListeners()))));
193
        }
194
195
        if (null !== $type && !$backend instanceof QueueDispatcherInterface) {
196
            throw new \RuntimeException(sprintf(
197
                'Unable to use the provided type %s with a non QueueDispatcherInterface backend',
198
                $type
199
            ));
200
        }
201
202
        if ($backend instanceof QueueDispatcherInterface) {
203
            return $backend->getBackend($type);
204
        }
205
206
        return $backend;
207
    }
208
209
    /**
210
     * @return EventDispatcherInterface
211
     */
212
    private function getNotificationDispatcher()
213
    {
214
        return $this->getContainer()->get('sonata.notification.dispatcher');
215
    }
216
217
    /**
218
     * @return EventDispatcherInterface
219
     */
220
    private function getEventDispatcher()
221
    {
222
        return $this->getContainer()->get('event_dispatcher');
223
    }
224
}
225