Skip to content

Commit

Permalink
[testing] Added WithTempDirectory::getTempDirectory() helper.
Browse files Browse the repository at this point in the history
  • Loading branch information
LastDragon-ru committed May 15, 2021
1 parent d95339b commit c8990e9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Package/TestCase.php
Expand Up @@ -6,6 +6,7 @@
use LastDragon_ru\LaraASP\Testing\Assertions\Assertions;
use LastDragon_ru\LaraASP\Testing\Concerns\Concerns;
use LastDragon_ru\LaraASP\Testing\SetUpTraits;
use LastDragon_ru\LaraASP\Testing\Utils\WithTempDirectory;
use LastDragon_ru\LaraASP\Testing\Utils\WithTestData;
use Orchestra\Testbench\TestCase as TestbenchTestCase;

Expand All @@ -19,6 +20,7 @@ class TestCase extends TestbenchTestCase {
use Assertions;
use Concerns;
use WithTestData;
use WithTempDirectory;

public function getApplication(): Application {
return $this->app;
Expand Down
44 changes: 44 additions & 0 deletions src/Utils/WithTempDirectory.php
@@ -0,0 +1,44 @@
<?php declare(strict_types = 1);

namespace LastDragon_ru\LaraASP\Testing\Utils;

use LastDragon_ru\LaraASP\Migrator\Package;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

use function mkdir;
use function register_shutdown_function;
use function rmdir;
use function sys_get_temp_dir;
use function tempnam;
use function unlink;

trait WithTempDirectory {
protected function getTempDirectory(): string {
$pkg = Package::Name;
$path = tempnam(sys_get_temp_dir(), $pkg);

unlink($path);
mkdir($path);

register_shutdown_function(static function () use ($path): void {
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST,
);

foreach ($files as $file) {
/** @var \SplFileInfo $file */
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}

rmdir($path);
});

return $path;
}
}

0 comments on commit c8990e9

Please sign in to comment.