Failed Conditions
Push — master ( 01d6ae...9ca6d9 )
by Philippe
534:14 queued 469:10
created

Directory::getContents()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 20
nop 0
dl 0
loc 26
rs 8.8333
c 0
b 0
f 0
ccs 15
cts 15
cp 1
crap 7
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
The expression yield current(new PhpSpe...RealPath())->toTexts()) returns the type Generator which is incompatible with the documented return type PhpSpellcheck\Text[].
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