Completed
Push — master ( 029d2f...81ffde )
by Tobias
08:28
created

Loco::export()   B

Complexity

Conditions 6
Paths 21

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 16
cp 0
rs 8.8817
c 0
b 0
f 0
cc 6
nc 21
nop 1
crap 42
1
<?php
2
3
/*
4
 * This file is part of the PHP Translation package.
5
 *
6
 * (c) PHP Translation team <[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 Translation\PlatformAdapter\Loco;
13
14
use FAPI\Localise\Exception\Domain\AssetConflictException;
15
use FAPI\Localise\Exception\Domain\NotFoundException;
16
use FAPI\Localise\LocoClient;
17
use Symfony\Component\Translation\MessageCatalogueInterface;
18
use Symfony\Component\Yaml\Yaml;
19
use Translation\Common\Exception\StorageException;
20
use Translation\Common\Model\Message;
21
use Translation\Common\Model\MessageInterface;
22
use Translation\Common\Storage;
23
use Translation\Common\TransferableStorage;
24
use Translation\PlatformAdapter\Loco\Model\LocoProject;
25
use Translation\SymfonyStorage\XliffConverter;
26
27
/**
28
 * Localize.biz.
29
 *
30
 * @author Tobias Nyholm <[email protected]>
31
 */
32
class Loco implements Storage, TransferableStorage
33
{
34
    /**
35
     * @var LocoClient
36
     */
37
    private $client;
38
39
    /**
40
     * @var LocoProject[]
41
     */
42
    private $projects = [];
43
44
    /**
45
     * @param LocoClient    $client
46
     * @param LocoProject[] $projects
47 1
     */
48
    public function __construct(LocoClient $client, array $projects)
49 1
    {
50 1
        $this->client = $client;
51 1
        $this->projects = $projects;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function get($locale, $domain, $key)
58
    {
59
        $project = $this->getProject($domain);
60
61
        try {
62
            $translation = $this->client->translations()->get($project->getApiKey(), $key, $locale)->getTranslation();
0 ignored issues
show
Bug introduced by
The method getTranslation does only exist in FAPI\Localise\Model\Translation\Translation, but not in Psr\Http\Message\ResponseInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
63
        } catch (\FAPI\Localise\Exception $e) {
64
            return null;
65
        }
66
        $meta = [];
67
68
        return new Message($key, $domain, $locale, $translation, $meta);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function create(MessageInterface $message)
75
    {
76
        $project = $this->getProject($message->getDomain());
77
        $isNewAsset = true;
78
79
        try {
80
            // Create asset first
81
            $this->client->asset()->create($project->getApiKey(), $message->getKey());
82
        } catch (AssetConflictException $e) {
83
            // This is okey
84
            $isNewAsset = false;
85
        }
86
87
        $translation = $message->getTranslation();
88
89
        // translation is the same as the key, so we will set it to empty string
90
        // as it was not translated and stats on loco will be unaffected
91
        if ($message->getKey() === $message->getTranslation()) {
92
            $translation = '';
93
        }
94
95
        if ($isNewAsset) {
96
            $this->client->translations()->create(
97
                $project->getApiKey(),
98
                $message->getKey(),
99
                $message->getLocale(),
100
                $translation
101
            );
102
        } else {
103
            try {
104
                $this->client->translations()->get(
105
                    $project->getApiKey(),
106
                    $message->getKey(),
107
                    $message->getLocale()
108
                );
109
            } catch (NotFoundException $e) {
110
                // Create only if not found.
111
                $this->client->translations()->create(
112
                    $project->getApiKey(),
113
                    $message->getKey(),
114
                    $message->getLocale(),
115
                    $translation
116
                );
117
            }
118
        }
119
120
        $this->client->asset()->tag($project->getApiKey(), $message->getKey(), $message->getDomain());
121
122
        if (!empty($message->getMeta('parameters'))) {
123
            // Pretty print the Meta field via YAML export
124
            $dump = Yaml::dump(['parameters' => $message->getMeta('parameters')], 4, 5);
125
            $dump = str_replace("     -\n", '', $dump);
126
            $dump = str_replace('     ', "\xC2\xA0", $dump); // no break space
127
128
            $this->client->asset()->patch(
129
                $project->getApiKey(),
130
                $message->getKey(),
131
                null,
132
                null,
133
                null,
134
                $dump
135
            );
136
        }
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function update(MessageInterface $message)
143
    {
144
        $project = $this->getProject($message->getDomain());
145
146
        try {
147
            $this->client->translations()->create($project->getApiKey(), $message->getKey(), $message->getLocale(), $message->getTranslation());
148
        } catch (NotFoundException $e) {
149
            $this->create($message);
150
        }
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156
    public function delete($locale, $domain, $key)
157
    {
158
        $project = $this->getProject($domain);
159
160
        $this->client->translations()->delete($project->getApiKey(), $key, $locale);
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function export(MessageCatalogueInterface $catalogue)
167
    {
168
        $locale = $catalogue->getLocale();
169
        foreach ($this->projects as $project) {
170
            foreach ($project->getDomains() as $domain) {
171
                try {
172
                    $params = [
173
                        'format' => 'symfony',
174
                        'index' => $project->getIndexParameter(),
175
                    ];
176
177
                    if ($project->getStatus()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $project->getStatus() 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...
178
                        $params['status'] = $project->getStatus();
179
                    }
180
181
                    if ($project->isMultiDomain()) {
182
                        $params['filter'] = $domain;
183
                    }
184
185
                    $data = $this->client->export()->locale($project->getApiKey(), $locale, 'xliff', $params);
186
                    $catalogue->addCatalogue(XliffConverter::contentToCatalogue($data, $locale, $domain));
0 ignored issues
show
Bug introduced by
It seems like $data defined by $this->client->export()-...cale, 'xliff', $params) on line 185 can also be of type object<Psr\Http\Message\ResponseInterface>; however, Translation\SymfonyStora...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...
Documentation introduced by
\Translation\SymfonyStor...data, $locale, $domain) is of type object<Symfony\Component...ation\MessageCatalogue>, but the function expects a object<self>.

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...
187
                } catch (NotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
188
                }
189
            }
190
        }
191
    }
192
193
    /**
194
     * {@inheritdoc}
195
     */
196
    public function import(MessageCatalogueInterface $catalogue)
197
    {
198
        $locale = $catalogue->getLocale();
199
        foreach ($this->projects as $project) {
200
            foreach ($project->getDomains() as $domain) {
201
                $data = XliffConverter::catalogueToContent($catalogue, $domain);
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...
202
                $params = [
203
                    'locale' => $locale,
204
                    'async' => 1,
205
                    'index' => $project->getIndexParameter(),
206
                ];
207
208
                if ($project->isMultiDomain()) {
209
                    $params['tag-all'] = $domain;
210
                }
211
212
                $this->client->import()->import($project->getApiKey(), 'xliff', $data, $params);
213
            }
214
        }
215
    }
216
217
    private function getProject($domain): LocoProject
218
    {
219
        foreach ($this->projects as $project) {
220
            if ($project->hasDomain($domain)) {
221
                return $project;
222
            }
223
        }
224
225
        throw new StorageException(sprintf('Project for "%s" domain was not found.', $domain));
226
    }
227
}
228