Completed
Push — master ( f58be8...855521 )
by Tilita
03:07
created

BaseConsumerCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 48.28%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 6
dl 0
loc 84
ccs 14
cts 29
cp 0.4828
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getConsumer() 0 4 1
A handle() 0 27 4
A injectCliLogger() 0 15 2
1
<?php
2
namespace NeedleProject\LaravelRabbitMq\Command;
3
4
use Illuminate\Console\Command;
5
use Monolog\Handler\StreamHandler;
6
use Monolog\Logger;
7
use NeedleProject\LaravelRabbitMq\ConsumerInterface;
8
use Psr\Log\LoggerAwareInterface;
9
use Psr\Log\LoggerInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
/**
13
 * Class BaseConsumerCommand
14
 *
15
 * @package NeedleProject\LaravelRabbitMq\Command
16
 * @author  Adrian Tilita <[email protected]>
17
 */
18
class BaseConsumerCommand extends Command
19
{
20
    /**
21
     * The name and signature of the console command.
22
     *
23
     * @var string
24
     */
25
    protected $signature = 'rabbitmq:consume {consumer} {--time=60} {--messages=100} {--memory=64}';
26
27
    /**
28
     * The console command description.
29
     *
30
     * @var string
31
     */
32
    protected $description = 'Start consuming messages';
33
34
    /**
35
     * @param string $consumerAliasName
36
     * @return ConsumerInterface
37
     */
38
    protected function getConsumer(string $consumerAliasName): ConsumerInterface
39
    {
40
        return app()->makeWith(ConsumerInterface::class, [$consumerAliasName]);
41
    }
42
43
    /**
44
     * Execute the console command.
45
     * @return int
46
     */
47 2
    public function handle()
48
    {
49 2
        $messageCount = $this->input->getOption('messages');
50 2
        $waitTime = $this->input->getOption('time');
51 2
        $memoryLimit = $this->input->getOption('memory');
52 2
        $isVerbose = in_array(
0 ignored issues
show
Unused Code introduced by
$isVerbose is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
53 2
            $this->output->getVerbosity(),
54 2
            [OutputInterface::VERBOSITY_VERBOSE, OutputInterface::VERBOSITY_VERY_VERBOSE]
55
        );
56
57
        /** @var ConsumerInterface $consumer */
58 2
        $consumer = $this->getConsumer($this->input->getArgument('consumer'));
0 ignored issues
show
Bug introduced by
It seems like $this->input->getArgument('consumer') targeting Symfony\Component\Consol...nterface::getArgument() can also be of type array<integer,string> or null; however, NeedleProject\LaravelRab...rCommand::getConsumer() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
59 2
        if ($consumer instanceof LoggerAwareInterface) {
60
            try {
61
                $this->injectCliLogger($consumer);
62
            } catch (\Throwable $e) {
63
                // Do nothing, we cannot inject a STDOUT logger
64
            }
65
        }
66
        try {
67 2
            return $consumer->startConsuming($messageCount, $waitTime, $memoryLimit);
68 1
        } catch (\Throwable $e) {
69 1
            $consumer->stopConsuming();
70 1
            $this->output->error($e->getMessage());
71 1
            return -1;
72
        }
73
    }
74
75
    /**
76
     * Inject a stdout logger
77
     *
78
     * This is a "hackish" method because we handle a interface to deduce an implementation
79
     * that exposes certain methods.
80
     *
81
     * @todo - Find a better way to inject a CLI logger when running in verbose mode
82
     *
83
     * @param LoggerAwareInterface $consumerWithLogger
84
     * @throws \Exception
85
     */
86
    protected function injectCliLogger(LoggerAwareInterface $consumerWithLogger)
87
    {
88
        $stdHandler = new StreamHandler('php://stdout');
89
        $class = new \ReflectionClass(get_class($consumerWithLogger));
90
        $property = $class->getProperty('logger');
91
        $property->setAccessible(true);
92
        /** @var LoggerInterface $logger */
93
        $logger = $property->getValue($consumerWithLogger);
94
        if ($logger instanceof \Illuminate\Log\LogManager) {
0 ignored issues
show
Bug introduced by
The class Illuminate\Log\LogManager does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
95
            /** @var Logger $logger */
96
            $logger = $logger->channel()->getLogger();
0 ignored issues
show
Bug introduced by
The method channel() does not seem to exist on object<Monolog\Logger>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
97
            $logger->pushHandler($stdHandler);
98
        }
99
        $property->setAccessible(false);
100
    }
101
}
102