ClassLoader::load()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
/**
3
 * This program is free software. It comes without any warranty, to
4
 * the extent permitted by applicable law. You can redistribute it
5
 * and/or modify it under the terms of the Do What The Fuck You Want
6
 * To Public License, Version 2, as published by Sam Hocevar. See
7
 * http://www.wtfpl.net/ for more details.
8
 */
9
10
declare(strict_types = 1);
11
12
namespace hanneskod\classtools\Loader;
13
14
use hanneskod\classtools\Iterator\ClassIterator;
15
16
/**
17
 * Autoload classes from a ClassIterator classmap
18
 *
19
 * @author Hannes Forsgård <[email protected]>
20
 */
21
class ClassLoader
22
{
23
    /**
24
     * @var \hanneskod\classtools\Iterator\SplFileInfo[] Maps names to SplFileInfo objects
25
     */
26
    private $classMap = [];
27
28
    /**
29
     * Load classmap at construct
30
     */
31
    public function __construct(ClassIterator $classIterator, bool $register = true)
32
    {
33
        $this->classMap = $classIterator->getClassMap();
34
        if ($register) {
35
            $this->register();
36
        }
37
    }
38
39
    /**
40
     * Register autoloader
41
     */
42
    public function register(): bool
43
    {
44
        return spl_autoload_register([$this, 'load']);
45
    }
46
47
    /**
48
     * Unregister autoloader
49
     */
50
    public function unregister(): bool
51
    {
52
        return spl_autoload_unregister([$this, 'load']);
53
    }
54
55
    /**
56
     * Attempt to load class definition
57
     */
58
    public function load(string $classname): void
59
    {
60
        if (isset($this->classMap[$classname])) {
61
            require $this->classMap[$classname]->getRealPath();
62
        }
63
    }
64
}
65