Passed
Push — master ( 0c19f1...8279ff )
by Ondřej
06:33
created

StringUtils   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 97
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 14
lcom 0
cbo 0
dl 0
loc 97
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A pregReplaceCallbackWithOffset() 0 18 3
B pregReplaceCallbackWithOffsetImpl() 0 26 4
A englishOrd() 0 13 4
A randomHexString() 0 13 3
1
<?php
2
declare(strict_types=1);
3
namespace Ivory\Utils;
4
5
class StringUtils
6
{
7
    /**
8
     * Like {@link preg_replace_callback()}, it performs a string search and replace. The callback does not receive
9
     * plain array of matches, but an extended array: each item is a pair of the matching portion of the needle and the
10
     * byte offset to the subject, like {@link preg_match_all()} does with the `PREG_OFFSET_CAPTURE` flag.
11
     *
12
     * @param string $pattern
13
     * @param callable $callback
14
     * @param string|string[] $subject
15
     * @param int $limit
16
     * @param int|null $count
17
     * @return string|string[] depending on whether <tt>$subject</tt> is <tt>string</tt> or <tt>array</tt>,
0 ignored issues
show
Documentation introduced by
Should the return type not be array|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
18
     *                           a <tt>string</tt> or <tt>array</tt> is returned
19
     */
20
    public static function pregReplaceCallbackWithOffset(
21
        string $pattern,
22
        callable $callback,
23
        $subject,
24
        int $limit = -1,
25
        int &$count = null
26
    )
27
    {
28
        if (is_array($subject)) {
29
            $result = [];
30
            foreach ($subject as $item) {
31
                $result[] = self::pregReplaceCallbackWithOffsetImpl($pattern, $callback, $item, $limit, $count);
32
            }
33
            return $result;
34
        } else {
35
            return self::pregReplaceCallbackWithOffsetImpl($pattern, $callback, $subject, $limit, $count);
36
        }
37
    }
38
39
    private static function pregReplaceCallbackWithOffsetImpl(
40
        string $pattern,
41
        callable $callback,
42
        string $subject,
43
        int $limit = -1,
44
        int &$count = null
45
    ): string
46
    {
47
        $count = 0;
48
49
        $curOffset = 0;
50
        $result = '';
51
        preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
52
        foreach ($matches as $i => $match) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
53
            if ($limit >= 0 && $i >= $limit) {
54
                break;
55
            }
56
57
            $result .= substr($subject, $curOffset, $match[0][1] - $curOffset) . $callback($match);
58
            $curOffset = $match[0][1] + strlen($match[0][0]);
59
            $count++;
60
        }
61
        $result .= substr($subject, $curOffset);
62
63
        return $result;
64
    }
65
66
    /**
67
     * @param int $num
68
     * @return string "1st", "2nd", "3rd", "4th", etc. according to <tt>$num</tt>
69
     */
70
    public static function englishOrd(int $num): string
71
    {
72
        switch ($num) {
73
            case 1:
74
                return '1st';
75
            case 2:
76
                return '2nd';
77
            case 3:
78
                return '3rd';
79
            default:
80
                return $num . 'th';
81
        }
82
    }
83
84
    /**
85
     * @param int $len
86
     * @return string a pseudo-random string of hexadecimal digits
87
     */
88
    public static function randomHexString(int $len): string
89
    {
90
        if ($len < 0) {
91
            throw new \DomainException('$len is negative');
92
        }
93
94
        $result = '';
95
        for ($i = 0; $i < $len; $i += strlen($s)) {
96
            $s = dechex(mt_rand());
97
            $result .= substr($s, 0, $len - $i);
98
        }
99
        return $result;
100
    }
101
}
102