XliffVersionDetector::resolveVersion()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Matecat\XliffParser\XliffUtils;
4
5
use Matecat\XliffParser\Exception\NotSupportedVersionException;
6
use Matecat\XliffParser\Exception\NotValidFileException;
7
8
class XliffVersionDetector {
9
    /**
10
     * @var array
11
     */
12
    private static array $versions_1 = [ '1.0', '1.1', '1.2' ];
13
14
    /**
15
     * @var array
16
     */
17
    private static array $versions_2 = [ '2.0', '2.1' ];
18
19
    /**
20
     * @param string $xliffContent
21
     *
22
     * @return int
23
     * @throws NotSupportedVersionException
24
     * @throws NotValidFileException
25
     */
26
    public static function detect( string $xliffContent ): int {
27
        preg_match( '|<xliff.*?\sversion\s?=\s?["\'](.*?)["\']|si', substr( $xliffContent, 0, 1000 ), $versionMatches );
28
29
        if ( empty( $versionMatches ) ) {
30
            throw new NotValidFileException( 'This is not a valid xliff file' );
31
        }
32
33
        $version = $versionMatches[ 1 ];
34
35
        return self::resolveVersion( $version );
36
    }
37
38
    /**
39
     * @param string $version
40
     *
41
     * @return int
42
     * @throws NotSupportedVersionException
43
     */
44
    private static function resolveVersion( string $version ): int {
45
        if ( in_array( $version, self::$versions_1 ) ) {
46
            return 1;
47
        }
48
49
        if ( in_array( $version, self::$versions_2 ) ) {
50
            return 2;
51
        }
52
53
        throw new NotSupportedVersionException( 'Not supported version' );
54
    }
55
}
56