Completed
Push — l10n_master ( 1196b3...ae29fe )
by Ruud
167:23 queued 153:15
created

TranslationRepository::findAllNotDisabled()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 3
nc 2
nop 2
1
<?php
2
3
namespace Kunstmaan\TranslatorBundle\Repository;
4
5
use DateTime;
6
use Exception;
7
use Kunstmaan\TranslatorBundle\Entity\Translation;
8
use Kunstmaan\TranslatorBundle\Model\Translation as TranslationModel;
9
use Kunstmaan\TranslatorBundle\Model\TextWithLocale;
10
11
/**
12
 * Translator Repository class
13
 */
14
class TranslationRepository extends AbstractTranslatorRepository
15
{
16
    /**
17
     * Get an array of all domains group by locales
18
     *
19
     * @return array array[0] = ["name" => "messages", "locale" => "nl"]
20
     */
21
    public function getAllDomainsByLocale()
22
    {
23
        return $this->createQueryBuilder('t')
24
            ->select('t.locale, t.domain name')
25
            ->addGroupBy('t.locale')
26
            ->addGroupBy('t.domain')
27
            ->getQuery()
28
            ->getArrayResult();
29
    }
30
31
    /**
32
     * Get an array of all non disabled translations
33
     * @param string $locale
34
     * @param string $domain
0 ignored issues
show
Documentation introduced by
Should the type for parameter $domain not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
35
     * @return array
36
     */
37
    public function findAllNotDisabled($locale, $domain = null)
38
    {
39
40
        $qb = $this->createQueryBuilder('t');
41
        $qb
42
            ->select('t')
43
            ->where('t.locale = :locale')
44
            ->andWhere('t.status != :statusstring')
45
            ->setParameter('statusstring', Translation::STATUS_DISABLED)
46
            ->setParameter('locale', $locale);
47
        if (!\is_null($domain) && !empty($domain)) {
48
            $qb->andWhere('t.domain = :tdomain')
49
                ->setParameter('tdomain', $domain);
50
        }
51
52
        return $qb->getQuery()->getResult();
53
    }
54
55
    /**
56
     * @return DateTime|null
57
     */
58
    public function getLastChangedTranslationDate()
59
    {
60
        $em = $this->getEntityManager();
61
62
        $flagNew = \Kunstmaan\TranslatorBundle\Entity\Translation::FLAG_NEW;
63
        $flagUpdated = \Kunstmaan\TranslatorBundle\Entity\Translation::FLAG_UPDATED;
64
65
        $sql = <<<EOQ
66
SELECT
67
    MAX(compare) as newestDate,
68
    flag
69
FROM (
70
    SELECT created_at as compare, flag FROM %s
71
    UNION ALL
72
    SELECT updated_at as compare, flag FROM %s) CACHE_CHECK
73
WHERE
74
    flag IN ('{$flagUpdated}','{$flagNew}')
75
    GROUP BY flag
76
    HAVING MAX(compare) IS NOT NULL
77
    ORDER BY newestDate DESC
78
EOQ;
79
        $table = $em->getClassMetaData('KunstmaanTranslatorBundle:Translation')->getTableName();
80
81
        $stmt = $em->getConnection()->prepare(sprintf($sql, $table, $table));
82
        $stmt->execute();
83
        $result = $stmt->fetch();
84
85
        if (is_array($result) && count($result) > 0) {
86
            return new \DateTime($result['newestDate']);
87
        }
88
89
        return null;
90
    }
91
92
    /**
93
     * @return mixed
94
     */
95
    public function resetAllFlags()
96
    {
97
        return $this->createQueryBuilder('t')
98
            ->update('KunstmaanTranslatorBundle:Translation', 't')
99
            ->set('t.flag', "NULL")
100
            ->getQuery()
101
            ->execute();
102
103
    }
104
105
    /**
106
     * @param $locales
107
     * @param $domains
108
     * @return mixed
109
     */
110
    public function getTranslationsByLocalesAndDomains($locales, $domains)
111
    {
112
        $em = $this->getEntityManager();
113
        $qb = $em->createQueryBuilder();
114
        $qb
115
            ->select('t')
116
            ->from('KunstmaanTranslatorBundle:Translation', 't')
117
            ->andWhere('t.status != :statusstring')
118
            ->setParameter('statusstring', Translation::STATUS_DISABLED)
119
            ->orderBy('t.domain', 'ASC')
120
            ->addOrderBy('t.keyword', 'ASC');
121
122
        if (count($locales) > 0) {
123
            $qb->andWhere($qb->expr()->in('t.locale', $locales));
124
        }
125
126
        if (count($domains) > 0) {
127
            $qb->andWhere($qb->expr()->in('t.domain', $domains));
128
        }
129
130
        $result = $qb
131
            ->getQuery()
132
            ->getResult();
133
134
        return $result;
135
    }
136
137
    /**
138
     * @param null $entity
139
     * @return mixed
140
     */
141
    public function flush($entity = null)
142
    {
143
        if ($entity !== null) {
144
            $this->persist($entity);
145
        }
146
147
        return $this->getEntityManager()->flush();
148
    }
149
150
    /**
151
     * @param $entity
152
     * @return mixed
153
     */
154
    public function persist($entity)
155
    {
156
        return $this->getEntityManager()->persist($entity);
157
    }
158
159
    /**
160
     * @param TranslationModel $translationModel
161
     * @return bool
162
     */
163
    public function isUnique(TranslationModel $translationModel)
164
    {
165
        $qb = $this->createQueryBuilder('t');
166
        $count = $qb->select('COUNT(t.id)')
167
            ->where('t.domain = :domain')
168
            ->andWhere('t.keyword = :keyword')
169
            ->setParameter('domain', $translationModel->getDomain())
170
            ->setParameter('keyword', $translationModel->getKeyword())
171
            ->getQuery()
172
            ->getSingleScalarResult();
173
174
        return $count == 0;
175
    }
176
177
    /**
178
     * @param TranslationModel $translationModel
179
     */
180
    public function createTranslations(TranslationModel $translationModel)
181
    {
182
        $this->getEntityManager()->beginTransaction();
183
        try {
184
            // Fetch new translation ID
185
            $translationId = $this->getUniqueTranslationId();
186
            /**
187
             * @var TextWithLocale $textWithLocale
188
             */
189
            foreach ($translationModel->getTexts() as $textWithLocale) {
190
                $text = $textWithLocale->getText();
191
                if (empty($text)) {
192
                    continue;
193
                }
194
195
                $translation = new Translation();
196
                $translation
197
                    ->setDomain($translationModel->getDomain())
198
                    ->setKeyword($translationModel->getKeyword())
199
                    ->setTranslationId($translationId)
200
                    ->setLocale($textWithLocale->getLocale())
201
                    ->setText($textWithLocale->getText());
202
                $this->getEntityManager()->persist($translation);
203
            }
204
            $this->getEntityManager()->commit();
205
        } catch (Exception $e) {
206
            $this->getEntityManager()->rollback();
207
        }
208
    }
209
210
    /**
211
     * @param TranslationModel $translationModel
212
     * @param                  $translationId
213
     */
214
    public function updateTranslations(TranslationModel $translationModel, $translationId)
215
    {
216
        $this->getEntityManager()->beginTransaction();
217
        try {
218
            /**
219
             * @var TextWithLocale $textWithLocale
220
             */
221
            foreach ($translationModel->getTexts() as $textWithLocale) {
222
                if ($textWithLocale->getId()) {
223
                    $translation = $this->find($textWithLocale->getId());
224
                    $translation->setLocale($textWithLocale->getLocale())
225
                        ->setText($textWithLocale->getText());
226
                    $this->getEntityManager()->persist($translation);
0 ignored issues
show
Bug introduced by
It seems like $translation defined by $this->find($textWithLocale->getId()) on line 223 can also be of type null; however, Doctrine\ORM\EntityManager::persist() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
227
                } else {
228
                    $text = $textWithLocale->getText();
229
                    if (empty($text)) {
230
                        continue;
231
                    }
232
233
                    $translation = new Translation();
234
                    $translation
235
                        ->setDomain($translationModel->getDomain())
236
                        ->setKeyword($translationModel->getKeyword())
237
                        ->setTranslationId($translationId)
238
                        ->setLocale($textWithLocale->getLocale())
239
                        ->setText($textWithLocale->getText());
240
                    $this->getEntityManager()->persist($translation);
241
                }
242
            }
243
            $this->getEntityManager()->commit();
244
        } catch (Exception $e) {
245
            $this->getEntityManager()->rollback();
246
        }
247
    }
248
249
    /**
250
     * Removes all translations with the given translation id
251
     *
252
     * @param string $translationId
253
     *
254
     * @return mixed
255
     */
256
    public function removeTranslations($translationId)
257
    {
258
        return $this->createQueryBuilder('t')
259
            ->delete()
260
            ->where('t.translationId = :translationId')
261
            ->setParameter('translationId', $translationId)
262
            ->getQuery()
263
            ->execute();
264
    }
265
266
    /**
267
     * @return int
0 ignored issues
show
Documentation introduced by
Should the return type not be object|integer|double|string|array|boolean? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
268
     */
269
    public function getUniqueTranslationId()
270
    {
271
        $qb = $this->createQueryBuilder('t');
272
        $newId = $qb->select('MAX(t.translationId)+1')
273
            ->getQuery()
274
            ->getSingleScalarResult();
275
        if (is_null($newId)) {
276
            $newId = 1;
277
        }
278
279
        return $newId;
280
    }
281
282
    /**
283
     * @param DateTime $date
284
     * @param string $domain
285
     * @return mixed
286
     */
287
    public function findDeprecatedTranslationsBeforeDate(DateTime $date, $domain)
288
    {
289
        $qb = $this->createQueryBuilder('t');
290
        $result = $qb->select('t')
291
            ->where('t.status = :status')
292
            ->andWhere('t.domain = :domain')
293
            ->andWhere('t.updatedAt < :date')
294
            ->setParameter('status', Translation::STATUS_DEPRECATED)
295
            ->setParameter('domain', $domain)
296
            ->setParameter('date', $date)
297
            ->getQuery()
298
            ->getResult();
299
300
        return $result;
301
    }
302
}
303