Failed Conditions
Branch v2.x (0635cc)
by Arnold
09:26
created

file_functions.php ➔ fnmatch_extended()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 2
dl 0
loc 15
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
    $handle = fopen($filename, 'r');
15
    if (!$handle) return false;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
16
    
17
    $valid = false;
18
    
19
    $len = max(2 * strlen($str), 256);
20
    $prev = '';
21
    
22
    while (!feof($handle)) {
23
        $cur = fread($handle, $len);
24
        
25
        if (strpos($prev . $cur, $str) !== false) {
26
            $valid = true;
27
            break;
28
        }
29
        $prev = $cur;
30
    }
31
    
32
    fclose($handle);
33
    
34
    return $valid;
35
}
36
37
/**
38
 * Match path against an extended wildcard pattern.
39
 *
40
 * @param string $pattern
41
 * @param string $path
42
 * @return boolean
43
 */
44
function fnmatch_extended($pattern, $path)
45
{
46
    $quoted = preg_quote($pattern, '~');
47
    
48
    $step1 = strtr($quoted, ['\?' => '[^/]', '\*' => '[^/]*', '/\*\*' => '(?:/.*)?', '#' => '\d+', '\[' => '[',
49
        '\]' => ']', '\-' => '-', '\{' => '{', '\}' => '}']);
50
    
51
    $step2 = preg_replace_callback('~{[^}]+}~', function ($part) {
52
        return '(?:' . substr(strtr($part[0], ',', '|'), 1, -1) . ')';
53
    }, $step1);
54
    
55
    $regex = rawurldecode($step2);
56
57
    return (boolean)preg_match("~^{$regex}$~", $path);
58
}
59