Completed
Push — master ( 130d29...c9c04e )
by Tobias
187:22 queued 181:29
created

ExtractCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 132
Duplicated Lines 8.33 %

Coupling/Cohesion

Components 2
Dependencies 13

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 9
lcom 2
cbo 13
dl 11
loc 132
ccs 0
cts 70
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A configure() 11 11 1
A execute() 0 44 4
A getConfiguredFinder() 0 15 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\Input\InputArgument;
16
use Symfony\Component\Console\Input\InputInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Console\Style\SymfonyStyle;
20
use Symfony\Component\Finder\Finder;
21
use Translation\Bundle\Catalogue\CatalogueCounter;
22
use Translation\Bundle\Catalogue\CatalogueFetcher;
23
use Translation\Bundle\Catalogue\CatalogueWriter;
24
use Translation\Bundle\Model\Configuration;
25
use Translation\Bundle\Service\ConfigurationManager;
26
use Translation\Bundle\Service\Importer;
27
use Translation\Extractor\Model\Error;
28
29
/**
30
 * @author Tobias Nyholm <[email protected]>
31
 */
32
class ExtractCommand extends Command
33
{
34
    use BundleTrait;
35
36
    protected static $defaultName = 'translation:extract';
37
38
    /**
39
     * @var CatalogueFetcher
40
     */
41
    private $catalogueFetcher;
42
43
    /**
44
     * @var CatalogueWriter
45
     */
46
    private $catalogueWriter;
47
48
    /**
49
     * @var CatalogueCounter
50
     */
51
    private $catalogueCounter;
52
53
    /**
54
     * @var Importer
55
     */
56
    private $importer;
57
58
    /**
59
     * @var ConfigurationManager
60
     */
61
    private $configurationManager;
62
63
    /**
64
     * @param CatalogueFetcher     $catalogueFetcher
65
     * @param CatalogueWriter      $catalogueWriter
66
     * @param CatalogueCounter     $catalogueCounter
67
     * @param Importer             $importer
68
     * @param ConfigurationManager $configurationManager
69
     */
70
    public function __construct(
71
        CatalogueFetcher $catalogueFetcher,
72
        CatalogueWriter $catalogueWriter,
73
        CatalogueCounter $catalogueCounter,
74
        Importer $importer,
75
        ConfigurationManager $configurationManager
76
    ) {
77
        $this->catalogueFetcher = $catalogueFetcher;
78
        $this->catalogueWriter = $catalogueWriter;
79
        $this->catalogueCounter = $catalogueCounter;
80
        $this->importer = $importer;
81
        $this->configurationManager = $configurationManager;
82
83
        parent::__construct();
84
    }
85
86 View Code Duplication
    protected function configure()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
87
    {
88
        $this
89
            ->setName(self::$defaultName)
90
            ->setDescription('Extract translations from source code.')
91
            ->addArgument('configuration', InputArgument::OPTIONAL, 'The configuration to use', 'default')
92
            ->addArgument('locale', InputArgument::OPTIONAL, 'The locale ot use. If omitted, we use all configured locales.', false)
93
            ->addOption('hide-errors', null, InputOption::VALUE_NONE, 'If we should print error or not')
94
            ->addOption('bundle', 'b', InputOption::VALUE_REQUIRED, 'The bundle you want extract translations from.')
95
        ;
96
    }
97
98
    protected function execute(InputInterface $input, OutputInterface $output)
99
    {
100
        $config = $this->configurationManager->getConfiguration($input->getArgument('configuration'));
101
102
        $locales = [];
103
        if ($inputLocale = $input->getArgument('locale')) {
104
            $locales = [$inputLocale];
105
        }
106
107
        $catalogues = $this->catalogueFetcher->getCatalogues($config, $locales);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->configurationMana...ument('configuration')) on line 100 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...
108
        $this->configureBundleDirs($input, $config);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->configurationMana...ument('configuration')) on line 100 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...
109
        $finder = $this->getConfiguredFinder($config);
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->configurationMana...ument('configuration')) on line 100 can be null; however, Translation\Bundle\Comma...::getConfiguredFinder() 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...
110
111
        $result = $this->importer->extractToCatalogues($finder, $catalogues, [
112
            'blacklist_domains' => $config->getBlacklistDomains(),
113
            'whitelist_domains' => $config->getWhitelistDomains(),
114
            'project_root' => $config->getProjectRoot(),
115
        ]);
116
        $errors = $result->getErrors();
117
118
        $this->catalogueWriter->writeCatalogues($config, $result->getMessageCatalogues());
0 ignored issues
show
Bug introduced by
It seems like $config defined by $this->configurationMana...ument('configuration')) on line 100 can be null; however, Translation\Bundle\Catal...iter::writeCatalogues() 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...
Documentation introduced by
$result->getMessageCatalogues() is of type array<integer,object<Sym...ageCatalogueInterface>>, but the function expects a array<integer,object<Sym...tion\MessageCatalogue>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
119
120
        $definedBefore = $this->catalogueCounter->getNumberOfDefinedMessages($catalogues[0]);
121
        $definedAfter = $this->catalogueCounter->getNumberOfDefinedMessages($result->getMessageCatalogues()[0]);
122
123
        /*
124
         * Print results
125
         */
126
        $io = new SymfonyStyle($input, $output);
127
        $io->table(['Type', 'Count'], [
128
            ['Total defined messages', $definedAfter],
129
            ['New messages', $definedAfter - $definedBefore],
130
            ['Errors', count($errors)],
131
        ]);
132
133
        if (!$input->getOption('hide-errors')) {
134
            /** @var Error $error */
135
            foreach ($errors as $error) {
136
                $io->error(
137
                    sprintf("%s\nLine: %s\nMessage: %s", $error->getPath(), $error->getLine(), $error->getMessage())
138
                );
139
            }
140
        }
141
    }
142
143
    /**
144
     * @param Configuration $config
145
     *
146
     * @return Finder
147
     */
148
    private function getConfiguredFinder(Configuration $config)
149
    {
150
        $finder = new Finder();
151
        $finder->in($config->getDirs());
152
153
        foreach ($config->getExcludedDirs() as $exclude) {
154
            $finder->notPath($exclude);
155
        }
156
157
        foreach ($config->getExcludedNames() as $exclude) {
158
            $finder->notName($exclude);
159
        }
160
161
        return $finder;
162
    }
163
}
164