Completed
Pull Request — master (#2775)
by Jeroen
10:25
created

TranslationRepository::getAllDomainsByLocale()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 7
cp 0
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 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
10
/**
11
 * Translator Repository class
12
 */
13
class TranslationRepository extends AbstractTranslatorRepository
14
{
15
    /**
16
     * Get an array of all domains group by locales
17
     *
18
     * @return array array[0] = ["name" => "messages", "locale" => "nl"]
19
     */
20
    public function getAllDomainsByLocale()
21
    {
22
        return $this->createQueryBuilder('t')
23
            ->select('t.locale, t.domain name')
24
            ->addGroupBy('t.locale')
25
            ->addGroupBy('t.domain')
26
            ->getQuery()
27
            ->getArrayResult();
28
    }
29
30
    /**
31
     * Get an array of all non disabled translations
32
     *
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
     *
36
     * @return array
37
     */
38
    public function findAllNotDisabled($locale, $domain = null)
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();
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\DBAL\Statement::fetch() has been deprecated with message: Use fetchNumeric(), fetchAssociative() or fetchOne() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
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
     * @param $locales
106
     * @param $domains
107
     *
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
        return $qb
131
            ->getQuery()
132
            ->getResult();
133
    }
134
135
    /**
136
     * @param null $entity
137
     *
138
     * @return mixed
139
     */
140
    public function flush($entity = null)
141
    {
142
        if ($entity !== null) {
143
            $this->persist($entity);
144
        }
145
146
        return $this->getEntityManager()->flush();
147
    }
148
149
    /**
150
     * @param $entity
151
     *
152
     * @return mixed
153
     */
154
    public function persist($entity)
155
    {
156
        return $this->getEntityManager()->persist($entity);
157
    }
158
159
    /**
160
     * @param TranslationModel $translationModel
161
     *
162
     * @return bool
163
     */
164
    public function isUnique(TranslationModel $translationModel)
165
    {
166
        $qb = $this->createQueryBuilder('t');
167
        $count = $qb->select('COUNT(t.id)')
168
            ->where('t.domain = :domain')
169
            ->andWhere('t.keyword = :keyword')
170
            ->setParameter('domain', $translationModel->getDomain())
171
            ->setParameter('keyword', $translationModel->getKeyword())
172
            ->getQuery()
173
            ->getSingleScalarResult();
174
175
        return $count == 0;
176
    }
177
178
    /**
179
     * @param TranslationModel $translationModel
180
     */
181
    public function createTranslations(TranslationModel $translationModel)
182
    {
183
        $this->getEntityManager()->beginTransaction();
184
185
        try {
186
            // Fetch new translation ID
187
            $translationId = $this->getUniqueTranslationId();
188
            /*
189
             * @var TextWithLocale
190
             */
191
            foreach ($translationModel->getTexts() as $textWithLocale) {
192
                $text = $textWithLocale->getText();
193
                if (empty($text)) {
194
                    continue;
195
                }
196
197
                $translation = new Translation();
198
                $translation
199
                    ->setDomain($translationModel->getDomain())
200
                    ->setKeyword($translationModel->getKeyword())
201
                    ->setTranslationId($translationId)
202
                    ->setLocale($textWithLocale->getLocale())
203
                    ->setText($textWithLocale->getText());
204
                $this->getEntityManager()->persist($translation);
205
            }
206
            $this->getEntityManager()->commit();
207
        } catch (Exception $e) {
208
            $this->getEntityManager()->rollback();
209
        }
210
    }
211
212
    /**
213
     * @param TranslationModel $translationModel
214
     * @param                  $translationId
215
     */
216
    public function updateTranslations(TranslationModel $translationModel, $translationId)
217
    {
218
        $this->getEntityManager()->beginTransaction();
219
220
        try {
221
            /*
222
             * @var TextWithLocale
223
             */
224
            foreach ($translationModel->getTexts() as $textWithLocale) {
225
                if ($textWithLocale->getId()) {
226
                    $translation = $this->find($textWithLocale->getId());
227
                    $translation->setLocale($textWithLocale->getLocale())
228
                        ->setText($textWithLocale->getText());
229
                    $this->getEntityManager()->persist($translation);
0 ignored issues
show
Bug introduced by
It seems like $translation defined by $this->find($textWithLocale->getId()) on line 226 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...
230
                } else {
231
                    $text = $textWithLocale->getText();
232
                    if (empty($text)) {
233
                        continue;
234
                    }
235
236
                    $translation = new Translation();
237
                    $translation
238
                        ->setDomain($translationModel->getDomain())
239
                        ->setKeyword($translationModel->getKeyword())
240
                        ->setTranslationId($translationId)
241
                        ->setLocale($textWithLocale->getLocale())
242
                        ->setText($textWithLocale->getText());
243
                    $this->getEntityManager()->persist($translation);
244
                }
245
            }
246
            $this->getEntityManager()->commit();
247
        } catch (Exception $e) {
248
            $this->getEntityManager()->rollback();
249
        }
250
    }
251
252
    /**
253
     * Removes all translations with the given translation id
254
     *
255
     * @param string $translationId
256
     *
257
     * @return mixed
258
     */
259
    public function removeTranslations($translationId)
260
    {
261
        return $this->createQueryBuilder('t')
262
            ->delete()
263
            ->where('t.translationId = :translationId')
264
            ->setParameter('translationId', $translationId)
265
            ->getQuery()
266
            ->execute();
267
    }
268
269
    /**
270
     * @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...
271
     */
272
    public function getUniqueTranslationId()
273
    {
274
        $qb = $this->createQueryBuilder('t');
275
        $newId = $qb->select('MAX(t.translationId)+1')
276
            ->getQuery()
277
            ->getSingleScalarResult();
278
        if (\is_null($newId)) {
279
            $newId = 1;
280
        }
281
282
        return $newId;
283
    }
284
285
    /**
286
     * @param DateTime $date
287
     * @param string   $domain
288
     *
289
     * @return mixed
290
     */
291
    public function findDeprecatedTranslationsBeforeDate(DateTime $date, $domain)
292
    {
293
        $qb = $this->createQueryBuilder('t');
294
        $result = $qb->select('t')
295
            ->where('t.status = :status')
296
            ->andWhere('t.domain = :domain')
297
            ->andWhere('t.updatedAt < :date')
298
            ->setParameter('status', Translation::STATUS_DEPRECATED)
299
            ->setParameter('domain', $domain)
300
            ->setParameter('date', $date)
301
            ->getQuery()
302
            ->getResult();
303
304
        return $result;
305
    }
306
}
307