FilesDataset::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Dataset;
6
7
use Phpml\Exception\DatasetException;
8
9
class FilesDataset extends ArrayDataset
10
{
11
    public function __construct(string $rootPath)
12
    {
13
        if (!is_dir($rootPath)) {
14
            throw new DatasetException(sprintf('Dataset root folder "%s" missing.', $rootPath));
15
        }
16
17
        $this->scanRootPath($rootPath);
18
    }
19
20
    private function scanRootPath(string $rootPath): void
21
    {
22
        $dirs = glob($rootPath.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
23
24
        if ($dirs === false) {
25
            throw new DatasetException(sprintf('An error occurred during directory "%s" scan', $rootPath));
26
        }
27
28
        foreach ($dirs as $dir) {
29
            $this->scanDir($dir);
30
        }
31
    }
32
33
    private function scanDir(string $dir): void
34
    {
35
        $target = basename($dir);
36
37
        $files = glob($dir.DIRECTORY_SEPARATOR.'*');
38
        if ($files === false) {
39
            return;
40
        }
41
42
        foreach (array_filter($files, 'is_file') as $file) {
43
            $this->samples[] = file_get_contents($file);
44
            $this->targets[] = $target;
45
        }
46
    }
47
}
48