Completed
Push — master ( 92ccbf...b2415b )
by Simonas
63:39
created

TranslationManager::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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