Create the ListGates command file:
- Create a new file called
ListGates.php
inside theapp/Console/Commands
directory of your Laravel project. - Place the following code inside the
ListGates.php
file:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Auth\Access\Gate;
class ListGates extends Command
{
protected $signature = 'gate:list';
protected $description = 'List all defined gates in Laravel';
protected $gate;
public function __construct(Gate $gate)
{
parent::__construct();
$this->gate = $gate;
}
protected function getClosureContents(\Closure $closure)
{
$reflection = new \ReflectionFunction($closure);
$closureCode = file($reflection->getFileName());
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine();
$contents = array_slice($closureCode, $startLine - 1, $endLine - $startLine + 1);
return implode('', $contents);
}
public function handle()
{
$gates = $this->gate->abilities();
$self = $this;
$tableData = array_reduce(array_keys($gates), function ($carry, $key) use ($gates, $self) {
$value = $gates[$key];
$carry[] = [
'Gate Name' => $key,
'Closure Contents' => $self->getClosureContents($value),
];
return $carry;
}, []);
$this->table(['Gate Name', 'Closure Contents'], $tableData);
}
}
The only additional task we need to perform is formatting the gates array in a structure suitable for the table format expected by the table
method of the Command class. Laravel provides a range of convenient methods for CLI output formatting with the Symphony Console component, making this process much easier.
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
// ...
protected $commands = [
// Other commands...
\App\Console\Commands\ListGates::class,
];
// ...
}
Now, you can run the gates:list command from your terminal:
php artisan gate:list
And get this beautiful table:
+---------------+----------------------------------------------------------+
| Gate Name | Closure Contents |
+---------------+----------------------------------------------------------+
| viewHorizon | Gate::define('viewHorizon', function ($user) { |
| | return in_array($user->email, [ |
| | // |
| | ]); |
| | }); |
| | |
| viewTelescope | Gate::define('viewTelescope', function ($user) { |
| | return in_array($user->email, [ |
| | // |
| | ]); |
| | }); |
| | |
+---------------+----------------------------------------------------------+
Top comments (0)