summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Test/ClassLoader.php
blob: af90a7eacb2d0c6f77a2948decbac13d470fdb69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */

namespace Icinga\Test;

/**
 * PSR-4 class loader
 */
class ClassLoader
{
    /**
     * Namespace separator
     */
    const NAMESPACE_SEPARATOR = '\\';

    /**
     * Namespaces
     *
     * @var array
     */
    private $namespaces = array();

    /**
     * Register a base directory for a namespace prefix
     *
     * @param   string  $namespace
     * @param   string  $directory
     *
     * @return  $this
     */
    public function registerNamespace($namespace, $directory)
    {
        $this->namespaces[$namespace] = $directory;

        return $this;
    }

    /**
     * Test whether a namespace exists
     *
     * @param   string $namespace
     *
     * @return  bool
     */
    public function hasNamespace($namespace)
    {
        return array_key_exists($namespace, $this->namespaces);
    }

    /**
     * Get the source file of the given class or interface
     *
     * @param   string      $class Name of the class or interface
     *
     * @return  string|null
     */
    public function getSourceFile($class)
    {
        foreach ($this->namespaces as $namespace => $dir) {
            if ($class === strstr($class, $namespace)) {
                $classPath = str_replace(
                    self::NAMESPACE_SEPARATOR,
                    DIRECTORY_SEPARATOR,
                    substr($class, strlen($namespace))
                ) . '.php';
                if (file_exists($file = $dir . $classPath)) {
                    return $file;
                }
            }
        }
        return null;
    }

    /**
     * Load the given class or interface
     *
     * @param   string  $class  Name of the class or interface
     *
     * @return  bool            Whether the class or interface has been loaded
     */
    public function loadClass($class)
    {
        if ($file = $this->getSourceFile($class)) {
            require $file;
            return true;
        }
        return false;
    }

    /**
     * Register {@link loadClass()} as an autoloader
     */
    public function register()
    {
        spl_autoload_register(array($this, 'loadClass'));
    }

    /**
     * Unregister {@link loadClass()} as an autoloader
     */
    public function unregister()
    {
        spl_autoload_unregister(array($this, 'loadClass'));
    }

    /**
     * Unregister this as an autoloader
     */
    public function __destruct()
    {
        $this->unregister();
    }
}