1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of Cecil. |
5
|
|
|
* |
6
|
|
|
* (c) Arnaud Ligny <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Cecil\Command\ShowContent; |
15
|
|
|
|
16
|
|
|
use RecursiveFilterIterator; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* FileExtensionFilter class. |
20
|
|
|
* |
21
|
|
|
* This class extends RecursiveFilterIterator to filter files based on their extensions. |
22
|
|
|
* It allows only files with specified extensions (default: 'md' and 'yml') to be accepted, |
23
|
|
|
* while excluding certain directories (like '.git', '.cecil', '.cache', '_site', 'vendor', 'node_modules'). |
24
|
|
|
* It can be used to traverse a directory structure and filter out unwanted files and directories. |
25
|
|
|
*/ |
26
|
|
|
class FileExtensionFilter extends RecursiveFilterIterator |
27
|
|
|
{ |
28
|
|
|
/** @var array */ |
29
|
|
|
protected $allowedExt = ['md', 'yml']; |
30
|
|
|
|
31
|
|
|
/** @var array */ |
32
|
|
|
protected $excludedDir = ['.git', '.cecil', '.cache', '_site', 'vendor', 'node_modules']; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param \RecursiveIterator $iterator |
36
|
|
|
* @param string|array|null $extensions |
37
|
|
|
*/ |
38
|
|
|
public function __construct(\RecursiveIterator $iterator, $extensions = null) |
39
|
|
|
{ |
40
|
|
|
if (!\is_null($extensions)) { |
41
|
|
|
if (!\is_array($extensions)) { |
42
|
|
|
$extensions = [$extensions]; |
43
|
|
|
} |
44
|
|
|
$this->allowedExt = $extensions; |
45
|
|
|
} |
46
|
|
|
parent::__construct($iterator); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Get children with allowed extensions. |
51
|
|
|
*/ |
52
|
|
|
public function getChildren(): ?RecursiveFilterIterator |
53
|
|
|
{ |
54
|
|
|
return new self($this->getInnerIterator()->/** @scrutinizer ignore-call */getChildren(), $this->allowedExt); // @phpstan-ignore-line |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Valid file with allowed extensions. |
59
|
|
|
*/ |
60
|
|
|
public function accept(): bool |
61
|
|
|
{ |
62
|
|
|
/** @var \SplFileInfo $file */ |
63
|
|
|
$file = $this->current(); |
64
|
|
|
if ($file->isFile()) { |
65
|
|
|
return \in_array($file->getExtension(), $this->allowedExt); |
66
|
|
|
} |
67
|
|
|
if ($file->isDir()) { |
68
|
|
|
return !\in_array($file->getBasename(), $this->excludedDir); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return true; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|