Finder   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 6
c 1
b 1
f 0
lcom 1
cbo 0
dl 0
loc 76
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B find() 0 28 5
1
<?php
2
3
/*
4
 * (c) Jean-François Lépine <https://twitter.com/Halleck45>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Hal\Component\File;
11
12
use RecursiveDirectoryIterator;
13
use RecursiveIteratorIterator;
14
use RegexIterator;
15
16
/**
17
 * File finder
18
 *
19
 * @author Jean-François Lépine <https://twitter.com/Halleck45>
20
 */
21
class Finder
22
{
23
24
    /**
25
     * Follow symlinks
26
     */
27
    const FOLLOW_SYMLINKS = RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
28
29
    /**
30
     * Extensions to match (regex)
31
     *
32
     * @var string
33
     */
34
    private $extensions;
35
36
    /**
37
     * Subdirectories to exclude (regex)
38
     *
39
     * @var string
40
     */
41
    private $excludedDirs;
42
43
    /**
44
     * Flags for RecursiveDirectoryIterator
45
     *
46
     * @var integer
47
     */
48
    private $flags;
49
50
    /**
51
     * @param string $extensions   regex of file extensions to include
52
     * @param string $excludedDirs regex of directories to exclude
53
     * @param integer $flags
54
     */
55
    public function __construct($extensions = 'php', $excludedDirs = '', $flags = null)
56
    {
57
        $this->extensions = (string) $extensions;
58
        $this->excludedDirs = (string) $excludedDirs;
59
        $this->flags = $flags;
60
    }
61
62
    /**
63
     * Find files in path
64
     *
65
     * @param string $path
66
     * @return array
67
     */
68
    public function find($path)
69
    {
70
        $files = array();
71
        if(is_dir($path)) {
72
            $path = rtrim($path, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
73
            $directory = new RecursiveDirectoryIterator($path, $this->flags);
74
            $iterator = new RecursiveIteratorIterator($directory);
75
76
            $filterRegex = sprintf(
77
                '`^%s%s$`',
78
                !empty($this->excludedDirs) ? '((?!'.$this->excludedDirs.').)+' : '.+',
79
                '\.(' . $this->extensions . ')'
80
            );
81
82
            $filteredIterator = new RegexIterator(
83
                $iterator,
84
                $filterRegex,
85
                \RecursiveRegexIterator::GET_MATCH
86
            );
87
88
            foreach($filteredIterator as $file) {
89
                $files[] = $file[0];
90
            }
91
        } elseif(is_file($path)) {
92
            $files = array($path);
93
        }
94
        return $files;
95
    }
96
}
97