tigitz /
php-spellchecker
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace PhpSpellcheck\Source; |
||
| 6 | |||
| 7 | use PhpSpellcheck\Text; |
||
| 8 | |||
| 9 | class Directory implements SourceInterface |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @var string |
||
| 13 | */ |
||
| 14 | private $dirPath; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * @var null|string |
||
| 18 | */ |
||
| 19 | private $pattern; |
||
| 20 | |||
| 21 | 2 | public function __construct(string $dirPath, ?string $pattern = null) |
|
| 22 | { |
||
| 23 | 2 | $this->dirPath = $dirPath; |
|
| 24 | 2 | $this->pattern = $pattern; |
|
| 25 | 2 | } |
|
| 26 | |||
| 27 | /** |
||
| 28 | * @return Text[] |
||
| 29 | */ |
||
| 30 | 2 | public function getContents(): iterable |
|
| 31 | { |
||
| 32 | 2 | $filesInDir = new \RecursiveIteratorIterator( |
|
| 33 | 2 | new \RecursiveDirectoryIterator( |
|
| 34 | 2 | $this->dirPath, |
|
| 35 | 2 | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME |
|
| 36 | ), |
||
| 37 | \RecursiveIteratorIterator::SELF_FIRST |
||
| 38 | 2 | ); |
|
| 39 | 1 | ||
| 40 | if ($this->pattern) { |
||
| 41 | $filesInDir = new \RegexIterator($filesInDir, $this->pattern, \RegexIterator::GET_MATCH); |
||
| 42 | } |
||
| 43 | 2 | ||
| 44 | 2 | /** @var \SplFileInfo|string|array $file */ |
|
| 45 | 1 | foreach ($filesInDir as $file) { |
|
| 46 | 1 | if (is_string($file)) { |
|
| 47 | $file = new \SplFileInfo($file); |
||
| 48 | 1 | } elseif (is_array($file)) { |
|
| 49 | // When regex pattern is used, an array containing the file path in its first element is returned |
||
| 50 | $file = new \SplFileInfo(current($file)); |
||
| 51 | 2 | } |
|
| 52 | 2 | ||
| 53 | if (!$file->isDir()) { |
||
| 54 | if ($file->getRealPath() !== false) { |
||
| 55 | 2 | yield current((new File($file->getRealPath()))->toTexts()); |
|
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 56 | } |
||
| 57 | 2 | } |
|
| 58 | } |
||
| 59 | 2 | } |
|
| 60 | 2 | ||
| 61 | 2 | public function toTexts(array $context): iterable |
|
| 62 | 2 | { |
|
| 63 | 2 | foreach ($this->getContents() as $text) { |
|
| 64 | yield new Text( |
||
| 65 | $text->getContent(), |
||
| 66 | 2 | $text->getEncoding(), |
|
| 67 | array_merge($text->getContext(), $context) |
||
| 68 | ); |
||
| 69 | } |
||
| 70 | } |
||
| 71 | } |
||
| 72 |