Skip to content

Instantly share code, notes, and snippets.

@normykinz
Last active March 7, 2023 14:52
Show Gist options
  • Save normykinz/727dd979ffddc778c313a18eb7784513 to your computer and use it in GitHub Desktop.
Save normykinz/727dd979ffddc778c313a18eb7784513 to your computer and use it in GitHub Desktop.
Lavel Typed Collection Make Command
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class CollectionCommand extends Command
{
protected $signature = 'make:collection {model}';
protected $description = 'Creates a typed collection (extends Gamez\Illuminate\Support\TypedCollection)';
public function __construct(protected Filesystem $files)
{
parent::__construct();
}
public function handle(): void
{
$path = $this->getSourceFilePath();
$this->makeDirectory(dirname($path));
$contents = $this->getSourceFile();
if (!$this->files->exists($path)) {
$this->files->put($path, $contents);
$this->info("File : {$path} created");
} else {
$this->info("File : {$path} already exits");
}
}
public function getSourceFilePath()
{
return base_path('App\\Collections') . '\\' . $this->argument('model') . 'Collection.php';
}
public function getStubPath()
{
return __DIR__ . '\stubs\collection.stub';
}
public function getStubVariables()
{
return [
'MODEL' => $this->argument('model'),
];
}
public function getStubContents($stub, $stubVariables = [])
{
$contents = file_get_contents($stub);
foreach ($stubVariables as $search => $replace) {
$contents = str_replace('$' . $search . '$', $replace, $contents);
}
return $contents;
}
public function getSourceFile()
{
return $this->getStubContents($this->getStubPath(), $this->getStubVariables());
}
protected function makeDirectory($path)
{
if (!$this->files->isDirectory($path)) {
$this->files->makeDirectory($path, 0777, true, true);
}
return $path;
}
}
<?php
namespace App\Collections;
use App\Models\$MODEL$;
use Gamez\Illuminate\Support\TypedCollection;
class $MODEL$Collection extends TypedCollection
{
protected static $allowedTypes = [$MODEL$::class];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment