ExecuteTestsCommand::setEvent()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
/**
3
 * ShouldPHP
4
 *
5
 * @author  Gabriel Jacinto <[email protected]>
6
 * @status  dev
7
 * @link    https://github.com/GabrielJMJ/ShouldPHP
8
 * @license MIT
9
 */
10
 
11
namespace Gabrieljmj\Should\Console\Command;
12
13
use Symfony\Component\Console\Command\Command;
14
use Symfony\Component\Console\Input\InputArgument;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Output\OutputInterface;
18
use Symfony\Component\EventDispatcher\Event;
19
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
20
use Psr\Log\LoggerInterface;
21
use Gabrieljmj\Should\Ambient\AmbientInterface;
22
use Gabrieljmj\Should\Template\TemplateInterface;
23
use Gabrieljmj\Should\Report\Report;
24
use Gabrieljmj\Should\Event\ExecutionEventInterface;
25
use Gabrieljmj\Should\Logger\LoggerAdapterInterface;
26
use Gabrieljmj\Should\Runner\RunnerInterface;
27
28
class ExecuteTestsCommand extends Command
29
{
30
    /**
31
     * @var \Gabrieljmj\Should\Logger\LoggerAdapterInterface
32
     */
33
    private $logger;
34
35
    /**
36
     * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
37
     */
38
    private $eventDispatcher;
39
40
    /**
41
     * @var \Symfony\Component\EventDispatcher\Event
42
     */
43
    private $event;
44
45
    /**
46
     * @var array
47
     */
48
    private $runners = [];
49
    
50
    /**
51
     * @var \Gabrieljmj\Should\Template\TemplateInterface
52
     */
53
    private $template;
54
55
    /**
56
     * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $eventDispatcher
57
     */
58
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
59
    {
60
        $this->eventDispatcher = $eventDispatcher;
61
    }
62
    
63
    /**
64
     * @param \Gabrieljmj\Should\Template\TemplateInterface $template
65
     */
66
    public function setTemplate(TemplateInterface $template)
67
    {
68
        $this->template = $template;
69
    }
70
71
    /**
72
     * @param \Gabrieljmj\Should\Event\ExecutionEventInterface $event
73
     */
74
    public function setEvent(ExecutionEventInterface $event)
75
    {
76
        if (!$event instanceof Event) {
77
            throw new \InvalidArgumentException('Argument passed shoud be instance of \Symfony\Component\EventDispatcher\Event');
78
        }
79
80
        $this->event = $event;
81
    }
82
83
    public function pushRunners($runners)
84
    {
85
        if (is_array($runners)) {
86
            foreach ($runners as $runner) {
87
                if (!$runner instanceof RunnerInterface) {
88
                    throw new \InvalidArgumentException('A runner passed is not instance of RunnerInterface');
89
                }
90
91
                if (!in_array($runner, $this->runners)) {
92
                    $this->runners[] = $runner;
93
                }
94
            }
95
96
            return;
97
        }
98
99
        if (!$runners instanceof RunnerInterface) {
100
            throw new \InvalidArgumentException('A runner passed is not instance of RunnerInterface');
101
        }
102
103
        if (!in_array($runners, $this->runners)) {
104
            $this->runners[] = $runner;
0 ignored issues
show
Bug introduced by
The variable $runner seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
105
        }
106
    }
107
108
    /**
109
     * @param \Gabrieljmj\Should\Logger\LoggerAdapterInterface $logger
110
     */
111
    public function setLogger(LoggerAdapterInterface $logger)
112
    {
113
        if (!$logger instanceof LoggerInterface) {
114
            throw new \Exception('Logger should impements Psr\Log\LoggerInterface');
115
        }
116
117
        $this->logger = $logger;
118
    }
119
120
    protected function configure()
121
    {
122
        $this->setName('execute')
123
             ->setDescription('Executes tests')
124
             ->addArgument(
125
                    'file',
126
                    InputArgument::REQUIRED,
127
                    'Indicate the file or the path that contains the tests ambients'
128
             )
129
             ->addOption(
130
                    'save',
131
                    's',
132
                    InputOption::VALUE_REQUIRED,
133
                    'Do you want to save the report?'
134
             )
135
             ->addOption(
136
                    'colors',
137
                    'c',
138
                    InputOption::VALUE_NONE,
139
                    'Show your report with colors?'
140
             );
141
    }
142
143
    /**
144
     * @param \Symfony\Component\Console\Input\InputInterface   $input
145
     * @param \Symfony\Component\Console\Output\OutputInterface $output
146
     */
147
    protected function execute(InputInterface $input, OutputInterface $output)
148
    {
149
        $file = $input->getArgument('file');
150
        $input->hasArgument('test_name') ? $testName = $input->getArgument('test_name') : null;
151
        $reports = [];
152
153 View Code Duplication
        foreach ($this->runners as $runner) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
            if ($runner->canHandle($file)) {
155
                $runner->run($file);
156
                $reports[] = $runner->getReport();
157
            }
158
        }
159
160
        if ($input->getOption('colors')) {
161
            $this->template->colors();
162
        }
163
        
164
        $this->event->setOutput($output);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\EventDispatcher\Event as the method setOutput() does only exist in the following sub-classes of Symfony\Component\EventDispatcher\Event: Gabrieljmj\Should\Event\ExecutionEvent. 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...
165
        $this->event->setTemplate($this->template);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\EventDispatcher\Event as the method setTemplate() does only exist in the following sub-classes of Symfony\Component\EventDispatcher\Event: Gabrieljmj\Should\Event\ExecutionEvent. 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...
166
        $this->event->setReport($report = $this->combineReports($reports));
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\EventDispatcher\Event as the method setReport() does only exist in the following sub-classes of Symfony\Component\EventDispatcher\Event: Gabrieljmj\Should\Event\ExecutionEvent. 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...
167
168
        if ($local = $input->getOption('save')) {
169
            $this->logger->setFile($local);
170
            $this->logger->info($report->serialize());
171
        }
172
173
        $this->eventDispatcher->dispatch('should.execute', $this->event);
174
    }
175
176
    private function combineReports($reports)
177
    {
178
        $finalReport = new Report('all_tests');
179
180
        foreach ($reports as $report) {
181
            $assertList = $report->getAssertList();
182
183
            foreach ($assertList as $testType => $value) {
184 View Code Duplication
                if (isset($assertList[$testType]['fail'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
                    foreach ($assertList[$testType]['fail'] as $element => $fails) {
186
                        foreach ($fails as $fail) {
187
                            $finalReport->addAssert($fail);
188
                        }
189
                    }
190
                }
191
192 View Code Duplication
                if (isset($assertList[$testType]['success'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
193
                    foreach ($assertList[$testType]['success'] as $element => $successes) {
194
                        foreach ($successes as $success) {
195
                            $finalReport->addAssert($success);
196
                        }
197
                    }
198
                }
199
            }
200
        }
201
202
        return $finalReport;
203
    }
204
}