Test Failed
Push — master ( c9c10d...19d548 )
by Nicolas
05:23
created

MissingCommand::translateValues()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 10
nc 2
nop 1
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace NicolasBeauvais\Transcribe\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Arr;
7
use NicolasBeauvais\Transcribe\Manager;
8
9
class MissingCommand extends Command
10
{
11
    /**
12
     * The name and signature of the console command.
13
     *
14
     * @var string
15
     */
16
    protected $signature = 'transcribe:missing {--default}';
17
18
    /**
19
     * The name and signature of the console command.
20
     *
21
     * @var string
22
     */
23
    protected $description = 'Find missing translation values and fill them.';
24
25
    /**
26
     * The Languages manager instance.
27
     *
28
     * @var \NicolasBeauvais\Transcribe\Manager
29
     */
30
    private $manager;
31
32
    /**
33
     * Array of requested file in different languages.
34
     *
35
     * @var array
36
     */
37
    protected $files;
38
39
    /**
40
     * ListCommand constructor.
41
     *
42
     * @param \NicolasBeauvais\Transcribe\Manager $manager
43
     *
44
     * @return void
45
     */
46
    public function __construct(Manager $manager)
47
    {
48
        parent::__construct();
49
50
        $this->manager = $manager;
51
    }
52
53
    /**
54
     * Execute the console command.
55
     *
56
     * @return mixed
57
     */
58
    public function handle()
59
    {
60
        $this->info('Looking for missing translations...');
61
62
        $languages = $this->manager->languages();
63
64
        $missing = $this->getMissing($languages);
65
66
        $values = $this->translateValues($missing);
0 ignored issues
show
Unused Code introduced by
The assignment to $values is dead and can be removed.
Loading history...
67
68
        $this->info('Done!');
69
    }
70
71
    /**
72
     * Collect translation values from console via questions.
73
     *
74
     * @param array $missing
75
     *
76
     * @return array
77
     */
78
    private function translateValues(array $missing)
79
    {
80
        $values = [];
81
82
        foreach ($missing as $missingKey) {
83
            $value = $this->ask(
84
                "<fg=yellow>{$missingKey}</> translation", $this->getDefaultValue($missingKey)
85
            );
86
87
            preg_match('/^([^\.]*)\.(.*):(.*)/', $missingKey, $matches);
88
89
            $this->manager->fillKeys(
90
                $matches[1],
91
                [$matches[2] => [$matches[3] => $value]]
92
            );
93
94
            $this->line("\"<fg=yellow>{$missingKey}</>\" was set to \"<fg=yellow>{$value}</>\" successfully.");
95
        }
96
97
        return $values;
98
    }
99
100
    /**
101
     * Get translation in default locale for the given key.
102
     *
103
     * @param string $missingKey
104
     *
105
     * @return string
106
     */
107
    private function getDefaultValue($missingKey)
108
    {
109
        if (!$this->option('default')) {
110
            return;
111
        }
112
113
        try {
114
            $missingKey = explode(':', $missingKey)[0];
115
116
            $decomposedKey = explode('.', $missingKey);
117
            $file = array_shift($decomposedKey);
118
            $key = implode('.', $decomposedKey);
119
120
            $filePath = $this->manager->files()[$file][config('app.fallback_locale')];
121
122
            return config('app.fallback_locale') . ':' . array_get($this->manager->getFileContent($filePath), $key);
123
        } catch (\Exception $e) {
124
            return;
125
        }
126
    }
127
128
    /**
129
     * Get an array of keys that have missing values with a hint
130
     * from another language translation file if possible.
131
     *
132
     * ex: [ ['key' => 'product.color.nl', 'hint' => 'en = "color"'] ]
133
     *
134
     * @param array $languages
135
     *
136
     * @return array
137
     */
138
    private function getMissing(array $languages)
0 ignored issues
show
Unused Code introduced by
The parameter $languages is not used and could be removed. ( Ignorable by Annotation )

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

138
    private function getMissing(/** @scrutinizer ignore-unused */ array $languages)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
139
    {
140
        $files = $this->manager->files();
141
142
        // Array of content of all files indexed by fileName.languageKey
143
        $filesResults = [];
144
145
        // The final output of the method
146
        $missing = [];
147
148
        // Here we collect the file results
149
        foreach ($files as $fileName => $languageFiles) {
150
            foreach ($languageFiles as $languageKey => $filePath) {
151
                $filesResults[$fileName][$languageKey] = $this->manager->getFileContent($filePath);
152
            }
153
        }
154
155
        $values = Arr::dot($filesResults);
156
157
        $emptyValues = array_filter($values, function ($value) {
158
            return $value == '';
159
        });
160
161
        // Adding all keys that has values = ''
162
        foreach ($emptyValues as $dottedValue => $emptyValue) {
163
            list($fileName, $languageKey, $key) = explode('.', $dottedValue, 3);
164
165
            $missing[] = "{$fileName}.{$key}:{$languageKey}";
166
        }
167
168
        $missing = array_merge($missing, $this->manager->getKeysExistingInALanguageButNotTheOther($values));
169
170
        return $missing;
171
    }
172
}
173