Skip to content

Instantly share code, notes, and snippets.

@Kehet
Created December 21, 2024 15:45
Show Gist options
  • Save Kehet/1b2fa2fafb1b71ccfde1214e2b1eacdc to your computer and use it in GitHub Desktop.
Save Kehet/1b2fa2fafb1b71ccfde1214e2b1eacdc to your computer and use it in GitHub Desktop.
<?php
namespace App\Console\Traits;
use Closure;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use function Laravel\Prompts\info;
use function Laravel\Prompts\table;
use function Laravel\Prompts\text;
trait ConsoleHelpers
{
public function argumentOrAsk(
string $argumentName,
?string $label = null,
string $placeholder = '',
string $default = '',
bool|string $required = false,
mixed $validate = null,
string $hint = '',
?Closure $transform = null,
) {
$argument = $this->argument($argumentName);
if (!empty($argument)) {
return $argument;
}
return text(
$label ?? Str::of($argumentName)->headline()->toString(),
$placeholder,
$default,
$required,
$validate,
$hint,
$transform
);
}
public function printModel(Model $model, ?string $title = null): void
{
info($title ?? (get_class($model) . ': ' . $model->getKey()));
$attributes = collect($model->getAttributes());
$attributes->forget('id');
$attributes->prepend($model->getKey(), $model->getKeyName());
table(
['Attribute', 'Value'],
$attributes
->map(fn($value, $key) => [Str::of($key)->headline()->toString(), $value])
->toArray()
);
}
/**
* @param Collection<int, Model> $collection
* @param string|null $title
* @return void
*/
public function printCollection(Collection $collection, ?string $title = null): void
{
info($title ?? ('Collection<' . get_class($collection->first()) . '>'));
table(
collect($collection->first()->getAttributes())
->keys()
->map(fn($key) => Str::of($key)->headline()->toString()),
$collection
->map(fn(Model $model) => $model->getAttributes())
->toArray()
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment