Completed
Pull Request — master (#92)
by
unknown
197:58 queued 132:49
created

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