1<?php
2/**
3 * Class to retrieve a filtered file list.
4 *
5 * @author    Juliette Reinders Folmer <phpcs_nospam@adviesenzo.nl>
6 * @copyright 2019 Juliette Reinders Folmer. All rights reserved.
7 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
8 */
9
10namespace PHP_CodeSniffer\Tests;
11
12class FileList
13{
14
15    /**
16     * The path to the project root directory.
17     *
18     * @var string
19     */
20    protected $rootPath;
21
22    /**
23     * Recursive directory iterator.
24     *
25     * @var \DirectoryIterator
26     */
27    public $fileIterator;
28
29    /**
30     * Base regex to use if no filter regex is provided.
31     *
32     * Matches based on:
33     * - File path starts with the project root (replacement done in constructor).
34     * - Don't match .git/ files.
35     * - Don't match dot files, i.e. "." or "..".
36     * - Don't match backup files.
37     * - Match everything else in a case-insensitive manner.
38     *
39     * @var string
40     */
41    private $baseRegex = '`^%s(?!\.git/)(?!(.*/)?\.+$)(?!.*\.(bak|orig)).*$`Dix';
42
43
44    /**
45     * Constructor.
46     *
47     * @param string $directory The directory to examine.
48     * @param string $rootPath  Path to the project root.
49     * @param string $filter    PCRE regular expression to filter the file list with.
50     */
51    public function __construct($directory, $rootPath='', $filter='')
52    {
53        $this->rootPath = $rootPath;
54
55        $directory = new \RecursiveDirectoryIterator(
56            $directory,
57            \RecursiveDirectoryIterator::UNIX_PATHS
58        );
59        $flattened = new \RecursiveIteratorIterator(
60            $directory,
61            \RecursiveIteratorIterator::LEAVES_ONLY,
62            \RecursiveIteratorIterator::CATCH_GET_CHILD
63        );
64
65        if ($filter === '') {
66            $filter = sprintf($this->baseRegex, preg_quote($this->rootPath));
67        }
68
69        $this->fileIterator = new \RegexIterator($flattened, $filter);
70
71        return $this;
72
73    }//end __construct()
74
75
76    /**
77     * Retrieve the filtered file list as an array.
78     *
79     * @return array
80     */
81    public function getList()
82    {
83        $fileList = [];
84
85        foreach ($this->fileIterator as $file) {
86            $fileList[] = str_replace($this->rootPath, '', $file);
87        }
88
89        return $fileList;
90
91    }//end getList()
92
93
94}//end class
95