Completed
Push — master ( 1008a1...9cabe1 )
by Tobias
01:30
created

Loco::getProject()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 4
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 6
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 $projectsByDomain = [];
42
43
    /**
44
     * @param LocoClient    $client
45
     * @param LocoProject[] $projectsByDomain
46
     */
47 1
    public function __construct(LocoClient $client, array $projectsByDomain)
48
    {
49 1
        $this->client = $client;
50 1
        $this->projectsByDomain = $projectsByDomain;
51 1
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function get($locale, $domain, $key)
57
    {
58
        $projectKey = $this->getProject($domain);
59
60
        try {
61
            $translation = $this->client->translations()->get($projectKey, $key, $locale)->getTranslation();
0 ignored issues
show
Documentation introduced by
$projectKey is of type object<Translation\Platf...Loco\Model\LocoProject>, 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...
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
        if (!empty($message->getMeta('parameters'))) {
120
            // Pretty print the Meta field via YAML export
121
            $dump = Yaml::dump(['parameters' => $message->getMeta('parameters')], 4, 5);
122
            $dump = str_replace("     -\n", '', $dump);
123
            $dump = str_replace('     ', "\xC2\xA0", $dump); // no break space
124
125
            $this->client->asset()->patch(
126
                $project->getApiKey(),
127
                $message->getKey(),
128
                null,
129
                null,
130
                null,
131
                $dump
132
            );
133
        }
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function update(Message $message)
140
    {
141
        $project = $this->getProject($message->getDomain());
142
        try {
143
            $this->client->translations()->create($project->getApiKey(), $message->getKey(), $message->getLocale(), $message->getTranslation());
144
        } catch (NotFoundException $e) {
145
            $this->create($message);
146
        }
147
    }
148
149
    /**
150
     * {@inheritdoc}
151
     */
152
    public function delete($locale, $domain, $key)
153
    {
154
        $project = $this->getProject($domain);
155
156
        $this->client->translations()->delete($project->getApiKey(), $key, $locale);
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162 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...
163
    {
164
        $locale = $catalogue->getLocale();
165
        foreach ($this->projectsByDomain as $domain => $project) {
166
            try {
167
                $data = $this->client->export()->locale(
168
                    $project->getApiKey(),
169
                    $locale,
170
                    'xliff',
171
                    ['format' => 'symfony', 'status' => 'translated', 'index' => $project->getIndexParameter()]
172
                );
173
174
                $catalogue->addCatalogue(XliffConverter::contentToCatalogue($data, $locale, $domain));
0 ignored issues
show
Bug introduced by
It seems like $data defined by $this->client->export()-...->getIndexParameter())) on line 167 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...
175
            } catch (NotFoundException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
176
            }
177
        }
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183 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...
184
    {
185
        $locale = $catalogue->getLocale();
186
        foreach ($this->projectsByDomain as $domain => $project) {
187
            $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...
188
            $this->client->import()->import(
189
                $project->getApiKey(),
190
                'xliff',
191
                $data,
192
                ['locale' => $locale, 'async' => 1, 'index' => $project->getIndexParameter()]
193
            );
194
        }
195
    }
196
197
    private function getProject($domain): LocoProject
198
    {
199
        if (isset($this->projectsByDomain[$domain])) {
200
            return $this->projectsByDomain[$domain];
201
        }
202
203
        throw new StorageException(sprintf('Project for "%s" domain was not found.', $domain));
204
    }
205
}
206