Completed
Branch master (3adcdb)
by Raffael
08:09 queued 04:17
created

Cli::reduceLogLevel()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 8.8571
c 0
b 0
f 0
cc 6
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 GetOpt\GetOpt;
16
use Monolog\Handler\FilterHandler;
17
use Monolog\Handler\StreamHandler;
18
use Monolog\Logger;
19
use Psr\Container\ContainerInterface;
20
use Psr\Log\LoggerInterface;
21
22
class Cli extends AbstractBootstrap
23
{
24
    /**
25
     * Getopt.
26
     *
27
     * @var GetOpt
28
     */
29
    protected $getopt;
30
31
    /**
32
     * Container.
33
     *
34
     * @var ContainerInterface
35
     */
36
    protected $container;
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function __construct(LoggerInterface $logger, GetOpt $getopt, ContainerInterface $container)
42
    {
43
        $this->logger = $logger;
44
        $this->getopt = $getopt;
45
        $this->container = $container;
46
        $this->reduceLogLevel();
47
        $this->setExceptionHandler();
48
    }
49
50
    /**
51
     * Process.
52
     *
53
     * @return Cli
54
     */
55
    public function process()
56
    {
57
        $this->getopt->addOption(['v', 'verbose', GetOpt::NO_ARGUMENT, 'Verbose']);
58
        $this->getopt->process();
59
        $this->configureLogger($this->getopt->getOption('verbose'));
60
        $this->getopt->routeCommand($this->container);
0 ignored issues
show
Documentation introduced by
$this->container is of type object<Psr\Container\ContainerInterface>, but the function expects a object<GetOpt\ContainerInterface>|null.

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...
61
62
        return $this;
63
    }
64
65
    /**
66
     * Remove logger.
67
     *
68
     * @return Cli
69
     */
70
    protected function reduceLogLevel(): self
71
    {
72
        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...
73
            if ($handler instanceof StreamHandler) {
74
                if ($handler->getUrl() === 'php://stderr' || $handler->getUrl() === 'php://stdout') {
75
                    $handler->setLevel(600);
76
                }
77
            } elseif ($handler instanceof FilterHandler) {
78
                $handler->setAcceptedLevels(1000, 1000);
79
            }
80
        }
81
82
        return $this;
83
    }
84
85
    /**
86
     * Configure cli logger.
87
     *
88
     * @return Cli
89
     */
90
    protected function configureLogger(?int $level = null): self
91
    {
92
        if (null === $level) {
93
            $level = 400;
94
        } else {
95
            $level = (4 - $level) * 100;
96
        }
97
98
        $formatter = new ColoredLineFormatter();
99
        $handler = new StreamHandler('php://stderr', Logger::EMERGENCY);
100
        $handler->setFormatter($formatter);
101
        $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...
102
103
        $handler = new StreamHandler('php://stdout', $level);
104
        $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...
105
        $handler->setFormatter($formatter);
106
107
        $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...
108
109
        return $this;
110
    }
111
112
    /**
113
     * Set exception handler.
114
     *
115
     * @return Cli
116
     */
117
    protected function setExceptionHandler(): self
118
    {
119
        set_exception_handler(function ($e) {
120
            $this->logger->emergency('uncaught exception: '.$e->getMessage(), [
121
                'category' => get_class($this),
122
                'exception' => $e,
123
            ]);
124
        });
125
126
        return $this;
127
    }
128
}
129