Completed
Pull Request — master (#89)
by
unknown
452:27 queued 387:21
created

ImportManager::findTranslationsFiles()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
rs 8.7624
cc 5
eloc 13
nc 16
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[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 ONGR\TranslationsBundle\Service\Import;
13
14
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
15
use ONGR\ElasticsearchBundle\Service\Manager;
16
use ONGR\TranslationsBundle\Document\Message;
17
use ONGR\TranslationsBundle\Document\Translation;
18
use Symfony\Component\Finder\Finder;
19
20
/**
21
 * Collects translations.
22
 */
23
class ImportManager
24
{
25
    /**
26
     * @var FileImport
27
     */
28
    private $fileImport;
29
30
    /**
31
     * @var array
32
     */
33
    private $locales;
34
35
    /**
36
     * @var array
37
     */
38
    private $domains;
39
40
    /**
41
     * @var array
42
     */
43
    private $formats;
44
45
    /**
46
     * @var array
47
     */
48
    private $translations = [];
49
50
    /**
51
     * @var Manager
52
     */
53
    private $esManager;
54
55
    /**
56
     * @param FileImport $fileImport
57
     * @param Manager    $esManager
58
     */
59
    public function __construct(
60
        FileImport $fileImport,
61
        Manager $esManager
62
    ) {
63
        $this->fileImport = $fileImport;
64
        $this->esManager = $esManager;
65
    }
66
67
    /**
68
     * @return mixed
69
     */
70
    public function getDomains()
71
    {
72
        return $this->domains;
73
    }
74
75
    /**
76
     * @param mixed $domains
77
     */
78
    public function setDomains($domains)
79
    {
80
        $this->domains = $domains;
0 ignored issues
show
Documentation Bug introduced by
It seems like $domains of type * is incompatible with the declared type array of property $domains.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
81
    }
82
83
    /**
84
     * @return mixed
85
     */
86
    public function getLocales()
87
    {
88
        return $this->locales;
89
    }
90
91
    /**
92
     * @param mixed $locales
93
     */
94
    public function setLocales($locales)
95
    {
96
        $this->locales = $locales;
0 ignored issues
show
Documentation Bug introduced by
It seems like $locales of type * is incompatible with the declared type array of property $locales.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
97
    }
98
99
    /**
100
     * @return mixed
101
     */
102
    public function getFormats()
103
    {
104
        return $this->formats;
105
    }
106
107
    /**
108
     * @param mixed $formats
109
     */
110
    public function setFormats($formats)
111
    {
112
        $this->formats = $formats;
0 ignored issues
show
Documentation Bug introduced by
It seems like $formats of type * is incompatible with the declared type array of property $formats.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
113
    }
114
115
    /**
116
     * Write translations to storage.
117
     */
118
    public function writeToStorage()
119
    {
120
        foreach ($this->translations as $domain => $keys) {
121
            foreach ($keys as $key => $transMeta) {
122
                $document = new Translation();
123
                $document->setDomain($domain);
124
                $document->setKey($key);
125
                $document->setPath($transMeta['path']);
126
                $document->setFormat($transMeta['format']);
127
                foreach ($transMeta['messages'] as $locale => $text) {
128
                    $message = new Message();
129
                    $message->setLocale($locale);
130
                    $message->setMessage($text);
131
                    $document->addMessage($message);
132
                }
133
                $this->esManager->persist($document);
134
            }
135
        }
136
137
        $this->esManager->commit();
138
    }
139
140
    /**
141
     * Imports translation files from a directory.
142
     * @param string $dir
143
     */
144
    public function importDirTranslationFiles($dir)
145
    {
146
        $finder = $this->findTranslationsFiles($dir);
147
        $this->importTranslationFiles($finder);
0 ignored issues
show
Bug introduced by
It seems like $finder defined by $this->findTranslationsFiles($dir) on line 146 can be null; however, ONGR\TranslationsBundle\...mportTranslationFiles() 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...
148
    }
149
150
    /**
151
     * Imports translation files form all bundles.
152
     *
153
     * @param array $bundles
154
     * @param bool  $isBundle
155
     */
156
    public function importBundlesTranslationFiles($bundles, $isBundle = false)
157
    {
158
        foreach ($bundles as $bundle) {
159
            $dir = $isBundle?
160
                dir($bundle->getPath())->path :
0 ignored issues
show
Bug introduced by
The property path does not seem to exist in Directory.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
161
                dirname((new \ReflectionClass($bundle))->getFileName());
162
163
            $this->importDirTranslationFiles($dir);
164
        }
165
    }
166
167
    /**
168
     * Return a Finder object if $path has a Resources/translations folder.
169
     *
170
     * @param string $path
171
     *
172
     * @return Finder
173
     */
174
    protected function findTranslationsFiles($path)
175
    {
176
        $finder = null;
177
178
        if (preg_match('#^win#i', PHP_OS)) {
179
            $path = preg_replace('#' . preg_quote(DIRECTORY_SEPARATOR, '#') . '#', '/', $path);
180
        } else {
181
            $path = str_replace('\\', '/', $path);
182
        }
183
184
        $dir = $path . '/Resources/translations';
185
186
        if (is_dir($dir)) {
187
            $finder = new Finder();
188
            $finder->files()
189
                ->name($this->getFileNamePattern())
190
                ->in($dir);
191
        }
192
193
        return (null !== $finder && $finder->count() > 0) ? $finder : null;
194
    }
195
196
    /**
197
     * @return string
198
     */
199
    protected function getFileNamePattern()
200
    {
201
        if (count($this->getDomains())) {
202
            $regex = sprintf(
203
                '/((%s)\.(%s)\.(%s))/',
204
                implode('|', $this->getDomains()),
205
                implode('|', $this->getLocales()),
206
                implode('|', $this->getFormats())
207
            );
208
        } else {
209
            $regex = sprintf(
210
                '/(.*\.(%s)\.(%s))/',
211
                implode('|', $this->getLocales()),
212
                implode('|', $this->getFormats())
213
            );
214
        }
215
216
        return $regex;
217
    }
218
219
    /**
220
     * Imports some translations files.
221
     *
222
     * @param Finder $finder
223
     */
224
    protected function importTranslationFiles($finder)
225
    {
226
        if ($finder instanceof Finder) {
227
            foreach ($finder as $file) {
228
                $this->translations = array_replace_recursive($this->fileImport->import($file), $this->translations);
229
            }
230
        }
231
    }
232
}
233