Completed
Push — master ( 92841c...9121c0 )
by Hannes
03:54
created

SourceFileIterator::getIterator()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 4
nop 0
1
<?php
2
3
namespace hanneskod\readmetester;
4
5
/**
6
 * Iterate over markdown formatted source files
7
 */
8
class SourceFileIterator implements \IteratorAggregate
9
{
10
    /**
11
     * @var string Source file or directory name
12
     */
13
    private $filename;
14
15
    public function __construct(string $filename)
16
    {
17
        $this->filename = $filename;
18
    }
19
20
    public function getIterator(): \Traversable
21
    {
22
        if (is_file($this->filename)) {
23
            yield basename($this->filename) => $this->readFile($this->filename);
24
            return;
25
        }
26
27
        foreach (new \DirectoryIterator($this->filename) as $fileInfo) {
28
            if (in_array(strtolower($fileInfo->getExtension()), ['md', 'mdown', 'markdown'])) {
29
                yield $fileInfo->getFilename() => $this->readFile($fileInfo->getRealPath());
30
            }
31
        }
32
    }
33
34
    private function readFile(string $filename): string
35
    {
36
        if (!is_file($filename) || !is_readable($filename)) {
37
            throw new \Exception("Not able to read $filename");
38
        }
39
40
        return file_get_contents($filename);
41
    }
42
}
43