Completed
Push — master ( d964e4...900267 )
by Jeroen
23:03 queued 15:42
created

TranslationRepository::removeTranslations()   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 1
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 3
    public function getAllDomainsByLocale()
21
    {
22 3
        return $this->createQueryBuilder('t')
23 3
            ->select('t.locale, t.domain name')
24 3
            ->addGroupBy('t.locale')
25 3
            ->addGroupBy('t.domain')
26 3
            ->getQuery()
27 3
            ->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 1
    public function findAllNotDisabled($locale, $domain = null)
39
    {
40 1
        $qb = $this->createQueryBuilder('t');
41
        $qb
42 1
            ->select('t')
43 1
            ->where('t.locale = :locale')
44 1
            ->andWhere('t.status != :statusstring')
45 1
            ->setParameter('statusstring', Translation::STATUS_DISABLED)
46 1
            ->setParameter('locale', $locale);
47 1
        if (!\is_null($domain) && !empty($domain)) {
48
            $qb->andWhere('t.domain = :tdomain')
49
                ->setParameter('tdomain', $domain);
50
        }
51
52 1
        return $qb->getQuery()->getResult();
53
    }
54
55
    /**
56
     * @return DateTime|null
57
     */
58 1
    public function getLastChangedTranslationDate()
59
    {
60 1
        $em = $this->getEntityManager();
61
62 1
        $flagNew = \Kunstmaan\TranslatorBundle\Entity\Translation::FLAG_NEW;
63 1
        $flagUpdated = \Kunstmaan\TranslatorBundle\Entity\Translation::FLAG_UPDATED;
64
65
        $sql = <<<EOQ
66 1
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 1
    flag IN ('{$flagUpdated}','{$flagNew}')
75
    GROUP BY flag
76
    HAVING MAX(compare) IS NOT NULL
77
    ORDER BY newestDate DESC
78
EOQ;
79 1
        $table = $em->getClassMetadata('KunstmaanTranslatorBundle:Translation')->getTableName();
80
81 1
        $stmt = $em->getConnection()->prepare(sprintf($sql, $table, $table));
82 1
        $stmt->execute();
83 1
        $result = $stmt->fetch();
84
85 1
        if (\is_array($result) && \count($result) > 0) {
86 1
            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 1
    public function getTranslationsByLocalesAndDomains($locales, $domains)
111
    {
112 1
        $em = $this->getEntityManager();
113 1
        $qb = $em->createQueryBuilder();
114
        $qb
115 1
            ->select('t')
116 1
            ->from('KunstmaanTranslatorBundle:Translation', 't')
117 1
            ->andWhere('t.status != :statusstring')
118 1
            ->setParameter('statusstring', Translation::STATUS_DISABLED)
119 1
            ->orderBy('t.domain', 'ASC')
120 1
            ->addOrderBy('t.keyword', 'ASC');
121
122 1
        if (\count($locales) > 0) {
123 1
            $qb->andWhere($qb->expr()->in('t.locale', $locales));
124
        }
125
126 1
        if (\count($domains) > 0) {
127 1
            $qb->andWhere($qb->expr()->in('t.domain', $domains));
128
        }
129
130
        return $qb
131 1
            ->getQuery()
132 1
            ->getResult();
133
    }
134
135
    /**
136
     * @param null $entity
137
     *
138
     * @return mixed
139
     */
140 3
    public function flush($entity = null)
141
    {
142 3
        if ($entity !== null) {
143
            $this->persist($entity);
144
        }
145
146 3
        return $this->getEntityManager()->flush();
147
    }
148
149
    /**
150
     * @param $entity
151
     *
152
     * @return mixed
153
     */
154 3
    public function persist($entity)
155
    {
156 3
        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 3
    public function getUniqueTranslationId()
273
    {
274 3
        $qb = $this->createQueryBuilder('t');
275 3
        $newId = $qb->select('MAX(t.translationId)+1')
276 3
            ->getQuery()
277 3
            ->getSingleScalarResult();
278 3
        if (\is_null($newId)) {
279 3
            $newId = 1;
280
        }
281
282 3
        return $newId;
283
    }
284
285
    /**
286
     * @param DateTime $date
287
     * @param string   $domain
288
     *
289
     * @return mixed
290
     */
291 1
    public function findDeprecatedTranslationsBeforeDate(DateTime $date, $domain)
292
    {
293 1
        $qb = $this->createQueryBuilder('t');
294 1
        $result = $qb->select('t')
295 1
            ->where('t.status = :status')
296 1
            ->andWhere('t.domain = :domain')
297 1
            ->andWhere('t.updatedAt < :date')
298 1
            ->setParameter('status', Translation::STATUS_DEPRECATED)
299 1
            ->setParameter('domain', $domain)
300 1
            ->setParameter('date', $date)
301 1
            ->getQuery()
302 1
            ->getResult();
303
304 1
        return $result;
305
    }
306
}
307