BinaryString   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 16
c 3
b 0
f 0
dl 0
loc 59
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A substring() 0 15 4
A length() 0 13 3
A constantTimeCompare() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Mdanter\Ecc\Util;
5
6
class BinaryString
7
{
8
    /**
9
     * Multi-byte-safe string length calculation
10
     *
11
     * @param string $str
12
     * @return int
13
     */
14
    public static function length(string $str): int
15
    {
16
        // Premature optimization: cache the function_exists() result
17
        static $exists = null;
18
        if ($exists === null) {
19
            $exists = function_exists('mb_strlen');
20
        }
21
22
        // If it exists, we need to make sure we're using 8bit mode
23
        if ($exists) {
24
            return mb_strlen($str, '8bit');
25
        }
26
        return strlen($str);
27
    }
28
29
    /**
30
     * Multi-byte-safe substring calculation
31
     *
32
     * @param string $str
33
     * @param int $start
34
     * @param int $length (optional)
35
     * @return string
36
     */
37
    public static function substring(string $str, int $start = 0, int $length = null): string
38
    {
39
        // Premature optimization: cache the function_exists() result
40
        static $exists = null;
41
        if ($exists === null) {
42
            $exists = function_exists('mb_substr');
43
        }
44
45
        // If it exists, we need to make sure we're using 8bit mode
46
        if ($exists) {
47
            return mb_substr($str, $start, $length, '8bit');
48
        } elseif ($length !== null) {
49
            return substr($str, $start, $length);
50
        }
51
        return substr($str, $start);
52
    }
53
    
54
    /**
55
     * Equivalent to hash_equals() in PHP 5.6
56
     *
57
     * @param string $knownString
58
     * @param string $userString
59
     *
60
     * @return bool
61
     */
62
    public static function constantTimeCompare(string $knownString, string $userString): bool
63
    {
64
        return hash_equals($knownString, $userString);
65
    }
66
}
67