TranslationKeyToValueCommand::execute()   B
last analyzed

Complexity

Conditions 10
Paths 84

Size

Total Lines 47
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 32
nc 84
nop 2
dl 0
loc 47
rs 7.6666
c 0
b 0
f 0

How to fix   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
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\CoreBundle\Command;
15
16
use Symfony\Component\Console\Attribute\AsCommand;
17
use Symfony\Component\Console\Command\Command;
18
use Symfony\Component\Console\Exception\InvalidArgumentException;
19
use Symfony\Component\Console\Input\InputArgument;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\Console\Style\SymfonyStyle;
23
use Symfony\Component\DependencyInjection\Attribute\Autowire;
24
use Symfony\Component\Filesystem\Filesystem;
25
use Symfony\Component\Finder\Finder;
26
use Symfony\Component\HttpKernel\KernelInterface;
27
use Symfony\Component\Yaml\Yaml;
28
29
#[AsCommand(name: 'zikula:translation:keytovalue', description: 'Update translation files to remove null values and replace them with the key.')]
30
class TranslationKeyToValueCommand extends Command
31
{
32
    public function __construct(
33
        #[Autowire(param: 'translator.default_path')]
34
        private readonly ?string $defaultTransPath = null
35
    ) {
36
        parent::__construct();
37
    }
38
39
    protected function configure()
40
    {
41
        $this
42
            ->addArgument('bundle', InputArgument::OPTIONAL, 'The bundle name or directory where to load the messages')
43
            ->setHelp(
44
                <<<'EOF'
45
The <info>%command.name%</info> command transforms translation strings of a given
46
bundle or the default translations directory. It sets null messages to the value of the key.
47
48
It is recommended to run <info>php bin/console translation:extract</info> first.
49
50
Example running against a Bundle (AcmeBundle)
51
52
  <info>php %command.full_name% AcmeBundle</info>
53
54
Example running against default messages directory
55
56
  <info>php %command.full_name%</info>
57
EOF
58
            )
59
        ;
60
    }
61
62
    protected function execute(InputInterface $input, OutputInterface $output): int
63
    {
64
        $io = new SymfonyStyle($input, $output);
65
66
        /** @var KernelInterface $kernel */
67
        $kernel = $this->getApplication()->getKernel();
0 ignored issues
show
introduced by
The method getKernel() does not exist on Symfony\Component\Console\Application. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

67
        $kernel = $this->getApplication()->/** @scrutinizer ignore-call */ getKernel();
Loading history...
68
        $transPaths = [];
69
        if ($this->defaultTransPath) {
70
            $transPaths[] = $this->defaultTransPath;
71
        }
72
        $currentName = 'default directory';
73
        // Override with provided Bundle info (this section copied from symfony's translation:update command)
74
        if (null !== ($bundle = $input->getArgument('bundle'))) {
75
            try {
76
                $foundBundle = $kernel->getBundle($bundle);
77
                $bundleDir = $foundBundle->getPath();
78
                $transPaths = [is_dir($bundleDir . '/Resources/translations') ? $bundleDir . '/Resources/translations' : $bundleDir . '/translations'];
79
                $currentName = $foundBundle->getName();
80
            } catch (\InvalidArgumentException) {
81
                // such a bundle does not exist, so treat the argument as path
82
                $path = $bundle;
83
                $transPaths = [$path . '/translations'];
84
                if (!is_dir($transPaths[0]) && !isset($transPaths[1])) {
85
                    throw new InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0]));
86
                }
87
            }
88
        }
89
        $io->title('Translation Messages Key to Value Transformer');
90
        $io->comment(sprintf('Transforming translation files for "<info>%s</info>"', $currentName));
91
        $finder = new Finder();
92
        $fs = new Filesystem();
93
        foreach ($finder->files()->in($transPaths)->name(['*.yaml', '*.yml']) as $file) {
94
            $io->text(sprintf('<comment>Parsing %s</comment>', $file->getBasename()));
95
            $messages = Yaml::parseFile($file->getRealPath());
96
            foreach ($messages as $key => $message) {
97
                if (null === $message) {
98
                    $messages[$key] = $key;
99
                }
100
            }
101
            $io->text(sprintf('<info>Dumping %s</info>', $file->getBasename()));
102
            ksort($messages); // sort the messages by key
103
            $fs->dumpFile($file->getRealPath(), Yaml::dump($messages));
104
        }
105
106
        $io->success('Success!');
107
108
        return Command::SUCCESS;
109
    }
110
}
111