Changeset View
Changeset View
Standalone View
Standalone View
src/app/Console/Commands/ObjectListCommand.php
- This file was added.
<?php | |||||
namespace App\Console\Commands; | |||||
use App\Console\Command; | |||||
use Illuminate\Database\Eloquent\SoftDeletes; | |||||
abstract class ObjectListCommand extends Command | |||||
{ | |||||
/** | |||||
* The name and signature of the console command. | |||||
* | |||||
* @var string | |||||
*/ | |||||
protected $signature; | |||||
/** | |||||
* The console command description. | |||||
* | |||||
* @var string | |||||
*/ | |||||
protected $description; | |||||
protected $objectClass; | |||||
protected $objectName; | |||||
protected $objectTitle; | |||||
public function __construct() | |||||
{ | |||||
$this->description = "List {$this->objectName}s"; | |||||
$classes = class_uses_recursive($this->objectClass); | |||||
if (in_array(SoftDeletes::class, $classes)) { | |||||
$this->signature = sprintf( | |||||
"%ss {--with-deleted : Include deleted %ss}", | |||||
$this->objectName, | |||||
$this->objectName | |||||
); | |||||
} else { | |||||
$this->signature = "{$this->objectName}s"; | |||||
} | |||||
parent::__construct(); | |||||
} | |||||
/** | |||||
* Execute the console command. | |||||
* | |||||
* @return mixed | |||||
*/ | |||||
public function handle() | |||||
{ | |||||
$classes = class_uses_recursive($this->objectClass); | |||||
if (in_array(SoftDeletes::class, $classes) && $this->option('with-deleted')) { | |||||
$objects = $this->objectClass::withTrashed(); | |||||
} else { | |||||
$objects = new $this->objectClass(); | |||||
} | |||||
$objects->each( | |||||
function ($object) { | |||||
if (!empty($this->objectTitle)) { | |||||
$title = $object->{$this->objectTitle}; | |||||
} else { | |||||
$title = $object->{$object->getKeyName()}; | |||||
} | |||||
if ($object->deleted_at) { | |||||
$this->info("{$title} (deleted at {$object->deleted_at}"); | |||||
} else { | |||||
$this->info("{$title}"); | |||||
} | |||||
} | |||||
); | |||||
} | |||||
} |