Skip to content

Instantly share code, notes, and snippets.

@MrPunyapal
Last active November 13, 2024 01:53
Show Gist options
  • Save MrPunyapal/79ac245dfba18e4724ce807797df6c8c to your computer and use it in GitHub Desktop.
Save MrPunyapal/79ac245dfba18e4724ce807797df6c8c to your computer and use it in GitHub Desktop.
Artisan Command for Generating Test Files in Laravel
<?php
Artisan::command('generate-tests', function () {
// Define the base path where class files are located
$files = File::allFiles(base_path('app/Classes'));
foreach ($files as $file) {
// Get the relative path of the current class file and apply string manipulations
$path = str($file->getRelativePathname())
->replace('.php', '') // Remove the .php extension
->replace('/', '\\') // Replace directory slashes with namespace slashes
->prepend(base_path('tests/Classes/')) // Prepend the test directory path
->append('Test.php'); // Append 'Test.php' to the path
// Ensure the directory for the test file exists
File::ensureDirectoryExists(dirname($path));
// Skip file creation if the test file already exists
if (File::exists($path)) {
continue;
}
// Define the content for the new test file
$content = "<?php" . PHP_EOL . PHP_EOL . "declare(strict_types=1);" . PHP_EOL . PHP_EOL;
// Create the test file with the specified content
File::put($path, $content);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment