Completed
Push — master ( a59df7...fcae40 )
by Derek
02:07
created

StringHelper::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
namespace Subreality\Dilmun\Anshar\Utils;
3
4
class StringHelper
5
{
6
    protected $string;
7
8
    /**
9
     * StringHelper constructor. Accepts and stores a string.
10
     *
11
     * @throws \InvalidArgumentException if not initialized with a string
12
     *
13
     * @param string $string    The string needing help
14
     */
15 11
    public function __construct($string)
16
    {
17 11
        if (!is_string($string)) {
18 6
            throw new \InvalidArgumentException("Supplied string is not a string");
19
        }
20
21 5
        $this->string = $string;
22 5
    }
23
24
    /**
25
     * Given a delimited string, returns a copy of the string with chunks defined by the delimiter affected by a given
26
     * function.
27
     *
28
     * @param callable $function    The function to be called against the delimited chunks
29
     * @param string[] $delimiters  One or more strings delimiting the chunks
0 ignored issues
show
Documentation introduced by
Should the type for parameter $delimiters not be string[][]?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
30
     *
31
     * @return string               A delimited string with chunks affected by the supplied function
32
     */
33 4
    public function affectChunks(callable $function, ...$delimiters)
34
    {
35 4
        $delimiter_string = "";
36 4
        $replace_callback = function ($matches) use ($function) {
37
38 3
            $callback_string = $function($matches[0]);
39
40 3
            return $callback_string;
41 4
        };
42
43 4
        foreach ($delimiters as $delimiter) {
44 4
            $delimiter_string .= preg_quote($delimiter, "/");
45 4
        }
46
47 4
        $pattern = "/[^{$delimiter_string}]+/";
48
49 4
        $affected_string = preg_replace_callback($pattern, $replace_callback, $this->string);
50
51 4
        return $affected_string;
52
    }
53
}
54