Completed
Pull Request — master (#89)
by
unknown
83:11 queued 18:18
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\ElasticsearchDSL\Aggregation\Bucketing\TermsAggregation;
17
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
18
use ONGR\ElasticsearchDSL\Query\TermsQuery;
19
use ONGR\ElasticsearchBundle\Service\Repository;
20
use ONGR\TranslationsBundle\Document\Message;
21
use ONGR\TranslationsBundle\Document\Translation;
22
use ONGR\TranslationsBundle\Event\Events;
23
use ONGR\TranslationsBundle\Event\TranslationEditMessageEvent;
24
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
25
use Symfony\Component\HttpFoundation\Request;
26
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
27
28
/**
29
 * Handles translation objects by http requests.
30
 */
31
class TranslationManager
32
{
33
    /**
34
     * @var Repository
35
     */
36
    private $repository;
37
38
    /**
39
     * @var HistoryManager
40
     */
41
    private $historyManager;
42
43
    /**
44
     * @var EventDispatcherInterface
45
     */
46
    private $dispatcher;
47
48
    /**
49
     * @param Repository               $repository
50
     * @param HistoryManager           $manager
51
     * @param EventDispatcherInterface $dispatcher
52
     */
53
    public function __construct(Repository $repository, HistoryManager $manager, EventDispatcherInterface $dispatcher)
54
    {
55
        $this->repository = $repository;
56
        $this->historyManager = $manager;
57
        $this->dispatcher = $dispatcher;
58
    }
59
60
    /**
61
     * Edits object from translation.
62
     *
63
     * @param string $id
64
     * @param Request $request Http request object.
65
     */
66
    public function edit($id, Request $request)
67
    {
68
        $content = json_decode($request->getContent(), true);
69
70
        if (empty($content)) {
71
            return;
72
        }
73
74
        $document = $this->getTranslation($id);
75
76
        if (isset($content['messages'])) {
77
            $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...
78
            unset($content['messages']);
79
        }
80
81
        try {
82
            foreach ($content as $key => $value) {
83
                $document->{'set'.ucfirst($key)}($value);
84
            }
85
86
            $document->setUpdatedAt(new \DateTime());
87
        } catch (\Exception $e) {
88
            throw new \LogicException('Illegal variable provided for translation');
89
        }
90
91
        $this->repository->getManager()->persist($document);
0 ignored issues
show
Bug introduced by
It seems like $document defined by $this->getTranslation($id) on line 74 can be null; however, ONGR\ElasticsearchBundle...vice\Manager::persist() 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...
92
        $this->repository->getManager()->commit();
93
    }
94
95
    /**
96
     * Returns all active tags from translations
97
     * @return array
98
     */
99
    public function getTags()
100
    {
101
        return $this->getItems('tags');
102
    }
103
104
    /**
105
     * Returns all active domains from translations
106
     * @return array
107
     */
108
    public function getDomains()
109
    {
110
        return $this->getItems('domain');
111
    }
112
113
    /**
114
     * @param string $id
115
     *
116
     * @return Translation
117
     *
118
     * @throws BadRequestHttpException
119
     */
120
    public function getTranslation($id)
121
    {
122
        try {
123
            $document = $this->repository->find($id);
124
        } catch (Missing404Exception $e) {
125
            throw new BadRequestHttpException('Invalid translation Id.');
126
        }
127
128
        return $document;
129
    }
130
131
    /**
132
     * Returns all translations if filters are not specified
133
     *
134
     * @param array $filters An array with specified limitations for results
135
     *
136
     * @return DocumentIterator
137
     */
138
    public function getTranslations(array $filters = null)
139
    {
140
        $search = $this->repository->createSearch();
141
        $search->addQuery(new MatchAllQuery());
142
        $search->setScroll('2m');
143
144
        if ($filters) {
145
            foreach ($filters as $field => $value) {
146
                $search->addFilter(new TermsQuery($field, $value));
147
            }
148
        }
149
150
        return $this->repository->findDocuments($search);
151
    }
152
153
    /**
154
     * @param Translation[] $translations
155
     */
156
    public function saveTranslations($translations)
157
    {
158
        foreach ($translations as $translation) {
159
            $this->repository->getManager()->persist($translation);
160
        }
161
162
        $this->repository->getManager()->commit();
163
    }
164
165
    /**
166
     * @param Translation $document
167
     * @param array $messages
168
     */
169
    private function updateMessages(Translation $document, array $messages)
170
    {
171
        $setMessagesLocales = array_keys($document->getMessagesArray());
172
        $documentMessages = $document->getMessages();
173
174
        foreach ($messages as $locale => $messageText) {
175
            if (!empty($messageText) && is_string($messageText)) {
176
                $this->dispatcher->dispatch(
177
                    Events::ADD_HISTORY,
178
                    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...
179
                );
180
181
                if (in_array($locale, $setMessagesLocales)) {
182
                    foreach ($documentMessages as $message) {
183
                        if ($message->getLocale() == $locale && $message->getMessage() != $messageText) {
184
                            $this->historyManager->addHistory($message, $document);
185
                            $this->updateMessageData($message, $locale, $messages[$locale], new \DateTime());
186
                            break;
187
                        }
188
                    }
189
                } else {
190
                    $documentMessages[] = $this->updateMessageData(new Message(), $locale, $messageText);
191
                }
192
            }
193
        }
194
195
        $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...
196
    }
197
198
    /**
199
     * @param Message   $message
200
     * @param string    $locale
201
     * @param string    $text
202
     * @param \DateTime $updatedAt
203
     *
204
     * @return Message
205
     */
206
    private function updateMessageData(Message $message, $locale, $text, $updatedAt = null)
207
    {
208
        $message->setLocale($locale);
209
        $message->setStatus(Message::DIRTY);
210
        $message->setMessage($text);
211
212
        if ($updatedAt) {
213
            $message->setUpdatedAt($updatedAt);
214
        }
215
216
        return $message;
217
    }
218
219
    /**
220
     * Returns a list of available tags or domains
221
     *
222
     * @param string $type
223
     * @return array
224
     */
225
    private function getItems($type)
226
    {
227
        if (!in_array($type, ['tags', 'domain'])) {
228
            throw new \LogicException();
229
        }
230
231
        $search = $this->repository->createSearch();
232
        $search->addAggregation(new TermsAggregation($type, $type));
233
        $result = $this->repository->findDocuments($search);
234
        $aggregation = $result->getAggregation($type);
235
        $items = [];
236
237
        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...
238
            $items[] = $item['key'];
239
        }
240
241
        return $items;
242
    }
243
}
244