Created
July 15, 2019 16:33
-
-
Save mentisy/7ab3e2da12de03c39bc57e192f2cd424 to your computer and use it in GitHub Desktop.
CakePHP: Trait for outputting entities in CLI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Command\Traits; | |
use Cake\Console\ConsoleIo; | |
use Cake\Datasource\EntityInterface; | |
trait EntitiesTrait { | |
/** | |
* Output all members | |
* | |
* @param ConsoleIo $io | |
* @param array $properties | |
* @param EntityInterface[] $entities | |
* @param array|null $headers | |
* @return void | |
*/ | |
public function outputEntities(ConsoleIo $io, $properties, $entities, $headers = null) { | |
if(is_null($headers)) { | |
$headers = $properties; | |
} | |
$output[] = $headers; | |
/** @var EntityInterface[] $entities */ | |
foreach($entities as $entity) { | |
$row = []; | |
foreach($entity->getVisible() as $property) { | |
$row[] = $entity->get($property); | |
} | |
$output[] = $row; | |
} | |
$io->helper('Table')->output($output); | |
} | |
/** | |
* @param ConsoleIo $io | |
* @param EntityInterface $entity | |
* @return array | |
*/ | |
public function askForProperties(ConsoleIo $io, EntityInterface $entity): array { | |
$props = []; | |
foreach($entity->getVisible() as $property) { | |
if($entity->isAccessible($property)) { | |
$props[$property] = $io->ask(sprintf("%s?", $property), (string)$entity->get($property)); | |
} | |
} | |
return $props; | |
} | |
/** | |
* @param ConsoleIo $io | |
* @param EntityInterface $entity | |
*/ | |
public function outputEntity(ConsoleIo $io, EntityInterface $entity) { | |
$rows[] = [__('Property'), __('Value')]; | |
foreach($entity->getVisible() as $property) { | |
if($entity->isAccessible($property)) { | |
$rows[] = [$property, $entity->get($property)]; | |
} | |
} | |
$io->helper('Table')->output($rows); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment