ListServicesCommand   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 2
cbo 7
dl 0
loc 93
ccs 37
cts 37
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 6 1
A __construct() 0 6 1
A execute() 0 21 3
B addDefinition() 0 23 5
1
<?php
2
3
namespace BrainExe\Core\Console;
4
5
use BrainExe\Core\Annotations\Command as CommandAnnotation;
6
use BrainExe\Core\DependencyInjection\Rebuild;
7
use BrainExe\Core\Traits\EventDispatcherTrait;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Helper\Table;
10
use Symfony\Component\Console\Input\InputArgument;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Symfony\Component\DependencyInjection\ContainerBuilder;
14
15
/**
16
 * @CommandAnnotation
17
 */
18
class ListServicesCommand extends Command
19
{
20
21
    const TYPE_PRIVATE   = 'private';
22
    const TYPE_PROTECTED = 'protected';
23
    const TYPE_PUBLIC    = 'public';
24
25
    use EventDispatcherTrait;
26
27
    /**
28
     * @var Rebuild
29
     */
30
    private $rebuild;
31
32
    /**
33
     * @var ContainerBuilder
34
     */
35
    private $container;
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 4
    protected function configure()
41
    {
42 4
        $this->setName('debug:list:services')
43 4
            ->setDescription('List all services')
44 4
            ->addArgument('visibility', InputArgument::OPTIONAL, 'public, protected or private');
45 4
    }
46
47
    /**
48
     * @param Rebuild $rebuild
49
     */
50 4
    public function __construct(Rebuild $rebuild)
51
    {
52 4
        $this->rebuild = $rebuild;
53
54 4
        parent::__construct();
55 4
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60 3
    protected function execute(InputInterface $input, OutputInterface $output)
61
    {
62 3
        $this->container = $this->rebuild->buildContainer();
63
64 3
        $table = new Table($output);
65 3
        $table->setHeaders(['service-id', 'tags', 'visibility']);
66
67 3
        $ids = $this->container->getServiceIds();
68
69 3
        sort($ids);
70
71 3
        $visibility = $input->getArgument('visibility');
72
73 3
        foreach ($ids as $id) {
74 3
            if ($this->container->hasDefinition($id)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\DependencyInjection\Container as the method hasDefinition() does only exist in the following sub-classes of Symfony\Component\DependencyInjection\Container: Container14\ProjectServiceContainer, Symfony\Component\Depend...ection\ContainerBuilder. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
75 3
                $this->addDefinition($id, $table, $visibility);
76
            }
77
        }
78
79 3
        $table->render();
80 3
    }
81
82
    /**
83
     * @param string $id
84
     * @param Table $table
85
     * @param bool $restrictedVisibility
86
     */
87 3
    private function addDefinition($id, Table $table, $restrictedVisibility)
88
    {
89 3
        $definition = $this->container->getDefinition($id);
90
91 3
        if (!$definition->isPublic()) {
92 3
            $currentVisibility = self::TYPE_PRIVATE;
93 3
            $color = 'error';
94 3
        } elseif (strpos($id, '__') === 0) {
95 3
            $currentVisibility = self::TYPE_PROTECTED;
96 3
            $color = 'comment';
97
        } else {
98 3
            $currentVisibility = self::TYPE_PUBLIC;
99 3
            $color = 'info';
100
        }
101
102 3
        if (!$restrictedVisibility || $restrictedVisibility === $currentVisibility) {
103 3
            $table->addRow([
104 3
                $id,
105 3
                implode(', ', array_keys($definition->getTags())),
106 3
                "<$color>$currentVisibility</$color>"
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $color instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $currentVisibility instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
107
            ]);
108
        }
109 3
    }
110
}
111