Changeset View
Changeset View
Standalone View
Standalone View
src/app/Console/Commands/ObjectRelationListCommand.php
- This file was added.
<?php | |||||
namespace App\Console\Commands; | |||||
use App\Console\Command; | |||||
use Illuminate\Database\Eloquent\SoftDeletes; | |||||
abstract class ObjectRelationListCommand 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 $objectRelation; | |||||
protected $objectTitle; | |||||
public function __construct() | |||||
{ | |||||
$this->description = "List {$this->objectRelation} for a {$this->objectName}"; | |||||
$this->signature = sprintf( | |||||
"%s:%s {%s}", | |||||
$this->objectName, | |||||
$this->objectRelation, | |||||
$this->objectName | |||||
); | |||||
parent::__construct(); | |||||
} | |||||
/** | |||||
* Execute the console command. | |||||
* | |||||
* @return mixed | |||||
*/ | |||||
public function handle() | |||||
{ | |||||
$argument = $this->argument($this->objectName); | |||||
$object = $this->getObject( | |||||
$this->objectClass, | |||||
$argument, | |||||
$this->objectTitle | |||||
); | |||||
if (!$object) { | |||||
$this->error("No such {$this->objectName} {$argument}"); | |||||
return 1; | |||||
} | |||||
if (method_exists($object, $this->objectRelation)) { | |||||
$result = call_user_func([$object, $this->objectRelation]); | |||||
} elseif (property_exists($object, $this->objectRelation)) { | |||||
$result = $object->{"{$this->objectRelation}"}; | |||||
} else { | |||||
$this->error("No such relation {$this->objectRelation}"); | |||||
return 1; | |||||
} | |||||
if ($result instanceof \Illuminate\Database\Eloquent\Collection) { | |||||
$result->each( | |||||
function ($entry) { | |||||
$this->info($entry->{$entry->getKeyName()}); | |||||
} | |||||
); | |||||
} elseif ($result instanceof \Illuminate\Database\Eloquent\Relations\Relation) { | |||||
$result->each( | |||||
function ($entry) { | |||||
$this->info($entry->{$entry->getKeyName()}); | |||||
} | |||||
); | |||||
} else { | |||||
$this->info($result->{$result->getKeyName()}); | |||||
} | |||||
} | |||||
} |