1
0
mirror of https://github.com/halaxa/json-machine.git synced 2025-01-17 13:08:16 +01:00

Tests for autoload.php

This commit is contained in:
Filip Halaxa 2022-02-12 15:28:42 +01:00
parent 6fc8f8f14a
commit ace39a082d
3 changed files with 60 additions and 3 deletions

1
.gitignore vendored
View File

@ -5,3 +5,4 @@ composer.lock
phpunit.xml
.php-cs-fixer.php
clover.xml
src/AutoloadStub.php

View File

@ -6,7 +6,7 @@ declare(strict_types=1);
*
* To use this just include this file in your script and the JsonMachine namespace will be made available
*
* i.e. require_once('/path/to/json-machine/Autoloader.php');
* Usage: spl_autoload_register(require_once('/path/to/Autoloader.php'));
*
* See: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md
*
@ -14,7 +14,8 @@ declare(strict_types=1);
*
* @return void
*/
spl_autoload_register(function ($class) {
return function ($class) {
// project-specific namespace prefix
$prefix = 'JsonMachine\\';
@ -40,4 +41,4 @@ spl_autoload_register(function ($class) {
if (file_exists($file)) {
require $file;
}
});
};

View File

@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace JsonMachineTest;
/**
* @covers \JsonMachine\FileChunks
*/
class autoloaderTest extends \PHPUnit_Framework_TestCase
{
public function testAutoloaderLoadsClass()
{
$dummyFile = $this->createAutoloadableClass();
$autoloadersBackup = $this->unregisterCurrentAutoloaders();
$autoloader = require __DIR__.'/../../autoloader.php';
spl_autoload_register($autoloader);
$autoloaded = class_exists('JsonMachine\\AutoloadStub');
spl_autoload_unregister($autoloader);
$this->registerPreviousAutoloaders($autoloadersBackup);
$this->assertTrue($autoloaded);
@unlink($dummyFile);
}
private function createAutoloadableClass(): string
{
$dummyFile = __DIR__.'/../../src/AutoloadStub.php';
file_put_contents($dummyFile, '<?php namespace JsonMachine; class AutoloadStub {}');
return $dummyFile;
}
private function unregisterCurrentAutoloaders(): array
{
$autoloadersBackup = [];
foreach (spl_autoload_functions() as $autoloader) {
$autoloadersBackup[] = $autoloader;
spl_autoload_unregister($autoloader);
}
return $autoloadersBackup;
}
private function registerPreviousAutoloaders(array $autoloadersBackup)
{
foreach ($autoloadersBackup as $restoreAutoloader) {
spl_autoload_register($restoreAutoloader);
}
}
}