CyrillicTransliterationTransformer   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 17
eloc 23
dl 0
loc 53
c 0
b 0
f 0
ccs 19
cts 19
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C transform() 0 48 17
1
<?php
2
3
declare(strict_types=1);
4
5
namespace kalanis\Pohoda\ValueTransformer;
6
7
/**
8
 * A transformer that rewrites Cyrillic script to its Latin alphabet equivalent.
9
 *
10
 * Note: This transformation is a phonetic representation and does not provide a translation of the text.
11
 */
12
final class CyrillicTransliterationTransformer implements ValueTransformerInterface
13
{
14
    /**
15
     * {@inheritdoc}
16
     */
17 4
    public function transform(string $value): string
18
    {
19 4
        $normalized = \Normalizer::normalize($value, \Normalizer::FORM_C);
20
21 4
        if (false === $normalized) {
22
            // @codeCoverageIgnoreStart
23
            // must do some error with Normalizer class
24
            return $value;
25
        }
26
        // @codeCoverageIgnoreEnd
27
28 4
        $transformer = \Transliterator::create('Any-Latin; Latin-ASCII');
29
30 4
        if (is_null($transformer)) {
31
            // @codeCoverageIgnoreStart
32
            // this can happen only if there is no latin encoding installed - not happen with Pohoda which need that
33
            return $value;
34
        }
35
        // @codeCoverageIgnoreEnd
36
37 4
        $chars = \preg_split('//u', $normalized, -1, PREG_SPLIT_NO_EMPTY);
38
39 4
        if (false === $chars) {
40
            // @codeCoverageIgnoreStart
41
            // can happen only when something in preg_split fails
42
            return $value;
43
        }
44
        // @codeCoverageIgnoreEnd
45
46 4
        $result = '';
47
48 4
        foreach ($chars as $char) {
49 4
            $codePoint = \mb_ord($char, 'UTF-8');
50
51 4
            if ((0x00400 <= $codePoint && 0x004FF >= $codePoint)    // Cyrillic Basic
52 4
                || (0x00500 <= $codePoint && 0x0052F >= $codePoint) // Cyrillic Supplement
53 4
                || (0x02DE0 <= $codePoint && 0x02DFF >= $codePoint) // Cyrillic Extended-A
54 4
                || (0x0A640 <= $codePoint && 0x0A69F >= $codePoint) // Cyrillic Extended-B
55 4
                || (0x01C80 <= $codePoint && 0x01C8F >= $codePoint) // Cyrillic Extended-C
56 4
                || (0x1E030 <= $codePoint && 0x1E08F >= $codePoint) // Cyrillic Extended-D
57
            ) {
58 1
                $result .= $transformer->transliterate($char);
59
            } else {
60 4
                $result .= $char;
61
            }
62
        }
63
64 4
        return $result;
65
    }
66
}
67