Completed
Pull Request — master (#92)
by
unknown
355:42 queued 290:59
created

TranslationManager::saveTranslations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
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
     * @param string $id
53
     *
54
     * @return Translation
55
     */
56
    public function get($id)
57
    {
58
        return $this->repository->find($id);
59
    }
60
61
    /**
62
     * Returns all active tags from translations
63
     * @return array
64
     */
65
    public function getTags()
66
    {
67
        return $this->getItems('tags');
68
    }
69
70
    /**
71
     * Returns all active domains from translations
72
     * @return array
73
     */
74
    public function getDomains()
75
    {
76
        return $this->getItems('domain');
77
    }
78
79
    /**
80
     * Returns all translations if filters are not specified
81
     *
82
     * @param array $filters An array with specified limitations for results
83
     *
84
     * @return DocumentIterator
85
     */
86
    public function getAll(array $filters = null)
87
    {
88
        $search = $this->repository->createSearch();
89
        $search->addQuery(new MatchAllQuery());
90
        $search->setScroll('2m');
91
92
        if ($filters) {
93
            foreach ($filters as $field => $value) {
94
                $search->addFilter(new TermsQuery($field, $value));
95
            }
96
        }
97
98
        return $this->repository->findDocuments($search);
99
    }
100
101
    /**
102
     * Edits object from translation.
103
     *
104
     * @param string $id
105
     * @param Request $request Http request object.
106
     */
107
    public function update($id, Request $request)
108
    {
109
        $content = json_decode($request->getContent(), true);
110
111
        if (empty($content)) {
112
            return;
113
        }
114
115
        $document = $this->get($id);
116
117
        if (isset($content['messages'])) {
118
            $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...
119
            unset($content['messages']);
120
        }
121
122
        try {
123
            foreach ($content as $key => $value) {
124
                $document->{'set'.ucfirst($key)}($value);
125
            }
126
127
            $document->setUpdatedAt(new \DateTime());
128
        } catch (\Error $e) {
129
            throw new \LogicException('Illegal variable provided for translation');
130
        }
131
132
        $this->repository->getManager()->persist($document);
0 ignored issues
show
Bug introduced by
It seems like $document defined by $this->get($id) on line 115 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...
133
        $this->repository->getManager()->commit();
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