Passed
Push — master ( a93e2d...567501 )
by Philippe
03:03
created

TextEncoding::detect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpSpellcheck\Utils;
6
7
use PhpSpellcheck\Exception\RuntimeException;
8
9
/**
10
 * Manage different text encoding behavior
11
 *
12
 * @TODO This class is meant to be an enum implementing the list of the most common character encodings
13
 * @see https://stackoverflow.com/a/8528866
14
 */
15
class TextEncoding
16
{
17
    public const UTF8 = 'UTF-8';
18
    public const ASCII = 'ASCII';
19
20
    public static function detect(string $string): string
21
    {
22
        $encoding = mb_detect_encoding($string, null, true);
23
24
        if ($encoding === false) {
25
            throw new RuntimeException(
26
                \Safe\sprintf(
27
                    'Coulnd\'t detect encoding of string:' . PHP_EOL . '%s',
28
                    $string
29
                )
30
            );
31
        }
32
33
        return $encoding;
34
    }
35
}
36