Completed
Push — master ( 91fdab...75a7b9 )
by
unknown
13:37
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
     * @var TranslationFileExplorer
19
     */
20
    private $translationFileExplorer;
21
22
    /**
23
     * Importer
24
     * @var Importer
25
     */
26
    private $importer;
27
28
    /**
29
     * Execute an import command
30
     * @param  ImportCommand $importCommand
31
     * @return int           total number of files imported
32
     */
33
    public function executeImportCommand(ImportCommand $importCommand)
34
    {
35
        if ($importCommand->getDefaultBundle() === false || $importCommand->getDefaultBundle() === null) {
36
            return $this->importGlobalTranslationFiles($importCommand);
37
        }
38
39
        return $this->importBundleTranslationFiles($importCommand);
40
    }
41
42
    /**
43
     * Import all translation files from app resources
44
     * @param  ImportCommand $importCommand
45
     * @return int           total number of files imported
46
     */
47
    private function importGlobalTranslationFiles(ImportCommand $importCommand)
48
    {
49
        $locales = $this->determineLocalesToImport($importCommand);
50
        $finder = $this->translationFileExplorer->find($this->kernel->getRootDir(), $locales);
51
52
        return $this->importTranslationFiles($finder, $importCommand->getForce());
53
    }
54
55
    /**
56
     * Import all translation files from a specific bundle, bundle name will be lowercased so cases don't matter
57
     * @param  ImportCommand $importCommand
58
     * @return int           total number of files imported
59
     */
60
    public function importBundleTranslationFiles(ImportCommand $importCommand)
61
    {
62
        $importBundle = strtolower($importCommand->getDefaultBundle());
63
64
        if ($importBundle == 'all') {
65
            return $this->importAllBundlesTranslationFiles($importCommand);
66
        } elseif ($importBundle == 'custom') {
67
            return $this->importCustomBundlesTranslationFiles($importCommand);
68
        } else {
69
            return $this->importOwnBundlesTranslationFiles($importCommand);
70
        }
71
    }
72
73
    /**
74
     * Import all translation files from all registered bundles (in AppKernel)
75
     * @param  ImportCommand $importCommand
76
     * @return int           total number of files imported
77
     */
78 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...
79
    {
80
        $bundles = array_map('strtolower', array_keys($this->kernel->getBundles()));
81
        $imported = 0;
82
83
        foreach ($bundles as $bundle) {
84
            $importCommand->setDefaultBundle($bundle);
85
86
            try {
87
                $imported += $this->importSingleBundleTranslationFiles($importCommand);
88
            } catch (TranslationsNotFoundException $e) {
89
                continue;
90
            }
91
        }
92
93
        return $imported;
94
    }
95
96
    /**
97
     * Import all translation files from your own registered bundles (in src/ directory)
98
     * @param  ImportCommand $importCommand
99
     * @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...
100
     */
101
    private function importOwnBundlesTranslationFiles(ImportCommand $importCommand)
102
    {
103
        $imported = 0;
104
        $srcDir = dirname($this->kernel->getRootDir()) . '/src';
105
106
        foreach($this->kernel->getBundles() as $name => $bundle) {
107
            if (strpos($bundle->getPath(), $srcDir) !== false) {
108
                $importCommand->setDefaultBundle(strtolower($name));
109
110
                try {
111
                    $imported += $this->importSingleBundleTranslationFiles($importCommand);
112
                } catch (TranslationsNotFoundException $e) {
113
                    continue;
114
                }
115
            }
116
        }
117
118
        return $imported;
119
    }
120
121
    /**
122
     * Import the translation files from the defined bundles.
123
     * @param  ImportCommand $importCommand
124
     * @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...
125
     */
126 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...
127
    {
128
        $imported = 0;
129
130
        foreach($importCommand->getBundles() as $bundle) {
131
            $importCommand->setDefaultBundle(strtolower($bundle));
132
133
            try {
134
                $imported += $this->importSingleBundleTranslationFiles($importCommand);
135
            } catch (TranslationsNotFoundException $e) {
136
                continue;
137
            }
138
        }
139
140
        return $imported;
141
    }
142
143
    /**
144
     * Import all translation files from a single bundle
145
     * @param  ImportCommand $importCommand
146
     * @return int           total number of files imported
147
     */
148
    private function importSingleBundleTranslationFiles(ImportCommand $importCommand)
149
    {
150
        $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...
151
        $bundles = array_change_key_case($this->kernel->getBundles(), CASE_LOWER);
152
        $finder = $this->translationFileExplorer->find($bundles[strtolower($importCommand->getDefaultBundle())]->getPath(), $this->determineLocalesToImport($importCommand));
153
154
        if ($finder === null) {
155
            return 0;
156
        }
157
158
        return $this->importTranslationFiles($finder, $importCommand->getForce());
159
    }
160
161
    /**
162
     * Import translation files from a specific Finder object
163
     * The finder object shoud already have the files to look for defined;
164
     * Forcing the import will override all existing translations in the stasher
165
     * @param  Finder  $finder
166
     * @param  boolean $force  override identical translations in the stasher (domain/locale and keyword combination)
167
     * @return int     total number of files imported
168
     */
169
    private function importTranslationFiles(Finder $finder, $force = flase)
170
    {
171
        if (!$finder instanceof Finder) {
172
            return false;
173
        }
174
175
        $imported = 0;
176
177
        foreach ($finder as $file) {
178
            $imported += $this->importer->import($file, $force);
179
        }
180
181
        return $imported;
182
    }
183
184
    /**
185
     * Validates that a bundle is registered in the AppKernel
186
     * @param  string     $bundle
187
     * @return boolean    bundle is valid or not
188
     * @throws \Exception If the bundlename isn't valid
189
     */
190
    public function validateBundleName($bundle)
191
    {
192
        // strtolower all bundle names
193
        $bundles = array_map('strtolower', array_keys($this->kernel->getBundles()));
194
195
        if (in_array(strtolower(trim($bundle)), $bundles)) {
196
            return true;
197
        }
198
199
        throw new \Exception(sprintf('bundle "%s" not found in available bundles: %s', $bundle, implode(', ', $bundles)));
200
    }
201
202
    /**
203
     * Gives an array with all languages that needs to be imported (from the given ImportCommand)
204
     * If non is given, all managed locales will be used (defined in config)
205
     * @param  ImportCommand $importCommand
206
     * @return array         all locales to import by the given ImportCommand
207
     */
208
    public function determineLocalesToImport(ImportCommand $importCommand)
209
    {
210
        if ($importCommand->getLocales() === false || $importCommand->getLocales() === null) {
211
            return $this->managedLocales;
212
        }
213
214
        return $this->parseRequestedLocales($importCommand->getLocales());
215
    }
216
217
    public function setTranslationFileExplorer($translationFileExplorer)
218
    {
219
        $this->translationFileExplorer = $translationFileExplorer;
220
    }
221
222
    public function setImporter($importer)
223
    {
224
        $this->importer = $importer;
225
    }
226
}
227