diff --git a/src/ScriptInjector.php b/src/ScriptInjector.php index 9f9e348e..b54f7ec0 100644 --- a/src/ScriptInjector.php +++ b/src/ScriptInjector.php @@ -118,7 +118,8 @@ public function __wakeup() $this->scriptDir, function () { $module = $this->scriptDir . self::MODULE; - return file_exists($module) ? \unserialize(\file_get_contents($module)) : new EmptyModule(); + + return \file_exists($module) ? \unserialize(\file_get_contents($module)) : new EmptyModule(); } ); } @@ -140,6 +141,17 @@ public function getInstance($interface, $name = Name::ANY) return $instance; } + public function clear() + { + $unlink = function ($path) use (&$unlink) { + foreach (\glob(\rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . '*') as $file) { + \is_dir($file) ? $unlink($file) : \unlink($file); + @\rmdir($file); + } + }; + $unlink($this->scriptDir); + } + public function isSingleton($dependencyIndex) : bool { $module = \unserialize(\file_get_contents($this->scriptDir . self::MODULE)); diff --git a/tests/ScriptInjectorTest.php b/tests/ScriptInjectorTest.php index ec61c354..7d18ce5a 100644 --- a/tests/ScriptInjectorTest.php +++ b/tests/ScriptInjectorTest.php @@ -229,4 +229,20 @@ function () { $result = $aop->returnSame(1); $this->assertSame(2, $result); } + + public function testClear() + { + $injector = new ScriptInjector( + $_ENV['TMP_DIR'], + function () { + return new FakeCarModule; + } + ); + $injector->getInstance(FakeCar::class); + $count = \count(\glob($_ENV['TMP_DIR'] . '/*')); + $this->assertGreaterThan(0, $count); + $injector->clear(); + $countAfterClear = \count(\glob($_ENV['TMP_DIR'] . '/*')); + $this->assertSame(0, $countAfterClear); + } }