Completed
Push — master ( 992188...6b183b )
by Tobias
06:43
created

Loco::export()   B

Complexity

Conditions 5
Paths 11

Size

Total Lines 23
Code Lines 14

Duplication

Lines 23
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 23
loc 23
ccs 0
cts 12
cp 0
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 14
nc 11
nop 1
crap 30
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\Storage;
22
use Translation\Common\TransferableStorage;
23
use Translation\PlatformAdapter\Loco\Model\LocoProject;
24
use Translation\SymfonyStorage\XliffConverter;
25
26
/**
27
 * Localize.biz.
28
 *
29
 * @author Tobias Nyholm <[email protected]>
30
 */
31
class Loco implements Storage, TransferableStorage
32
{
33
    /**
34
     * @var LocoClient
35
     */
36
    private $client;
37
38
    /**
39
     * @var LocoProject[]
40
     */
41
    private $projects = [];
42
43
    /**
44
     * @param LocoClient    $client
45
     * @param LocoProject[] $projects
46
     */
47 1
    public function __construct(LocoClient $client, array $projects)
48
    {
49 1
        $this->client = $client;
50 1
        $this->projects = $projects;
51 1
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function get($locale, $domain, $key)
57
    {
58
        $project = $this->getProject($domain);
59
60
        try {
61
            $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...
62
        } catch (\FAPI\Localise\Exception $e) {
63
            return null;
64
        }
65
        $meta = [];
66
67
        return new Message($key, $domain, $locale, $translation, $meta);
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function create(Message $message)
74
    {
75
        $project = $this->getProject($message->getDomain());
76
        $isNewAsset = true;
77
78
        try {
79
            // Create asset first
80
            $this->client->asset()->create($project->getApiKey(), $message->getKey());
81
        } catch (AssetConflictException $e) {
82
            // This is okey
83
            $isNewAsset = false;
84
        }
85
86
        $translation = $message->getTranslation();
87
88
        // translation is the same as the key, so we will set it to empty string
89
        // as it was not translated and stats on loco will be unaffected
90
        if ($message->getKey() === $message->getTranslation()) {
91
            $translation = '';
92
        }
93
94
        if ($isNewAsset) {
95
            $this->client->translations()->create(
96
                $project->getApiKey(),
97
                $message->getKey(),
98
                $message->getLocale(),
99
                $translation
100
            );
101
        } else {
102
            try {
103
                $this->client->translations()->get(
104
                    $project->getApiKey(),
105
                    $message->getKey(),
106
                    $message->getLocale()
107
                );
108
            } catch (NotFoundException $e) {
109
                // Create only if not found.
110
                $this->client->translations()->create(
111
                    $project->getApiKey(),
112
                    $message->getKey(),
113
                    $message->getLocale(),
114
                    $translation
115
                );
116
            }
117
        }
118
119
        $this->client->asset()->tag($project->getApiKey(), $message->getKey(), $message->getDomain());
120
121
        if (!empty($message->getMeta('parameters'))) {
122
            // Pretty print the Meta field via YAML export
123
            $dump = Yaml::dump(['parameters' => $message->getMeta('parameters')], 4, 5);
124
            $dump = str_replace("     -\n", '', $dump);
125
            $dump = str_replace('     ', "\xC2\xA0", $dump); // no break space
126
127
            $this->client->asset()->patch(
128
                $project->getApiKey(),
129
                $message->getKey(),
130
                null,
131
                null,
132
                null,
133
                $dump
134
            );
135
        }
136
    }
137
138
    /**
139
     * {@inheritdoc}
140
     */
141
    public function update(Message $message)
142
    {
143
        $project = $this->getProject($message->getDomain());
144
145
        try {
146
            $this->client->translations()->create($project->getApiKey(), $message->getKey(), $message->getLocale(), $message->getTranslation());
147
        } catch (NotFoundException $e) {
148
            $this->create($message);
149
        }
150
    }
151
152
    /**
153
     * {@inheritdoc}
154
     */
155
    public function delete($locale, $domain, $key)
156
    {
157
        $project = $this->getProject($domain);
158
159
        $this->client->translations()->delete($project->getApiKey(), $key, $locale);
160
    }
161
162
    /**
163
     * {@inheritdoc}
164
     */
165 View Code Duplication
    public function export(MessageCatalogueInterface $catalogue)
0 ignored issues
show
Duplication introduced by
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...
166
    {
167
        $locale = $catalogue->getLocale();
168
        foreach ($this->projects as $project) {
169
            foreach ($project->getDomains() as $domain) {
170
                try {
171
                    $params = [
172
                        'format' => 'symfony',
173
                        'status' => 'translated',
174
                        'index' => $project->getIndexParameter(),
175
                    ];
176
177
                    if ($project->isMultiDomain()) {
178
                        $params['filter'] = $domain;
179
                    }
180
181
                    $data = $this->client->export()->locale($project->getApiKey(), $locale, 'xliff', $params);
182
                    $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 181 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...
183
                } catch (NotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
184
                }
185
            }
186
        }
187
    }
188
189
    /**
190
     * {@inheritdoc}
191
     */
192 View Code Duplication
    public function import(MessageCatalogueInterface $catalogue)
0 ignored issues
show
Duplication introduced by
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...
193
    {
194
        $locale = $catalogue->getLocale();
195
        foreach ($this->projects as $project) {
196
            foreach ($project->getDomains() as $domain) {
197
                $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...
198
                $params = [
199
                    'locale' => $locale,
200
                    'async' => 1,
201
                    'index' => $project->getIndexParameter(),
202
                ];
203
204
                if ($project->isMultiDomain()) {
205
                    $params['tag-all'] = $domain;
206
                }
207
208
                $this->client->import()->import($project->getApiKey(), 'xliff', $data, $params);
209
            }
210
        }
211
    }
212
213
    private function getProject($domain): LocoProject
214
    {
215
        foreach ($this->projects as $project) {
216
            if ($project->hasDomain($domain)) {
217
                return $project;
218
            }
219
        }
220
221
        throw new StorageException(sprintf('Project for "%s" domain was not found.', $domain));
222
    }
223
}
224