Passed
Pull Request — master (#96)
by Rustam
10:42
created

ListCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 27
c 1
b 0
f 0
dl 0
loc 48
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 5 1
A execute() 0 29 5
A __construct() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Command\Route;
6
7
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Helper\Table;
10
use Symfony\Component\Console\Helper\TableSeparator;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Symfony\Component\Console\Style\SymfonyStyle;
14
use Yiisoft\Router\Route;
15
use Yiisoft\Router\UrlMatcherInterface;
16
use Yiisoft\Yii\Console\ExitCode;
17
18
class ListCommand extends Command
19
{
20
    private UrlMatcherInterface $urlMatcher;
21
22
    protected static $defaultName = 'route/list';
23
24
    public function __construct(UrlMatcherInterface $urlMatcher)
25
    {
26
        $this->urlMatcher = $urlMatcher;
27
        parent::__construct();
28
    }
29
30
    protected function configure()
31
    {
32
        $this
33
            ->setDescription('List all registered routes')
34
            ->setHelp('This command displays a list of registered routes.');
35
    }
36
37
    protected function execute(InputInterface $input, OutputInterface $output)
38
    {
39
        $table = new Table($output);
40
        $io = new SymfonyStyle($input, $output);
41
        /** @var Route[] $routes */
42
        $routes = $this->urlMatcher->getRouteCollection()->getRoutes();
43
        $table->setHeaders(['Host', 'Methods', 'Name', 'Pattern', 'Defaults']);
44
        foreach ($routes as $key => $route) {
45
            $table->addRow(
46
                [
47
                    $route->getHost(),
48
                    implode(',', $route->getMethods()),
49
                    $route->getName(),
50
                    $route->getPattern(),
51
                    implode(',', $route->getDefaults())
52
                ]
53
            );
54
            if (next($routes) !== false) {
55
                $table->addRow(new TableSeparator());
56
            }
57
        }
58
59
        try {
60
            $table->render();
61
        } catch (\Throwable $exception) {
62
            $io->error($exception->getMessage());
63
            return $exception->getCode() ?: ExitCode::UNSPECIFIED_ERROR;
64
        }
65
        return ExitCode::OK;
66
    }
67
}
68