Completed
Push — master ( 488311...d1b79f )
by Sascha-Oliver
05:57
created

PhraseApp::update()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 0
cts 25
cp 0
rs 8.439
c 0
b 0
f 0
cc 5
eloc 16
nc 5
nop 1
crap 30
1
<?php
2
3
namespace Translation\PlatformAdapter\PhraseApp;
4
5
use FAPI\PhraseApp\Model\Key\KeyCreated;
6
use FAPI\PhraseApp\Model\Key\KeySearchResults;
7
use FAPI\PhraseApp\Model\Translation\Index;
8
use FAPI\PhraseApp\PhraseAppClient;
9
use Symfony\Component\Translation\MessageCatalogueInterface;
10
use Translation\Common\Exception\StorageException;
11
use Translation\Common\Model\Message;
12
use Translation\Common\Storage;
13
use Translation\Common\TransferableStorage;
14
use Translation\PlatformAdapter\PhraseApp\Bridge\Symfony\XliffConverter;
15
16
/**
17
 * @author Sascha-Oliver Prolic <[email protected]>
18
 */
19
class PhraseApp implements Storage, TransferableStorage
20
{
21
    /**
22
     * @var PhraseAppClient
23
     */
24
    private $client;
25
26
    /**
27
     * @var string
28
     */
29
    private $projectId;
30
31
    /**
32
     * @var array
33
     */
34
    private $localeToIdMapping;
35
36
    /**
37
     * @var array
38
     */
39
    private $domains;
40
41
    /**
42
     * @var string|null
43
     */
44
    private $defaultLocale;
45
46
    public function __construct(
47
        PhraseAppClient $client,
48
        string $projectId,
49
        array $localeToIdMapping,
50
        array $domains,
51
        string $defaultLocale = null
52
    ) {
53
        $this->client = $client;
54
        $this->projectId = $projectId;
55
        $this->localeToIdMapping = $localeToIdMapping;
56
        $this->domains = $domains;
57
        $this->defaultLocale = $defaultLocale;
58
    }
59
60
    public function get($locale, $domain, $key)
61
    {
62
        /* @var Index $index */
63
        $index = $this->client->translation()->indexLocale($this->projectId, $this->getLocaleId($locale), [
64
            'tags' => $domain
65
        ]);
66
67
        foreach ($index->getTranslations() as $translation) {
0 ignored issues
show
Bug introduced by
The method getTranslations() does not seem to exist on object<FAPI\PhraseApp\Model\Translation\Index>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
68
            if ($translation->getKey()->getName() === $domain.'::'.$key) {
69
                return new Message($key, $domain, $locale, $translation->getContent(), []);
70
            }
71
        }
72
    }
73
74
    public function create(Message $message)
75
    {
76
        $localeId = $this->getLocaleId($message->getLocale());
77
78
        /* @var KeySearchResults $result */
79
        $result = $this->client->key()->search($this->projectId, [
80
            'tags' => $message->getDomain(),
81
            'name' => $message->getDomain().'::'.$message->getKey(),
82
        ]);
83
84
        foreach ($result as $key) {
85
            if ($key->getName() === $message->getDomain().'::'.$message->getKey()) {
86
                /* @var Index $index */
87
                $index = $this->client->translation()->indexKey($this->projectId, $key->getId(), ['tags' => $message->getDomain()]);
88
89
                foreach ($index as $translation) {
90
                    if ($translation->getLocale()->getId() === $localeId
91
                        && $translation->getContent() !== $message->getTranslation()
92
                    ) {
93
                        $this->client->translation()->update($this->projectId, $translation->getId(), $message->getTranslation());
94
95
                        return;
96
                    }
97
                }
98
99
                $this->client->translation()->create($this->projectId, $localeId, $key->getId(), $message->getTranslation());
100
101
                return;
102
            }
103
        }
104
105
        /* @var KeyCreated $keyCreated */
106
        $keyCreated = $this->client->key()->create($this->projectId, $message->getDomain().'::'.$message->getKey(), [
107
            'tags' => $message->getDomain(),
108
        ]);
109
110
        $this->client->translation()->create(
111
            $this->projectId,
112
            $this->getLocaleId($message->getLocale()),
113
            $keyCreated->getId(),
114
            $message->getTranslation()
115
        );
116
    }
117
118
    public function update(Message $message)
119
    {
120
        $localeId = $this->getLocaleId($message->getLocale());
121
        /* @var KeySearchResults $results */
122
        $results = $this->client->key()->search($this->projectId, [
123
            'tags' => $message->getDomain(),
124
            'name' => $message->getDomain().'::'.$message->getKey()
125
        ]);
126
127
        foreach ($results as $searchResult) {
128
            if ($searchResult->getName() === $message->getDomain().'::'.$message->getKey()) {
129
130
                /* @var Index $translations */
131
                $translations = $this->client->translation()->indexKey($this->projectId, $searchResult->getId(), [
132
                    'tags' => $message->getDomain(),
133
                ]);
134
135
                foreach ($translations as $translation) {
136
                    if ($translation->getLocale()->getId() === $localeId) {
137
                        $this->client->translation()->update(
138
                            $this->projectId,
139
                            $translation->getId(),
140
                            $message->getTranslation()
141
                        );
142
143
                        return;
144
                    }
145
                }
146
            }
147
        }
148
    }
149
150
    public function delete($locale, $domain, $key)
151
    {
152
        /* @var KeySearchResults $results */
153
        $results = $this->client->key()->search($this->projectId, $this->getLocaleId($locale), [
0 ignored issues
show
Documentation introduced by
$this->getLocaleId($locale) is of type string, but the function expects a array.

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...
Unused Code introduced by
The call to Key::search() has too many arguments starting with array('tags' => $domain,... $domain . '::' . $key).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
154
            'tags' => $domain,
155
            'name' => $domain.'::'.$key
156
        ]);
157
158
        foreach ($results->getSearchResults() as $searchResult) {
0 ignored issues
show
Bug introduced by
The method getSearchResults() does not seem to exist on object<FAPI\PhraseApp\Model\Key\KeySearchResults>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
159
            if ($searchResult->getName() === $domain.'::'.$key) {
160
                $this->client->key()->delete($this->projectId, $searchResult->getId());
161
                break;
162
            }
163
        }
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169
    public function export(MessageCatalogueInterface $catalogue)
170
    {
171
        $locale = $catalogue->getLocale();
172
        $localeId = $this->getLocaleId($locale);
173
174
        foreach ($this->domains as $domain) {
175
            try {
176
                $response = $this->client->locale()->download($this->projectId, $localeId, 'symfony_xliff', [
177
                    'tag' => $domain
178
                ]);
179
            } catch (\Throwable $e) {
180
                throw new StorageException($e->getMessage());
181
            }
182
183
            try {
184
                $newCatalogue = XliffConverter::contentToCatalogue($response, $locale, $domain);
0 ignored issues
show
Bug introduced by
It seems like $response defined by $this->client->locale()-...rray('tag' => $domain)) on line 176 can also be of type object<Psr\Http\Message\ResponseInterface>; however, Translation\PlatformAdap...r::contentToCatalogue() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
185
186
                $messages = [];
187
188
                foreach ($newCatalogue->all($domain) as $message => $translation) {
189
                    $messages[substr($message, strlen($domain) + 2)] = $translation;
190
                }
191
192
                $newCatalogue->replace($messages, $domain);
193
194
                $catalogue->addCatalogue($newCatalogue);
195
            } catch (\Throwable $e) {
196
                // ignore empty translation files
197
            }
198
        }
199
200
        return $catalogue;
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function import(MessageCatalogueInterface $catalogue)
207
    {
208
        $locale = $catalogue->getLocale();
209
        $localeId = $this->getLocaleId($locale);
210
211
        foreach ($this->domains as $domain) {
212
            $messages = [];
213
214
            foreach ($catalogue->all($domain) as $message => $translation) {
215
                $messages[$domain . '::' . $message] = $translation;
216
            }
217
218
            $catalogue->replace($messages, $domain);
219
220
            if ($this->defaultLocale) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->defaultLocale of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
221
                $options = ['default_locale' => $this->defaultLocale];
222
            } else {
223
                $options = [];
224
            }
225
226
            $data = XliffConverter::catalogueToContent($catalogue, $domain, $options);
0 ignored issues
show
Compatibility introduced by
$catalogue of type object<Symfony\Component...sageCatalogueInterface> is not a sub-type of object<Symfony\Component...ation\MessageCatalogue>. It seems like you assume a concrete implementation of the interface Symfony\Component\Transl...ssageCatalogueInterface to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
227
228
            $file = sys_get_temp_dir() . '/' . $domain . '.' . $locale . '.xlf';
229
230
            try {
231
                file_put_contents($file, $data);
232
233
                $this->client->upload()->upload($this->projectId, 'symfony_xliff', $file, [
234
                    'locale_id' => $localeId,
235
                    'tags' => $domain,
236
                ]);
237
            } catch (\Throwable $e) {
238
                throw new StorageException($e->getMessage());
239
            } finally {
240
                unlink($file);
241
            }
242
        }
243
    }
244
245
    private function getLocaleId(string $locale): string
246
    {
247
        if (isset($this->localeToIdMapping[$locale])) {
248
            return $this->localeToIdMapping[$locale];
249
        }
250
251
        throw new StorageException(sprintf('Id for locale "%s" has not been configured.', $locale));
252
    }
253
}
254