Completed
Branch master (f8a0b6)
by Arnold
06:06
created

file_functions.php ➔ file_contains()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4
Metric Value
cc 4
eloc 14
nc 4
nop 2
dl 0
loc 24
ccs 14
cts 14
cp 1
crap 4
rs 8.6845
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 1
    $handle = fopen($filename, 'r');
15 1
    if (!$handle) return false;
16
    
17 1
    $valid = false;
18
    
19 1
    $len = max(2 * strlen($str), 256);
20 1
    $prev = '';
21
    
22 1
    while (!feof($handle)) {
23 1
        $cur = fread($handle, $len);
24
        
25 1
        if (strpos($prev . $cur, $str) !== false) {
26 1
            $valid = true;
27 1
            break;
28
        }
29 1
        $prev = $cur;
30 1
    }
31
    
32 1
    fclose($handle);
33
    
34 1
    return $valid;
35
}
36
37
/**
38
 * Match path against wildcard pattern.
39
 *
40
 * @param string $pattern
41
 * @param string $path
42
 * @return boolean
43
 */
44
function fnmatch($pattern, $path)
45
{
46 1
    $quoted = preg_quote($pattern, '~');
47
    
48 1
    $step1 = strtr($quoted, ['\?' => '[^/]', '\*' => '[^/]*', '/\*\*' => '(?:/.*)?', '#' => '\d+', '\[' => '[',
49 1
        '\]' => ']', '\-' => '-', '\{' => '{', '\}' => '}']);
50
    
51
    $step2 = preg_replace_callback('~{[^}]+}~', function ($part) {
52 1
        return '(?:' . substr(strtr($part[0], ',', '|'), 1, -1) . ')';
53 1
    }, $step1);
54
    
55 1
    $regex = rawurldecode($step2);
56
57 1
    return (boolean)preg_match("~^{$regex}$~", $path);
58
}
59