Completed
Push — master ( 8aaacb...83329d )
by Park Jong-Hun
02:44
created

ArrayUtils::find()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 7
nop 2
dl 0
loc 16
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Core\Utils;
4
5
use InvalidArgumentException;
6
7
class ArrayUtils
8
{
9
    /**
10
     * @param array $arr
11
     * @param $str
12
     * @return string|false return matching pattern
13
     */
14
    public static function find(array $arr, $str)
15
    {
16
        foreach ($arr as $key => $value) {
17
            $item = is_int($key) ? $value : $key;
18
19
            if(is_string($item) === false) {
20
                throw new InvalidArgumentException('Given array contain not string key');
21
            }
22
23
            if(self::isMatchedString($item, $str)) {
24
                return $item;
25
            }
26
        }
27
28
        return false;
29
    }
30
31
    private static function isMatchedString($str1, $str2) {
32
        $quotedStr1 = preg_quote($str1);
33
        $quotedStr2 = preg_quote($str2);
34
35
        $inspectStr1 = str_replace('\\*', '.*', $quotedStr1);
36
        $inspectStr2 = str_replace('\\*', '.*', $quotedStr2);
37
38
        return preg_match(sprintf('/^%s$/', $inspectStr1), $str2)
39
            || preg_match(sprintf('/^%s$/', $inspectStr2), $str1);
40
    }
41
}