Skip to content

Instantly share code, notes, and snippets.

@mentisy
Created July 15, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mentisy/7ab3e2da12de03c39bc57e192f2cd424 to your computer and use it in GitHub Desktop.
Save mentisy/7ab3e2da12de03c39bc57e192f2cd424 to your computer and use it in GitHub Desktop.
CakePHP: Trait for outputting entities in CLI
<?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