Completed
Pull Request — master (#89)
by
unknown
62:49
created

TranslationManager::updateMessages()   C

Complexity

Conditions 8
Paths 6

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
ccs 0
cts 17
cp 0
rs 5.3846
cc 8
eloc 17
nc 6
nop 2
crap 72
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\Translation;
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
use Symfony\Component\PropertyAccess\PropertyAccess;
30
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
31
32
/**
33
 * Handles translation objects by http requests.
34
 */
35
class TranslationManager
36
{
37
    /**
38
     * @var Repository
39
     */
40
    private $repository;
41
42
    /**
43
     * @var HistoryManager
44
     */
45
    private $historyManager;
46
47
    /**
48
     * @var EventDispatcherInterface
49
     */
50
    private $dispatcher;
51
52
    /**
53
     * @param Repository               $repository
54
     * @param HistoryManager           $manager
55
     * @param EventDispatcherInterface $dispatcher
56
     */
57
    public function __construct(Repository $repository, HistoryManager $manager, EventDispatcherInterface $dispatcher)
58
    {
59
        $this->repository = $repository;
60
        $this->historyManager = $manager;
61
        $this->dispatcher = $dispatcher;
62
    }
63
64
    /**
65
     * Edits object from translation.
66
     *
67
     * @param string $id
68
     * @param Request $request Http request object.
69
     */
70
    public function edit($id, Request $request)
71
    {
72
        $content = $this->parseJsonContent($request);
73
        $document = $this->getTranslation($id);
74
75
        if (isset($content['messages'])) {
76
            $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...
77
            unset($content['messages']);
78
        }
79
80
        try {
81
            foreach ($content as $key => $value) {
82
                $document->{'set'.ucfirst($key)}($value);
83
            }
84
85
            $document->setUpdatedAt(new \DateTime());
86
        } catch (\Exception $e) {
87
            throw new \LogicException('Illegal variable provided for translation');
88
        }
89
90
        $this->commitTranslation($document);
0 ignored issues
show
Bug introduced by
It seems like $document defined by $this->getTranslation($id) on line 73 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...
91
    }
92
93
    /**
94
     * @param Translation $document
95
     * @param array $messages
96
     */
97
    private function updateMessages(Translation $document, array $messages)
98
    {
99
        $setMessagesLocales = array_keys($document->getMessagesArray());
100
        $documentMessages = $document->getMessages();
101
102
        foreach ($messages as $locale => $messageText) {
103
            if (!empty($messageText) && is_string($messageText)) {
104
                $this->dispatcher->dispatch(
105
                    Events::ADD_HISTORY,
106
                    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...
107
                );
108
109
                if (in_array($locale, $setMessagesLocales)) {
110
                    foreach ($documentMessages as $message) {
111
                        if ($message->getLocale() == $locale && $message->getMessage() != $messageText) {
112
                            $this->historyManager->addHistory($message, $document->getId(), $locale);
113
                            $this->updateMessageData($message, $locale, $messages[$locale], new \DateTime());
114
                            break;
115
                        }
116
                    }
117
                } else {
118
                    $documentMessages[] = $this->updateMessageData(new Message(), $locale, $messageText);
119
                }
120
            }
121
        }
122
123
        $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...
124
    }
125
126
    /**
127
     * @param Message   $message
128
     * @param string    $locale
129
     * @param string    $text
130
     * @param \DateTime $updatedAt
131
     *
132
     * @return Message
133
     */
134
    private function updateMessageData(Message $message, $locale, $text, $updatedAt = null)
135
    {
136
        $message->setLocale($locale);
137
        $message->setStatus(Message::DIRTY);
138
        $message->setMessage($text);
139
140
        if ($updatedAt) {
141
            $message->setUpdatedAt($updatedAt);
142
        }
143
144
        return $message;
145
    }
146
147
    /**
148
     * Returns specific values from objects.
149
     *
150
     * @param Request $request Http request object.
151
     *
152
     * @return array
153
     */
154
    public function get(Request $request)
155
    {
156
        $content = $this->parseJsonContent($request);
157
158
        $search = $this
159
            ->repository
160
            ->createSearch()
161
            ->addFilter(new ExistsQuery($content['name']));
162
163
        if (array_key_exists('properties', $content)) {
164
            foreach ($content['properties'] as $property) {
165
                $search->setSource($content['name'] . '.' . $property);
166
            }
167
        }
168
169
        if (array_key_exists('findBy', $content)) {
170
            foreach ($content['findBy'] as $field => $value) {
171
                $search->addQuery(
172
                    new TermsQuery($content['name'] . '.' . $field, is_array($value) ? $value : [$value]),
173
                    'must'
174
                );
175
            }
176
        }
177
178
        return $this->repository->execute($search, Result::RESULTS_ARRAY);
0 ignored issues
show
Deprecated Code introduced by
The method ONGR\ElasticsearchBundle...e\Repository::execute() has been deprecated with message: Use strict execute functions instead. e.g. executeIterator, executeRawIterator.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
179
    }
180
181
    /**
182
     * @return DocumentIterator
183
     */
184
    public function getAllTranslations()
185
    {
186
        $search = $this->repository->createSearch();
187
        $search->addQuery(new MatchAllQuery());
188
        $search->setSize(1000);
189
190
        return $this->repository->findDocuments($search);
191
    }
192
193
    /**
194
     * Returns all active tags from translations
195
     * @return array
196
     */
197
    public function getTags()
198
    {
199
        return $this->getItems('tags');
200
    }
201
202
    /**
203
     * Returns all active domains from translations
204
     * @return array
205
     */
206
    public function getDomains()
207
    {
208
        return $this->getItems('domain');
209
    }
210
211
    /**
212
     * @param string $type
213
     * @return array
214
     */
215
    private function getItems($type)
216
    {
217
        if (!in_array($type, ['tags', 'domain'])) {
218
            throw new \LogicException();
219
        }
220
221
        $search = $this->repository->createSearch();
222
        $search->addAggregation(new TermsAggregation($type, $type));
223
        $result = $this->repository->findDocuments($search);
224
        $aggregation = $result->getAggregation($type);
225
        $items = [];
226
227
        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...
228
            $items[] = $item['key'];
229
        }
230
231
        return $items;
232
    }
233
234
    /**
235
     * Parses http request content from json to array.
236
     *
237
     * @param Request $request Http request object.
238
     *
239
     * @return array
240
     *
241
     * @throws BadRequestHttpException
242
     */
243
    private function parseJsonContent(Request $request)
244
    {
245
        $content = json_decode($request->getContent(), true);
246
247
        if (empty($content)) {
248
            throw new BadRequestHttpException('No content found.');
249
        }
250
251
        return $content;
252
    }
253
254
    /**
255
     * @param object $document
256
     */
257
    private function commitTranslation($document)
258
    {
259
        $this->repository->getManager()->persist($document);
260
        $this->repository->getManager()->commit();
261
    }
262
263
    /**
264
     * Returns translation from elasticsearch.
265
     *
266
     * @param string $id
267
     *
268
     * @return Translation
269
     *
270
     * @throws BadRequestHttpException
271
     */
272
    private function getTranslation($id)
273
    {
274
        try {
275
            $document = $this->repository->find($id);
276
        } catch (Missing404Exception $e) {
277
            throw new BadRequestHttpException('Invalid translation Id.');
278
        }
279
280
        return $document;
281
    }
282
}
283