Completed
Push — master ( 1de9b7...830752 )
by Kristof
38:46 queued 24:09
created

Service/Command/Importer/ImportCommandHandler.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\TranslatorBundle\Service\Command\Importer;
4
5
use Kunstmaan\TranslatorBundle\Model\Import\ImportCommand;
6
use Kunstmaan\TranslatorBundle\Service\Command\AbstractCommandHandler;
7
use Kunstmaan\TranslatorBundle\Service\Exception\TranslationsNotFoundException;
8
use Kunstmaan\TranslatorBundle\Service\TranslationFileExplorer;
9
use Symfony\Component\Finder\Finder;
10
11
/**
12
 * Parses an ImportCommand
13
 */
14
class ImportCommandHandler extends AbstractCommandHandler
15
{
16
    /**
17
     * TranslationFileExplorer
18
     *
19
     * @var TranslationFileExplorer
20
     */
21
    private $translationFileExplorer;
22
23
    /**
24
     * Importer
25
     *
26
     * @var Importer
27
     */
28
    private $importer;
29
30
    /**
31
     * Execute an import command
32
     *
33
     * @param ImportCommand $importCommand
34
     *
35
     * @return int total number of files imported
36
     */
37
    public function executeImportCommand(ImportCommand $importCommand)
38
    {
39
        if ($importCommand->getDefaultBundle() === false || $importCommand->getDefaultBundle() === null) {
40
            return $this->importGlobalTranslationFiles($importCommand);
41
        }
42
43
        return $this->importBundleTranslationFiles($importCommand);
44
    }
45
46
    /**
47
     * Import all translation files from app resources
48
     *
49
     * @param ImportCommand $importCommand
50
     *
51
     * @return int total number of files imported
52
     */
53
    private function importGlobalTranslationFiles(ImportCommand $importCommand)
54
    {
55
        $locales = $this->determineLocalesToImport($importCommand);
56
        $finder = $this->translationFileExplorer->find($this->kernel->getRootDir(), $locales);
57
58
        return $this->importTranslationFiles($finder, $importCommand->getForce());
59
    }
60
61
    /**
62
     * Import all translation files from a specific bundle, bundle name will be lowercased so cases don't matter
63
     *
64
     * @param ImportCommand $importCommand
65
     *
66
     * @return int total number of files imported
67
     */
68
    public function importBundleTranslationFiles(ImportCommand $importCommand)
69
    {
70
        $importBundle = strtolower($importCommand->getDefaultBundle());
71
72
        if ($importBundle == 'all') {
73
            return $this->importAllBundlesTranslationFiles($importCommand);
74
        } elseif ($importBundle == 'custom') {
75
            return $this->importCustomBundlesTranslationFiles($importCommand);
76
        } else {
77
            return $this->importOwnBundlesTranslationFiles($importCommand);
78
        }
79
    }
80
81
    /**
82
     * Import all translation files from all registered bundles (in AppKernel)
83
     *
84
     * @param ImportCommand $importCommand
85
     *
86
     * @return int total number of files imported
87
     */
88 View Code Duplication
    private function importAllBundlesTranslationFiles(ImportCommand $importCommand)
0 ignored issues
show
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...
89
    {
90
        $bundles = array_map('strtolower', array_keys($this->kernel->getBundles()));
91
        $imported = 0;
92
93
        foreach ($bundles as $bundle) {
94
            $importCommand->setDefaultBundle($bundle);
95
96
            try {
97
                $imported += $this->importSingleBundleTranslationFiles($importCommand);
98
            } catch (TranslationsNotFoundException $e) {
99
                continue;
100
            }
101
        }
102
103
        return $imported;
104
    }
105
106
    /**
107
     * Import all translation files from your own registered bundles (in src/ directory)
108
     *
109
     * @param ImportCommand $importCommand
110
     *
111
     * @return int The total number of imported files
0 ignored issues
show
Should the return type not be integer|double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
112
     */
113
    private function importOwnBundlesTranslationFiles(ImportCommand $importCommand)
114
    {
115
        $imported = 0;
116
        $srcDir = dirname($this->kernel->getRootDir()) . '/src';
117
118
        foreach ($this->kernel->getBundles() as $name => $bundle) {
119
            if (strpos($bundle->getPath(), $srcDir) !== false) {
120
                $importCommand->setDefaultBundle(strtolower($name));
121
122
                try {
123
                    $imported += $this->importSingleBundleTranslationFiles($importCommand);
124
                } catch (TranslationsNotFoundException $e) {
125
                    continue;
126
                }
127
            }
128
        }
129
130
        return $imported;
131
    }
132
133
    /**
134
     * Import the translation files from the defined bundles.
135
     *
136
     * @param ImportCommand $importCommand
137
     *
138
     * @return int The total number of imported files
0 ignored issues
show
Should the return type not be integer|double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
139
     */
140 View Code Duplication
    private function importCustomBundlesTranslationFiles(ImportCommand $importCommand)
0 ignored issues
show
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...
141
    {
142
        $imported = 0;
143
144
        foreach ($importCommand->getBundles() as $bundle) {
145
            $importCommand->setDefaultBundle(strtolower($bundle));
146
147
            try {
148
                $imported += $this->importSingleBundleTranslationFiles($importCommand);
149
            } catch (TranslationsNotFoundException $e) {
150
                continue;
151
            }
152
        }
153
154
        return $imported;
155
    }
156
157
    /**
158
     * Import all translation files from a single bundle
159
     *
160
     * @param ImportCommand $importCommand
161
     *
162
     * @return int total number of files imported
163
     */
164
    private function importSingleBundleTranslationFiles(ImportCommand $importCommand)
165
    {
166
        $this->validateBundleName($importCommand->getDefaultBundle());
0 ignored issues
show
$importCommand->getDefaultBundle() is of type boolean, but the function expects a string.

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...
167
        $bundles = array_change_key_case($this->kernel->getBundles(), CASE_LOWER);
168
        $finder = $this->translationFileExplorer->find($bundles[strtolower($importCommand->getDefaultBundle())]->getPath(), $this->determineLocalesToImport($importCommand));
169
170
        if ($finder === null) {
171
            return 0;
172
        }
173
174
        return $this->importTranslationFiles($finder, $importCommand->getForce());
175
    }
176
177
    /**
178
     * Import translation files from a specific Finder object
179
     * The finder object shoud already have the files to look for defined;
180
     * Forcing the import will override all existing translations in the stasher
181
     *
182
     * @param Finder $finder
183
     * @param bool   $force  override identical translations in the stasher (domain/locale and keyword combination)
184
     *
185
     * @return int total number of files imported
186
     */
187
    private function importTranslationFiles(Finder $finder, $force = flase)
188
    {
189
        if (!$finder instanceof Finder) {
190
            return false;
191
        }
192
193
        $imported = 0;
194
195
        foreach ($finder as $file) {
196
            $imported += $this->importer->import($file, $force);
197
        }
198
199
        return $imported;
200
    }
201
202
    /**
203
     * Validates that a bundle is registered in the AppKernel
204
     *
205
     * @param string $bundle
206
     *
207
     * @return bool bundle is valid or not
208
     *
209
     * @throws \Exception If the bundlename isn't valid
210
     */
211
    public function validateBundleName($bundle)
212
    {
213
        // strtolower all bundle names
214
        $bundles = array_map('strtolower', array_keys($this->kernel->getBundles()));
215
216
        if (in_array(strtolower(trim($bundle)), $bundles)) {
217
            return true;
218
        }
219
220
        throw new \Exception(sprintf('bundle "%s" not found in available bundles: %s', $bundle, implode(', ', $bundles)));
221
    }
222
223
    /**
224
     * Gives an array with all languages that needs to be imported (from the given ImportCommand)
225
     * If non is given, all managed locales will be used (defined in config)
226
     *
227
     * @param ImportCommand $importCommand
228
     *
229
     * @return array all locales to import by the given ImportCommand
230
     */
231
    public function determineLocalesToImport(ImportCommand $importCommand)
232
    {
233
        if ($importCommand->getLocales() === false || $importCommand->getLocales() === null) {
234
            return $this->managedLocales;
235
        }
236
237
        return $this->parseRequestedLocales($importCommand->getLocales());
238
    }
239
240
    public function setTranslationFileExplorer($translationFileExplorer)
241
    {
242
        $this->translationFileExplorer = $translationFileExplorer;
243
    }
244
245
    public function setImporter($importer)
246
    {
247
        $this->importer = $importer;
248
    }
249
}
250