Passed
Push — master ( 47e248...a43368 )
by Raffael
09:50
created

Cli::reduceLogLevel()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 13
cp 0
rs 8.8571
c 0
b 0
f 0
cc 6
crap 42
eloc 8
nc 5
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2018 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon\Bootstrap;
13
14
use Bramus\Monolog\Formatter\ColoredLineFormatter;
15
use Closure;
16
use GetOpt\GetOpt;
17
use Monolog\Handler\FilterHandler;
18
use Monolog\Handler\StreamHandler;
19
use Monolog\Logger;
20
use Psr\Container\ContainerInterface;
21
use Psr\Log\LoggerInterface;
22
23
class Cli extends AbstractBootstrap
24
{
25
    /**
26
     * Getopt.
27
     *
28
     * @var GetOpt
29
     */
30
    protected $getopt;
31
32
    /**
33
     * Container.
34
     *
35
     * @var ContainerInterface
36
     */
37
    protected $container;
38
39
    /**
40
     * Cli.
41
     *
42
     * @param LoggerInterface    $logger
43
     * @param Getopt             $getopt
44
     * @param ContainerInterface $container
45
     */
46
    public function __construct(LoggerInterface $logger, GetOpt $getopt, ContainerInterface $container)
47
    {
48
        $this->logger = $logger;
49
        $this->getopt = $getopt;
50
        $this->container = $container;
51
        $this->reduceLogLevel();
52
        $this->setExceptionHandler();
53
    }
54
55
    /**
56
     * Process.
57
     *
58
     * @return Cli
59
     */
60
    public function process()
61
    {
62
        $this->getopt->addOption(['v', 'verbose', GetOpt::NO_ARGUMENT, 'Verbose']);
63
        $this->getopt->addOption(['h', 'help', GetOpt::NO_ARGUMENT, 'Help']);
64
65
        $this->getopt->process();
66
        if ($this->getopt->getOption('help')) {
67
            echo $this->getopt->getHelpText();
68
69
            return $this;
70
        }
71
72
        $this->configureLogger($this->getopt->getOption('verbose'));
73
        $this->routeCommand();
74
75
        return $this;
76
    }
77
78
    /**
79
     * Route command.
80
     */
81
    protected function routeCommand()
82
    {
83
        $cmd = $this->getopt->getCommand();
84
        if ($cmd === null) {
85
            echo $this->getopt->getHelpText();
86
87
            return null;
88
        }
89
90
        $handler = $cmd->getHandler();
91
92
        if (is_string($handler)) {
93
            $handler();
94
        } elseif ($handler instanceof Closure) {
95
            $handler->call();
96
        } elseif (is_array($handler) && count($handler) === 2 && is_string($handler[0])) {
97
            $class = $this->container->get($handler[0]);
98
            $class->{$handler[1]}();
99
        } elseif (is_callable($handler)) {
100
            call_user_func_array($handler, []);
101
        }
102
103
        return null;
104
    }
105
106
    /**
107
     * Remove logger.
108
     *
109
     * @return Cli
110
     */
111
    protected function reduceLogLevel(): self
112
    {
113
        foreach ($this->logger->getHandlers() as $handler) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method getHandlers() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
114
            if ($handler instanceof StreamHandler) {
115
                if ($handler->getUrl() === 'php://stderr' || $handler->getUrl() === 'php://stdout') {
116
                    $handler->setLevel(600);
117
                }
118
            } elseif ($handler instanceof FilterHandler) {
119
                $handler->setAcceptedLevels(1000, 1000);
120
            }
121
        }
122
123
        return $this;
124
    }
125
126
    /**
127
     * Configure cli logger.
128
     *
129
     * @return Cli
130
     */
131
    protected function configureLogger(?int $level = null): self
132
    {
133
        if (null === $level) {
134
            $level = 400;
135
        } else {
136
            $level = (4 - $level) * 100;
137
        }
138
139
        $formatter = new ColoredLineFormatter();
140
        $handler = new StreamHandler('php://stderr', Logger::EMERGENCY);
141
        $handler->setFormatter($formatter);
142
        $this->logger->pushHandler($handler);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method pushHandler() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
143
144
        $handler = new StreamHandler('php://stdout', $level);
145
        $filter = new FilterHandler($handler, $level, Logger::ERROR);
0 ignored issues
show
Documentation introduced by
$handler is of type object<Monolog\Handler\StreamHandler>, but the function expects a callable.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
146
        $handler->setFormatter($formatter);
147
148
        $this->logger->pushHandler($filter);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Log\LoggerInterface as the method pushHandler() does only exist in the following implementations of said interface: Monolog\Logger.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
149
150
        return $this;
151
    }
152
153
    /**
154
     * Set exception handler.
155
     *
156
     * @return Cli
157
     */
158
    protected function setExceptionHandler(): self
159
    {
160
        set_exception_handler(function ($e) {
161
            $this->logger->emergency('uncaught exception: '.$e->getMessage(), [
162
                'category' => get_class($this),
163
                'exception' => $e,
164
            ]);
165
        });
166
167
        return $this;
168
    }
169
}
170