Passed
Push — master ( 80875d...eb7214 )
by Alec
02:41
created

Calculator::computeErasingLength()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 8
c 0
b 0
f 0
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 10
cc 4
nc 5
nop 1
crap 4
1
<?php declare(strict_types=1);
2
3
namespace AlecRabbit\Spinner\Core;
4
5
use AlecRabbit\Spinner\Settings\Contracts\Defaults;
6
7
class Calculator
8
{
9 33
    public static function computeErasingLength(array $strings): int
10
    {
11 33
        if (empty($strings)) {
12 7
            return 0;
13
        }
14 30
        $lengths = [];
15 30
        foreach ($strings as $string) {
16 30
            $lengths[] = self::erasingLen($string);
17
        }
18 30
        if (1 !== count(array_unique($lengths))) {
19 1
            throw new \InvalidArgumentException('Strings have different erasing lengths');
20
        }
21 29
        return $lengths[0];
22
    }
23
24
25
    /**
26
     * @param null|string $in
27
     * @return int
28
     */
29 30
    protected static function erasingLen(?string $in): int
30
    {
31 30
        if (null === $in || Defaults::EMPTY_STRING === $in) {
32 3
            return 0;
33
        }
34 27
        $in = Strip::escCodes($in);
35 27
        $mbSymbolLen = mb_strlen($in);
36 27
        $oneCharLen = strlen($in) / $mbSymbolLen;
37 27
        if (4 === $oneCharLen) {
38 3
            return 2 * $mbSymbolLen;
39
        }
40 27
        return 1 * $mbSymbolLen;
41
    }
42
43
    /**
44
     * @param string $message
45
     * @param null|int $erasingLength
46
     * @return int
47
     */
48 24
    public static function refineErasingLen(string $message, ?int $erasingLength): int
49
    {
50 24
        if (null === $erasingLength) {
51 24
            return self::computeErasingLength([$message]);
52
        }
53 23
        return $erasingLength;
54
    }
55
}
56