Passed
Push — main ( 63d141...3e84d7 )
by Nils
03:05
created

PatternCommand::doExecute()   B

Complexity

Conditions 7
Paths 40

Size

Total Lines 41
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 21
c 2
b 0
f 0
nc 40
nop 2
dl 0
loc 41
rs 8.6506
1
<?php
2
3
namespace Startwind\Forrest\CliCommand\Search;
4
5
use Startwind\Forrest\Output\OutputHelper;
6
use Symfony\Component\Console\Command\Command;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Input\InputOption;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class PatternCommand extends SearchCommand
13
{
14
    const PERFECT_SCORE = 10;
15
16
    public const COMMAND_NAME = 'search:pattern';
17
18
    protected static $defaultName = self::COMMAND_NAME;
19
    protected static $defaultDescription = 'Search for commands that fit the given pattern.';
20
21
    protected function configure(): void
22
    {
23
        parent::configure();
24
25
        $this->addArgument('pattern', InputArgument::IS_ARRAY, 'The pattern you want to search for.');
26
        $this->addOption('force', null, InputOption::VALUE_NONE, 'Run the command without asking for permission.');
27
        $this->addOption('score', 's', InputOption::VALUE_OPTIONAL, 'The minimal search score.', 7);
28
29
        $this->setAliases(['pattern']);
30
    }
31
32
    protected function doExecute(InputInterface $input, OutputInterface $output): int
33
    {
34
        OutputHelper::renderHeader($output);
35
36
        $minScore = $input->getOption('score');
37
38
        $this->enrichRepositories();
39
40
        $pattern = $input->getArgument('pattern');
41
42
        $this->renderInfoBox('This is a list of commands that match the given pattern. Sorted by relevance.');
43
44
        $commands = $this->getRepositoryCollection()->searchByPattern($pattern);
45
46
        $filteredCommands = [];
47
        $perfectCommands = [];
48
49
        foreach ($commands as $key => $command) {
50
            if ($command->getScore() > $minScore) {
51
                $filteredCommands[$key] = $command;
52
            }
53
54
            if ($command->getScore() > self::PERFECT_SCORE) {
55
                $perfectCommands[$key] = $command;
56
            }
57
        }
58
59
        if (count($filteredCommands) == 0) {
60
            $filteredCommands = $commands;
61
        }
62
63
        if (count($perfectCommands) > 0) {
64
            $filteredCommands = $perfectCommands;
65
        }
66
67
        if (empty($filteredCommands)) {
68
            $this->renderErrorBox('No commands found that match the given pattern.');
69
            return Command::FAILURE;
70
        }
71
72
        return $this->runFromCommands($filteredCommands);
73
    }
74
}
75