Completed
Push — master ( 62d002...c4a196 )
by Bocharsky
04:05 queued 56s
created

DeleteObsoleteCommand::execute()   C

Complexity

Conditions 11
Paths 84

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
dl 0
loc 54
ccs 0
cts 46
cp 0
rs 6.8569
c 0
b 0
f 0
cc 11
nc 84
nop 2
crap 132

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Translation\Bundle\Command;
13
14
use Symfony\Component\Console\Command\Command;
15
use Symfony\Component\Console\Helper\ProgressBar;
16
use Symfony\Component\Console\Input\InputArgument;
17
use Symfony\Component\Console\Input\InputInterface;
18
use Symfony\Component\Console\Input\InputOption;
19
use Symfony\Component\Console\Output\OutputInterface;
20
use Symfony\Component\Console\Question\ConfirmationQuestion;
21
use Translation\Bundle\Catalogue\CatalogueFetcher;
22
use Translation\Bundle\Catalogue\CatalogueManager;
23
use Translation\Bundle\Service\ConfigurationManager;
24
use Translation\Bundle\Service\StorageManager;
25
26
/**
27
 * @author Tobias Nyholm <[email protected]>
28
 */
29
class DeleteObsoleteCommand extends Command
30
{
31
    use BundleTrait;
32
    use StorageTrait;
33
34
    protected static $defaultName = 'translation:delete-obsolete';
35
36
    /**
37
     * @var ConfigurationManager
38
     */
39
    private $configurationManager;
40
41
    /**
42
     * @var CatalogueManager
43
     */
44
    private $catalogueManager;
45
46
    /**
47
     * @var CatalogueFetcher
48
     */
49
    private $catalogueFetcher;
50
51
    /**
52
     * @param StorageManager       $storageManager
53
     * @param ConfigurationManager $configurationManager
54
     * @param CatalogueManager     $catalogueManager
55
     * @param CatalogueFetcher     $catalogueFetcher
56
     */
57
    public function __construct(
58
        StorageManager $storageManager,
59
        ConfigurationManager $configurationManager,
60
        CatalogueManager $catalogueManager,
61
        CatalogueFetcher $catalogueFetcher
62
    ) {
63
        $this->storageManager = $storageManager;
64
        $this->configurationManager = $configurationManager;
65
        $this->catalogueManager = $catalogueManager;
66
        $this->catalogueFetcher = $catalogueFetcher;
67
        parent::__construct();
68
    }
69
70 View Code Duplication
    protected function configure()
71
    {
72
        $this
73
            ->setName(self::$defaultName)
74
            ->setDescription('Delete all translations marked as obsolete.')
75
            ->addArgument('configuration', InputArgument::OPTIONAL, 'The configuration to use', 'default')
76
            ->addArgument('locale', InputArgument::OPTIONAL, 'The locale to use. If omitted, we use all configured locales.', null)
77
            ->addOption('bundle', 'b', InputOption::VALUE_REQUIRED, 'The bundle you want remove translations from.')
78
        ;
79
    }
80
81
    protected function execute(InputInterface $input, OutputInterface $output)
82
    {
83
        $configName = $input->getArgument('configuration');
84
        $locales = [];
85
        if (null !== $inputLocale = $input->getArgument('locale')) {
86
            $locales = [$inputLocale];
87
        }
88
89
        $config = $this->configurationManager->getConfiguration($configName);
0 ignored issues
show
Bug introduced by
It seems like $configName defined by $input->getArgument('configuration') on line 83 can also be of type array<integer,string>; however, Translation\Bundle\Servi...ger::getConfiguration() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
90
        $this->configureBundleDirs($input, $config);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->configurationMana...figuration($configName) on line 89 can be null; however, Translation\Bundle\Comma...::configureBundleDirs() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
91
        $this->catalogueManager->load($this->catalogueFetcher->getCatalogues($config, $locales));
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->configurationMana...figuration($configName) on line 89 can be null; however, Translation\Bundle\Catal...etcher::getCatalogues() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
92
93
        $storage = $this->getStorage($configName);
0 ignored issues
show
Bug introduced by
It seems like $configName defined by $input->getArgument('configuration') on line 83 can also be of type array<integer,string> or null; however, Translation\Bundle\Comma...rageTrait::getStorage() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
94
        $messages = $this->catalogueManager->findMessages(['locale' => $inputLocale, 'isObsolete' => true]);
95
96
        $messageCount = count($messages);
97
        if (0 === $messageCount) {
98
            $output->writeln('No messages are obsolete');
99
100
            return;
101
        }
102
103
        if ($input->isInteractive()) {
104
            $helper = $this->getHelper('question');
105
            $question = new ConfirmationQuestion(sprintf('You are about to remove %d translations. Do you wish to continue? (y/N) ', $messageCount), false);
106
            if (!$helper->ask($input, $output, $question)) {
107
                return;
108
            }
109
        }
110
111
        $progress = null;
112
        if (OutputInterface::VERBOSITY_NORMAL === $output->getVerbosity() && OutputInterface::VERBOSITY_QUIET !== $output->getVerbosity()) {
113
            $progress = new ProgressBar($output, $messageCount);
114
        }
115
        foreach ($messages as $message) {
116
            $storage->delete($message->getLocale(), $message->getDomain(), $message->getKey());
117
            if ($output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL) {
118
                $output->writeln(sprintf(
119
                    'Deleted obsolete message "<info>%s</info>" from domain "<info>%s</info>" and locale "<info>%s</info>"',
120
                    $message->getKey(),
121
                    $message->getDomain(),
122
                    $message->getLocale()
123
                ));
124
            }
125
126
            if ($progress) {
127
                $progress->advance();
128
            }
129
        }
130
131
        if ($progress) {
132
            $progress->finish();
133
        }
134
    }
135
}
136