Completed
Pull Request — master (#89)
by
unknown
452:27 queued 387:21
created

TranslationManager::edit()   B

Complexity

Conditions 5
Paths 11

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
rs 8.439
cc 5
eloc 16
nc 11
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
    public function getTranslation($id)
119
    {
120
        return $this->repository->find($id);
121
    }
122
123
    /**
124
     * Returns all translations if filters are not specified
125
     *
126
     * @param array $filters An array with specified limitations for results
127
     *
128
     * @return DocumentIterator
129
     */
130
    public function getTranslations(array $filters = null)
131
    {
132
        $search = $this->repository->createSearch();
133
        $search->addQuery(new MatchAllQuery());
134
        $search->setScroll('2m');
135
136
        if ($filters) {
137
            foreach ($filters as $field => $value) {
138
                $search->addFilter(new TermsQuery($field, $value));
139
            }
140
        }
141
142
        return $this->repository->findDocuments($search);
143
    }
144
145
    /**
146
     * @param Translation[] $translations
147
     */
148
    public function saveTranslations($translations)
149
    {
150
        foreach ($translations as $translation) {
151
            $this->repository->getManager()->persist($translation);
152
        }
153
154
        $this->repository->getManager()->commit();
155
    }
156
157
    /**
158
     * @param Translation $document
159
     * @param array $messages
160
     */
161
    private function updateMessages(Translation $document, array $messages)
162
    {
163
        $setMessagesLocales = array_keys($document->getMessagesArray());
164
        $documentMessages = $document->getMessages();
165
166
        foreach ($messages as $locale => $messageText) {
167
            if (!empty($messageText) && is_string($messageText)) {
168
                $this->dispatcher->dispatch(
169
                    Events::ADD_HISTORY,
170
                    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...
171
                );
172
173
                if (in_array($locale, $setMessagesLocales)) {
174
                    foreach ($documentMessages as $message) {
175
                        if ($message->getLocale() == $locale && $message->getMessage() != $messageText) {
176
                            $this->historyManager->addHistory($message, $document);
177
                            $this->updateMessageData($message, $locale, $messages[$locale], new \DateTime());
178
                            break;
179
                        }
180
                    }
181
                } else {
182
                    $documentMessages[] = $this->updateMessageData(new Message(), $locale, $messageText);
183
                }
184
            }
185
        }
186
187
        $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...
188
    }
189
190
    /**
191
     * @param Message   $message
192
     * @param string    $locale
193
     * @param string    $text
194
     * @param \DateTime $updatedAt
195
     *
196
     * @return Message
197
     */
198
    private function updateMessageData(Message $message, $locale, $text, $updatedAt = null)
199
    {
200
        $message->setLocale($locale);
201
        $message->setStatus(Message::DIRTY);
202
        $message->setMessage($text);
203
204
        if ($updatedAt) {
205
            $message->setUpdatedAt($updatedAt);
206
        }
207
208
        return $message;
209
    }
210
211
    /**
212
     * Returns a list of available tags or domains
213
     *
214
     * @param string $type
215
     * @return array
216
     */
217
    private function getItems($type)
218
    {
219
        $search = $this->repository->createSearch();
220
        $search->addAggregation(new TermsAggregation($type, $type));
221
        $result = $this->repository->findDocuments($search);
222
        $aggregation = $result->getAggregation($type);
223
        $items = [];
224
225
        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...
226
            $items[] = $item['key'];
227
        }
228
229
        return $items;
230
    }
231
}
232