Completed
Pull Request — master (#89)
by
unknown
65:00
created

TranslationChecker::check()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
rs 5.3846
cc 8
eloc 21
nc 12
nop 2
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 Symfony\Component\Translation\Interval;
15
use Symfony\Component\Translation\PluralizationRules;
16
17
/**
18
 * Class used to check if plural translation is valid.
19
 */
20
class TranslationChecker
21
{
22
    /**
23
     * Checks if translation is valid.
24
     *
25
     * @param string $message Message to check.
26
     * @param string $locale  Locale used for.
27
     *
28
     * @return bool
29
     */
30
    public static function check($message, $locale)
31
    {
32
        $parts = explode('|', $message);
33
        $explicitRules = [];
34
        $standardRules = [];
35
        foreach ($parts as $part) {
36
            $part = trim($part);
37
38
            if (preg_match(
39
                '/^(?P<interval>' . Interval::getIntervalRegexp() . ')\s*(?P<message> . *?)$/x',
40
                $part,
41
                $matches
42
            )) {
43
                $explicitRules[$matches['interval']] = $matches['message'];
44
            } elseif (preg_match('/^\w+\:\s*(.*?)$/', $part, $matches)) {
45
                $standardRules[] = $matches[1];
46
            } else {
47
                $standardRules[] = $part;
48
            }
49
        }
50
51
        if (count($parts) !== 1 && count($parts) !== count($explicitRules)) {
52
            for ($count = 0; $count < 200; $count++) {
53
                $position = PluralizationRules::get($count, $locale);
54
55
                if (!isset($standardRules[$position])) {
56
                    return false;
57
                }
58
            }
59
        }
60
61
        return true;
62
    }
63
}
64