Completed
Pull Request — master (#89)
by
unknown
65:00
created

TranslationManager::updateMessages()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
rs 5.3846
cc 8
eloc 17
nc 6
nop 2
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;
13
14
use Elasticsearch\Common\Exceptions\Missing404Exception;
15
use ONGR\ElasticsearchBundle\Result\DocumentIterator;
16
use ONGR\ElasticsearchBundle\Result\Result;
17
use ONGR\ElasticsearchDSL\Aggregation\Bucketing\TermsAggregation;
18
use ONGR\ElasticsearchDSL\Query\ExistsQuery;
19
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
20
use ONGR\ElasticsearchDSL\Query\TermsQuery;
21
use ONGR\ElasticsearchBundle\Service\Repository;
22
use ONGR\TranslationsBundle\Document\Message;
23
use ONGR\TranslationsBundle\Document\Translation;
24
use ONGR\TranslationsBundle\Event\Events;
25
use ONGR\TranslationsBundle\Event\TranslationEditMessageEvent;
26
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
27
use Symfony\Component\HttpFoundation\Request;
28
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
29
30
/**
31
 * Handles translation objects by http requests.
32
 */
33
class TranslationManager
34
{
35
    /**
36
     * @var Repository
37
     */
38
    private $repository;
39
40
    /**
41
     * @var HistoryManager
42
     */
43
    private $historyManager;
44
45
    /**
46
     * @var EventDispatcherInterface
47
     */
48
    private $dispatcher;
49
50
    /**
51
     * @param Repository               $repository
52
     * @param HistoryManager           $manager
53
     * @param EventDispatcherInterface $dispatcher
54
     */
55
    public function __construct(Repository $repository, HistoryManager $manager, EventDispatcherInterface $dispatcher)
56
    {
57
        $this->repository = $repository;
58
        $this->historyManager = $manager;
59
        $this->dispatcher = $dispatcher;
60
    }
61
62
    /**
63
     * Edits object from translation.
64
     *
65
     * @param string $id
66
     * @param Request $request Http request object.
67
     */
68
    public function edit($id, Request $request)
69
    {
70
        $content = $this->parseJsonContent($request);
71
        $document = $this->getTranslation($id);
72
73
        if (isset($content['messages'])) {
74
            $this->updateMessages($document, $content['messages']);
0 ignored issues
show
Documentation introduced by
$document is of type null|object<ReflectionClass>, but the function expects a object<ONGR\Translations...e\Document\Translation>.

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...
75
            unset($content['messages']);
76
        }
77
78
        try {
79
            foreach ($content as $key => $value) {
80
                $document->{'set'.ucfirst($key)}($value);
81
            }
82
83
            $document->setUpdatedAt(new \DateTime());
84
        } catch (\Exception $e) {
85
            throw new \LogicException('Illegal variable provided for translation');
86
        }
87
88
        $this->commitTranslation($document);
0 ignored issues
show
Bug introduced by
It seems like $document defined by $this->getTranslation($id) on line 71 can be null; however, ONGR\TranslationsBundle\...er::commitTranslation() 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...
89
    }
90
91
    /**
92
     * Returns all active tags from translations
93
     * @return array
94
     */
95
    public function getTags()
96
    {
97
        return $this->getItems('tags');
98
    }
99
100
    /**
101
     * Returns all active domains from translations
102
     * @return array
103
     */
104
    public function getDomains()
105
    {
106
        return $this->getItems('domain');
107
    }
108
109
    /**
110
     * @param string $id
111
     *
112
     * @return Translation
113
     *
114
     * @throws BadRequestHttpException
115
     */
116
    public function getTranslation($id)
117
    {
118
        try {
119
            $document = $this->repository->find($id);
120
        } catch (Missing404Exception $e) {
121
            throw new BadRequestHttpException('Invalid translation Id.');
122
        }
123
124
        return $document;
125
    }
126
127
    /**
128
     * Returns all translations if filters are not specified
129
     *
130
     * @param array $filters An array with specified limitations for results
131
     *
132
     * @return DocumentIterator
133
     */
134
    public function getTranslations(array $filters = null)
135
    {
136
        $search = $this->repository->createSearch();
137
        $search->addQuery(new MatchAllQuery());
138
        $search->setScroll('2m');
139
140
        if ($filters) {
141
            foreach ($filters as $field => $value) {
142
                $search->addFilter(new TermsQuery($field, $value));
143
            }
144
        }
145
146
        return $this->repository->findDocuments($search);
147
    }
148
149
    /**
150
     * @param Translation[] $translations
151
     */
152
    public function saveTranslations($translations)
153
    {
154
        foreach ($translations as $translation) {
155
            $this->repository->getManager()->persist($translation);
156
        }
157
158
        $this->repository->getManager()->commit();
159
    }
160
161
    /**
162
     * @param Translation $document
163
     * @param array $messages
164
     */
165
    private function updateMessages(Translation $document, array $messages)
166
    {
167
        $setMessagesLocales = array_keys($document->getMessagesArray());
168
        $documentMessages = $document->getMessages();
169
170
        foreach ($messages as $locale => $messageText) {
171
            if (!empty($messageText) && is_string($messageText)) {
172
                $this->dispatcher->dispatch(
173
                    Events::ADD_HISTORY,
174
                    new TranslationEditMessageEvent($document, $locale)
0 ignored issues
show
Documentation introduced by
$locale is of type integer|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...
175
                );
176
177
                if (in_array($locale, $setMessagesLocales)) {
178
                    foreach ($documentMessages as $message) {
179
                        if ($message->getLocale() == $locale && $message->getMessage() != $messageText) {
180
                            $this->historyManager->addHistory($message, $document);
181
                            $this->updateMessageData($message, $locale, $messages[$locale], new \DateTime());
182
                            break;
183
                        }
184
                    }
185
                } else {
186
                    $documentMessages[] = $this->updateMessageData(new Message(), $locale, $messageText);
187
                }
188
            }
189
        }
190
191
        $document->setMessages($documentMessages);
0 ignored issues
show
Documentation introduced by
$documentMessages is of type array<integer,object<ONG...ndle\Document\Message>>, but the function expects a null|object<ONGR\Elastic...\Collection\Collection>.

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...
192
    }
193
194
    /**
195
     * @param Message   $message
196
     * @param string    $locale
197
     * @param string    $text
198
     * @param \DateTime $updatedAt
199
     *
200
     * @return Message
201
     */
202
    private function updateMessageData(Message $message, $locale, $text, $updatedAt = null)
203
    {
204
        $message->setLocale($locale);
205
        $message->setStatus(Message::DIRTY);
206
        $message->setMessage($text);
207
208
        if ($updatedAt) {
209
            $message->setUpdatedAt($updatedAt);
210
        }
211
212
        return $message;
213
    }
214
215
    /**
216
     * Returns a list of available tags or domains
217
     *
218
     * @param string $type
219
     * @return array
220
     */
221
    private function getItems($type)
222
    {
223
        if (!in_array($type, ['tags', 'domain'])) {
224
            throw new \LogicException();
225
        }
226
227
        $search = $this->repository->createSearch();
228
        $search->addAggregation(new TermsAggregation($type, $type));
229
        $result = $this->repository->findDocuments($search);
230
        $aggregation = $result->getAggregation($type);
231
        $items = [];
232
233
        foreach ($aggregation as $item) {
0 ignored issues
show
Bug introduced by
The expression $aggregation of type null|object<ONGR\Elastic...ation\AggregationValue> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
234
            $items[] = $item['key'];
235
        }
236
237
        return $items;
238
    }
239
240
    /**
241
     * Parses http request content from json to array.
242
     *
243
     * @param Request $request Http request object.
244
     *
245
     * @return array
246
     *
247
     * @throws BadRequestHttpException
248
     */
249
    private function parseJsonContent(Request $request)
250
    {
251
        $content = json_decode($request->getContent(), true);
252
253
        if (empty($content)) {
254
            throw new BadRequestHttpException('No content found.');
255
        }
256
257
        return $content;
258
    }
259
260
    /**
261
     * @param object $document
262
     */
263
    private function commitTranslation($document)
264
    {
265
        $this->repository->getManager()->persist($document);
266
        $this->repository->getManager()->commit();
267
    }
268
}
269