xref: /web-bugs/tests/Unit/AutoloaderTest.php (revision f762db34)
1<?php declare(strict_types=1);
2
3namespace App\Tests\Unit;
4
5use App\Autoloader;
6use PHPUnit\Framework\TestCase;
7
8class MockAutoloader extends Autoloader
9{
10    protected $files = [];
11
12    public function setFiles(array $files)
13    {
14        $this->files = $files;
15    }
16
17    protected function requireFile($file)
18    {
19        return in_array($file, $this->files);
20    }
21}
22
23class AutoloaderTest extends TestCase
24{
25    /** @var MockAutoloader */
26    protected $autoloader;
27
28    protected function setUp(): void
29    {
30        $this->autoloader = new MockAutoloader;
31
32        $this->autoloader->setFiles([
33            '/vendor/foo.bar/src/ClassName.php',
34            '/vendor/foo.bar/src/DoomClassName.php',
35            '/vendor/foo.bar/tests/ClassNameTest.php',
36            '/vendor/foo.bardoom/src/ClassName.php',
37            '/vendor/foo.bar.baz.dib/src/ClassName.php',
38            '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php',
39            '/src/lib/ClassName.php',
40            '/src/libfoo/ClassFoo.php',
41        ]);
42
43        $this->autoloader->addNamespace(
44            'Foo\Bar',
45            '/vendor/foo.bar/src'
46        );
47
48        $this->autoloader->addNamespace(
49            'Foo\Bar',
50            '/vendor/foo.bar/tests'
51        );
52
53        $this->autoloader->addNamespace(
54            'Foo\\BarDoom',
55            '/vendor/foo.bardoom/src/'
56        );
57
58        $this->autoloader->addNamespace(
59            'Foo\Bar\Baz\Dib',
60            '/vendor/foo.bar.baz.dib/src/'
61        );
62
63        $this->autoloader->addNamespace(
64            'Foo\Bar\Baz\Dib\Zim\Gir',
65            '/vendor/foo.bar.baz.dib.zim.gir/src/'
66        );
67
68        $this->autoloader->addClassmap(
69            'ClassName',
70            '/src/lib/ClassName.php'
71        );
72
73        $this->autoloader->addClassmap(
74            'ClassFoo',
75            '/src/libfoo/ClassFoo.php'
76        );
77    }
78
79    /**
80     * @dataProvider classesProvider
81     */
82    public function testLoad(string $class, $expected): void
83    {
84        $this->assertEquals($expected, $this->autoloader->load($class));
85    }
86
87    public function classesProvider(): array
88    {
89        return [
90            ['Foo\Bar\ClassName', '/vendor/foo.bar/src/ClassName.php'],
91            ['Foo\Bar\ClassNameTest', '/vendor/foo.bar/tests/ClassNameTest.php'],
92            ['ClassName', '/src/lib/ClassName.php'],
93            ['ClassFoo', '/src/libfoo/ClassFoo.php'],
94            ['No_Vendor\No_Package\NoClass', false],
95            ['Foo\Bar\Baz\Dib\Zim\Gir\ClassName', '/vendor/foo.bar.baz.dib.zim.gir/src/ClassName.php'],
96            ['Foo\Bar\DoomClassName', '/vendor/foo.bar/src/DoomClassName.php'],
97            ['Foo\BarDoom\ClassName', '/vendor/foo.bardoom/src/ClassName.php'],
98        ];
99    }
100}
101