Completed
Pull Request — master (#2026)
by Sander
22:59
created

findDeprecatedTranslationsBeforeDate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
cc 1
nc 1
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
        $result = $qb->select('t')
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
42
            ->where('t.locale = :locale')
43
            ->andWhere('t.status is null OR t.status != :statusstring')
44
            ->setParameter('statusstring', Translation::STATUS_DISABLED)
45
            ->setParameter('locale', $locale);
46
        if (!\is_null($domain) && !empty($domain)) {
47
            $qb->andWhere('t.domain = :tdomain')
48
                ->setParameter('tdomain', $domain);
49
        }
50
51
        return $qb->getQuery()->getResult();
52
    }
53
54
    /**
55
     * @return DateTime|null
56
     */
57
    public function getLastChangedTranslationDate()
58
    {
59
        $em = $this->getEntityManager();
60
61
        $flagNew = \Kunstmaan\TranslatorBundle\Entity\Translation::FLAG_NEW;
62
        $flagUpdated = \Kunstmaan\TranslatorBundle\Entity\Translation::FLAG_UPDATED;
63
64
        $sql = <<<EOQ
65
SELECT
66
    MAX(compare) as newestDate,
67
    flag
68
FROM (
69
    SELECT created_at as compare, flag FROM %s
70
    UNION ALL
71
    SELECT updated_at as compare, flag FROM %s) CACHE_CHECK
72
WHERE
73
    flag IN ('{$flagUpdated}','{$flagNew}')
74
    GROUP BY flag
75
    HAVING MAX(compare) IS NOT NULL
76
    ORDER BY newestDate DESC
77
EOQ;
78
        $table = $em->getClassMetaData('KunstmaanTranslatorBundle:Translation')->getTableName();
79
80
        $stmt = $em->getConnection()->prepare(sprintf($sql, $table, $table));
81
        $stmt->execute();
82
        $result = $stmt->fetch();
83
84
        if (is_array($result) && count($result) > 0) {
85
            return new \DateTime($result['newestDate']);
86
        }
87
88
        return null;
89
    }
90
91
    /**
92
     * @return mixed
93
     */
94
    public function resetAllFlags()
95
    {
96
        return $this->createQueryBuilder('t')
97
            ->update('KunstmaanTranslatorBundle:Translation', 't')
98
            ->set('t.flag', "NULL")
99
            ->getQuery()
100
            ->execute();
101
102
    }
103
104
    /**
105
     * @param $locales
106
     * @param $domains
107
     * @return mixed
108
     */
109
    public function getTranslationsByLocalesAndDomains($locales, $domains)
110
    {
111
        $em = $this->getEntityManager();
112
        $qb = $em->createQueryBuilder();
113
        $qb
114
            ->select('t')
115
            ->from('KunstmaanTranslatorBundle:Translation', 't')
116
            ->andWhere('t.status is null OR t.status != :statusstring')
117
            ->setParameter('statusstring', Translation::STATUS_DISABLED)
118
            ->orderBy('t.domain', 'ASC')
119
            ->addOrderBy('t.keyword', 'ASC');
120
121
        if (count($locales) > 0) {
122
            $qb->andWhere($qb->expr()->in('t.locale', $locales));
123
        }
124
125
        if (count($domains) > 0) {
126
            $qb->andWhere($qb->expr()->in('t.domain', $domains));
127
        }
128
129
        $result = $qb
130
            ->getQuery()
131
            ->getResult();
132
133
        return $result;
134
    }
135
136
    /**
137
     * @param null $entity
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
     * @return mixed
152
     */
153
    public function persist($entity)
154
    {
155
        return $this->getEntityManager()->persist($entity);
156
    }
157
158
    /**
159
     * @param TranslationModel $translationModel
160
     * @return bool
161
     */
162
    public function isUnique(TranslationModel $translationModel)
163
    {
164
        $qb = $this->createQueryBuilder('t');
165
        $count = $qb->select('COUNT(t.id)')
166
            ->where('t.domain = :domain')
167
            ->andWhere('t.keyword = :keyword')
168
            ->setParameter('domain', $translationModel->getDomain())
169
            ->setParameter('keyword', $translationModel->getKeyword())
170
            ->getQuery()
171
            ->getSingleScalarResult();
172
173
        return $count == 0;
174
    }
175
176
    /**
177
     * @param TranslationModel $translationModel
178
     */
179
    public function createTranslations(TranslationModel $translationModel)
180
    {
181
        $this->getEntityManager()->beginTransaction();
182
        try {
183
            // Fetch new translation ID
184
            $translationId = $this->getUniqueTranslationId();
185
            /**
186
             * @var TextWithLocale $textWithLocale
187
             */
188
            foreach ($translationModel->getTexts() as $textWithLocale) {
189
                $text = $textWithLocale->getText();
190
                if (empty($text)) {
191
                    continue;
192
                }
193
194
                $translation = new Translation();
195
                $translation
196
                    ->setDomain($translationModel->getDomain())
197
                    ->setKeyword($translationModel->getKeyword())
198
                    ->setTranslationId($translationId)
199
                    ->setLocale($textWithLocale->getLocale())
200
                    ->setText($textWithLocale->getText());
201
                $this->getEntityManager()->persist($translation);
202
            }
203
            $this->getEntityManager()->commit();
204
        } catch (Exception $e) {
205
            $this->getEntityManager()->rollback();
206
        }
207
    }
208
209
    /**
210
     * @param TranslationModel $translationModel
211
     * @param                  $translationId
212
     */
213
    public function updateTranslations(TranslationModel $translationModel, $translationId)
214
    {
215
        $this->getEntityManager()->beginTransaction();
216
        try {
217
            /**
218
             * @var TextWithLocale $textWithLocale
219
             */
220
            foreach ($translationModel->getTexts() as $textWithLocale) {
221
                if ($textWithLocale->getId()) {
222
                    $translation = $this->find($textWithLocale->getId());
223
                    $translation->setLocale($textWithLocale->getLocale())
224
                        ->setText($textWithLocale->getText());
225
                    $this->getEntityManager()->persist($translation);
0 ignored issues
show
Bug introduced by
It seems like $translation defined by $this->find($textWithLocale->getId()) on line 222 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...
226
                } else {
227
                    $text = $textWithLocale->getText();
228
                    if (empty($text)) {
229
                        continue;
230
                    }
231
232
                    $translation = new Translation();
233
                    $translation
234
                        ->setDomain($translationModel->getDomain())
235
                        ->setKeyword($translationModel->getKeyword())
236
                        ->setTranslationId($translationId)
237
                        ->setLocale($textWithLocale->getLocale())
238
                        ->setText($textWithLocale->getText());
239
                    $this->getEntityManager()->persist($translation);
240
                }
241
            }
242
            $this->getEntityManager()->commit();
243
        } catch (Exception $e) {
244
            $this->getEntityManager()->rollback();
245
        }
246
    }
247
248
    /**
249
     * Removes all translations with the given translation id
250
     *
251
     * @param string $translationId
252
     *
253
     * @return mixed
254
     */
255
    public function removeTranslations($translationId)
256
    {
257
        return $this->createQueryBuilder('t')
258
            ->delete()
259
            ->where('t.translationId = :translationId')
260
            ->setParameter('translationId', $translationId)
261
            ->getQuery()
262
            ->execute();
263
    }
264
265
    /**
266
     * @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...
267
     */
268
    public function getUniqueTranslationId()
269
    {
270
        $qb = $this->createQueryBuilder('t');
271
        $newId = $qb->select('MAX(t.translationId)+1')
272
            ->getQuery()
273
            ->getSingleScalarResult();
274
        if (is_null($newId)) {
275
            $newId = 1;
276
        }
277
278
        return $newId;
279
    }
280
281
    /**
282
     * @param DateTime $date
283
     * @param string $domain
284
     * @return mixed
285
     */
286
    public function findDeprecatedTranslationsBeforeDate(DateTime $date, string $domain)
287
    {
288
        $qb = $this->createQueryBuilder('t');
289
        $result = $qb->select('t')
290
            ->where('t.status = :status')
291
            ->andWhere('t.domain = :domain')
292
            ->andWhere('t.updatedAt < :date')
293
            ->setParameter('status', Translation::STATUS_DEPRECATED)
294
            ->setParameter('domain', $domain)
295
            ->setParameter('date', $date)
296
            ->getQuery()
297
            ->getResult();
298
299
        return $result;
300
    }
301
}
302