Completed
Push — master ( dc4b6d...04cf1c )
by Kacper
04:06
created

RegenerateCommand::review()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 4
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
4
namespace Kadet\Highlighter\bin\Commands\Test;
5
6
7
use Kadet\Highlighter\Formatter\FormatterInterface;
8
use Kadet\Highlighter\KeyLighter;
9
use Kadet\Highlighter\Language\Language;
10
use Kadet\Highlighter\Parser\Tokens;
11
use Kadet\Highlighter\Tests\Helpers\TestFormatter;
12
use Kadet\Highlighter\Utils\StringHelper;
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\Console\Question\ConfirmationQuestion;
19
20
class RegenerateCommand extends Command
21
{
22
    /**
23
     * @var KeyLighter
24
     */
25
    private $_keylighter;
26
    /** @var  \Kadet\Highlighter\Formatter\FormatterInterface */
27
    private $_formatter;
28
29
    private $_input;
30
    private $_output;
31
32
    protected function configure()
33
    {
34
        $this->setName('test:regenerate')
35
            ->addArgument('files', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'tests to regenerate', ['*'])
36
            ->addOption('new', null, InputOption::VALUE_NONE, 'generate only new files')
37
            ->addOption('review', 'r', InputOption::VALUE_OPTIONAL, 'review generated files')
38
            ->setDescription('Regenerates test files')
39
        ;
40
41
        $this->_keylighter = KeyLighter::get();
42
        $this->_formatter  = new TestFormatter();
0 ignored issues
show
Documentation Bug introduced by Kacper Donat
It seems like new \Kadet\Highlighter\T...Helpers\TestFormatter() of type object<Kadet\Highlighter...\Helpers\TestFormatter> is incompatible with the declared type object<Kadet\Highlighter...ter\FormatterInterface> of property $_formatter.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
43
44
        $this->_input  = realpath(__DIR__.'/../../../Tests/Samples');
45
        $this->_output = realpath(__DIR__.'/../../../Tests/Expected/Test');
46
    }
47
48
    protected function execute(InputInterface $input, OutputInterface $output)
49
    {
50
        $iterator = new \RecursiveIteratorIterator(
51
            new \RecursiveDirectoryIterator(
52
                $this->_input,
53
                \RecursiveDirectoryIterator::SKIP_DOTS | \RecursiveDirectoryIterator::UNIX_PATHS
54
            ), \RecursiveIteratorIterator::LEAVES_ONLY
55
        );
56
57
        $reviewer = $this->_keylighter->getFormatter($input->getOption('review') ?: 'cli');
58
59
        /** @var \SplFileInfo $file */
60
        foreach ($iterator as $file) {
61
            $pathname = substr($file->getPathname(), strlen($this->_input) + 1);
62
            if(!$this->regenerate($input, $pathname)) {
63
                continue;
64
            }
65
66
            $output->writeln("Generating $pathname...", OutputInterface::VERBOSITY_QUIET);
67
68
            $language = Language::byFilename($pathname);
69
            $tokens   = $language->parse(file_get_contents($file->getPathname()));
70
71
            if ($this->review($input, $output, $tokens, $reviewer)) {
72
                $result = StringHelper::normalize($this->_formatter->format($tokens));
73
74
                if(!file_exists($this->_output.'/'.dirname($pathname))) {
75
                    mkdir($this->_output.'/'.dirname($pathname), true);
76
                }
77
78
                file_put_contents("{$this->_output}/$pathname.tkn", $result);
79
            }
80
        }
81
    }
82
83
    private function review(InputInterface $input, OutputInterface $output, Tokens $tokens, FormatterInterface $reviewer)
84
    {
85
        if (!$this->shouldReview($input)) {
86
            return true;
87
        }
88
89
        $result = $reviewer->format($tokens);
90
        $output->writeln($result);
91
92
        $question = new ConfirmationQuestion('Does it look right?');
93
        return $this->getHelper('question')->ask($input, $output, $question);
0 ignored issues
show
Bug introduced by Kacper Donat
It seems like you code against a concrete implementation and not the interface Symfony\Component\Console\Helper\HelperInterface as the method ask() does only exist in the following implementations of said interface: Symfony\Component\Console\Helper\QuestionHelper, Symfony\Component\Consol...r\SymfonyQuestionHelper.

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...
94
    }
95
96
    private function shouldReview(InputInterface $input)
97
    {
98
        return $input->hasParameterOption('--review')
99
            || $input->hasParameterOption('-r');
100
    }
101
102
    private function regenerate(InputInterface $input, $filename) {
103
        $filename = str_replace(DIRECTORY_SEPARATOR, '/', $filename);
104
        $patterns = $input->getArgument('files');
105
106
        foreach($patterns as $pattern) {
107
            if($input->getOption('new') && file_exists("{$this->_output}/$filename.tkn")) {
108
                continue;
109
            }
110
111
            if(fnmatch($pattern, $filename)) {
112
                return true;
113
            }
114
        }
115
116
        return false;
117
    }
118
}