Failed Conditions
Branch master (51f507)
by Arnold
05:21
created

file_functions.php ➔ fnmatch_extended()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 2
dl 0
loc 15
ccs 6
cts 6
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Jasny;
4
5
/**
6
 * Check if the file contains the specified string
7
 *
8
 * @string $filename
9
 * @string $str
10
 * @return boolean
11
 */
12
function file_contains($filename, $str)
13
{
14 2
    $handle = fopen($filename, 'r');
15
16 2
    if ($handle === false) {
17 1
        return false;
18
    }
19
    
20 1
    $valid = false;
21
    
22 1
    $len = max(2 * strlen($str), 256);
23 1
    $prev = '';
24
    
25 1
    while (!feof($handle)) {
26 1
        $cur = fread($handle, $len);
27
        
28 1
        if (strpos($prev . $cur, $str) !== false) {
29 1
            $valid = true;
30 1
            break;
31
        }
32 1
        $prev = $cur;
33
    }
34
    
35 1
    fclose($handle);
36
    
37 1
    return $valid;
38
}
39
40
/**
41
 * Match path against an extended wildcard pattern.
42
 *
43
 * @param string $pattern
44
 * @param string $path
45
 * @return boolean
46
 */
47
function fnmatch_extended($pattern, $path)
48
{
49 24
    $quoted = preg_quote($pattern, '~');
50
    
51 24
    $step1 = strtr($quoted, ['\?' => '[^/]', '\*' => '[^/]*', '/\*\*' => '(?:/.*)?', '#' => '\d+', '\[' => '[',
52
        '\]' => ']', '\-' => '-', '\{' => '{', '\}' => '}']);
53
    
54
    $step2 = preg_replace_callback('~{[^}]+}~', function ($part) {
55 4
        return '(?:' . substr(strtr($part[0], ',', '|'), 1, -1) . ')';
56 24
    }, $step1);
57
    
58 24
    $regex = rawurldecode($step2);
59
60 24
    return (boolean)preg_match("~^{$regex}$~", $path);
61
}
62
63