59 lines
1.7 KiB
PHP
59 lines
1.7 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
declare(strict_types=1);
|
||
|
|
|
||
|
|
namespace App\Commands;
|
||
|
|
|
||
|
|
use App\Services\Trakt;
|
||
|
|
use Illuminate\Support\Arr;
|
||
|
|
|
||
|
|
class TraktDebug extends Command
|
||
|
|
{
|
||
|
|
protected $signature = 'trakt:debug {endpoint : Trakt API endpoint to call} {method=GET : HTTP method to use} {--d|data=* : data}';
|
||
|
|
protected $description = 'Make arbitrary requests to Trakt API.' . PHP_EOL . '-d should be formatted with key=value or key:=value for non-strings';
|
||
|
|
|
||
|
|
public function handle(Trakt $trakt): int
|
||
|
|
{
|
||
|
|
$body = $this->getBody();
|
||
|
|
$method = $this->argument('method');
|
||
|
|
$url = $this->argument('endpoint');
|
||
|
|
|
||
|
|
$resp = $trakt->request()->asJson();
|
||
|
|
if ($body) {
|
||
|
|
$body = json_encode($body);
|
||
|
|
$resp->withBody($body);
|
||
|
|
}
|
||
|
|
|
||
|
|
$this->line("Request: $method $url $body");
|
||
|
|
$resp = $resp->send($method, $url);
|
||
|
|
$this->line('Response (' . $resp->status() . '):' . PHP_EOL . json_encode($resp->json(), JSON_PRETTY_PRINT));
|
||
|
|
|
||
|
|
return static::SUCCESS;
|
||
|
|
}
|
||
|
|
|
||
|
|
protected function getBody(): ?array
|
||
|
|
{
|
||
|
|
if ($this->argument('method') === 'GET') {
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
$ret = [];
|
||
|
|
foreach ($this->option('data') as $kv) {
|
||
|
|
[$k, $v] = explode('=', $kv) + [null, null];
|
||
|
|
if (empty($k) || empty($v)) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if ($k[strlen($k) - 1] === ':') {
|
||
|
|
$k = substr($k, 0, strlen($k) - 1);
|
||
|
|
$v = json_decode($v, true);
|
||
|
|
if (json_last_error() !== JSON_ERROR_NONE) {
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
Arr::set($ret, $k, $v);
|
||
|
|
}
|
||
|
|
|
||
|
|
return $ret;
|
||
|
|
}
|
||
|
|
}
|