FileLoader   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 2 Features 0
Metric Value
eloc 12
c 3
b 2
f 0
dl 0
loc 32
ccs 8
cts 8
cp 1
rs 10
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A checkAndLoad() 0 25 5
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * neuralyzer : Data Anonymization Library and CLI Tool
7
 *
8
 * PHP Version 7.2
9
 *
10
 * @author    Emmanuel Dyan
11
 *
12
 * @copyright 2020 Emmanuel Dyan
13
 *
14
 * @package edyan/neuralyzer
15
 *
16
 * @license GNU General Public License v2.0
17
 *
18
 * @link https://github.com/edyan/neuralyzer
19
 */
20
21
namespace Edyan\Neuralyzer\Utils;
22
23
/**
24
 * Class FileLoader
25
 *
26
 * @package edyan/neuralyzer
27
 */
28
class FileLoader
29
{
30
    /**
31
     * Checks if a PHP source file is readable and loads it.
32
     *
33
     * @throws \Exception
34 2
     */
35
    public static function checkAndLoad(string $filename): string
36 2
    {
37
        $includePathFilename = \stream_resolve_include_path($filename);
38
        // As a fallback, PHP looks in the directory of the file executing the
39
        // stream_resolve_include_path function.
40
        //
41
        // We don't want to load the Test.php file here, so skip it if it found that.
42 2
        // PHP prioritizes the include_path setting, so if the current directory is in there,
43
        // it will first look in the current working directory.
44 2
        $localFile = __DIR__ . DIRECTORY_SEPARATOR . $filename;
45
46 2
        $isReadable = true;
47 1
        try {
48
            \fopen($includePathFilename, 'r') !== false;
49
        } catch (\TypeError $e) {
50 1
            $isReadable = false;
51
        }
52 1
53
        if (! $includePathFilename || ! $isReadable || $includePathFilename === $localFile) {
54
            throw new \Exception(\sprintf('Cannot open file "%s".' . "\n", $filename));
55
        }
56
57
        require_once $includePathFilename;
58
59
        return $includePathFilename;
60
    }
61
}
62