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