File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/ArtisanCommands/SendcloudParcelStatuses.php
<?php
namespace App\ArtisanCommands;
use App\Shipments\ProviderAdapters\Sendcloud as SendcloudAdapter;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class SendcloudParcelStatuses extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sendcloud:parcel_statuses {--e|enum : Updates the enum in the Shipments namespace}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Shows a list of all possible parcel statuses';
/**
* Execute the console command.
*/
public function handle()
{
$adapter = new SendcloudAdapter();
$statuses = $adapter->parcelStatuses();
if(!$this->option('enum')) {
$this->displayStatuses($statuses);
} else {
$this->makeEnum($statuses);
}
}
private function displayStatuses(array $statuses) {
$this->info('Sendcloud Parcel statuses: ');
$this->line('');
foreach ($statuses as $status) {
$this->line($status['id'].' => '.$status['message']);
}
}
public function makeEnum(array $statuses) {
$enumName = 'SendcloudParcelStatusEnum';
$path = app_path('Shipments'.DIRECTORY_SEPARATOR.'Enums'.DIRECTORY_SEPARATOR.$enumName.'.php');
//Build basic file contents
$stub = <<<STUB
<?php declare(strict_types=1);
namespace App\Shipments\Enums;
use Komma\KMS\Base\Enum;
class {$enumName} extends Enum
{
STUB;
//Extract status names and ids
$statusNames = array_map(fn($status) => $status['message'], $statuses);
$ids = array_map(fn($status) => intval($status['id']), $statuses);
//turn status names into constant names
$statusNames = array_map(function($statusName) {
$const = strtoupper(Str::snake($statusName));
$const = preg_replace('/[^A-Za-z0-9_]/', '', $const);
return $const;
}, $statusNames);
//Build a list of class constants
$longestStatusName = max(array_map('mb_strlen', $statusNames));
foreach($ids as $index => $id) {
$leftHandSide = ' const ' . $statusNames[$index];
$rightHandSide = $id;
$stub .= str_pad($leftHandSide, $longestStatusName * 1.2, ' ', STR_PAD_RIGHT) . ' = ' . $rightHandSide.';'.PHP_EOL;
}
//End file contents
$stub .= <<<STUB
}
STUB;
//Save file
file_put_contents($path, $stub);
}
}