oc-adrema-plugin/support/Proxy.php

49 lines
1.2 KiB
PHP

<?php
namespace Silva\Adrema\Support;
use Cache;
use Silva\Adrema\Models\Settings;
use Http;
use Illuminate\Http\JsonResponse;
class Proxy
{
public function run(string $url): ?array
{
if ($url === 'api/form') {
return Cache::rememberForever('adrema-all-events', fn () => $this->get($url));
}
return $this->get($url);
}
protected function get(string $url): ?array
{
$response = Http::acceptJson()->get($this->url($url));
if (!$response->ok()) {
return null;
}
return $response->json();
}
public function submit(string $url): JsonResponse
{
$headers = request()->header('X-Adrema-Token')
? [
'Authorization' => 'Bearer ' . request()->header('X-Adrema-Token'),
]
: [];
$response = Http::acceptJson()->withHeaders($headers)->post($this->url($url), request()->input());
return response()->json($response->json(), $response->status());
}
private function url(string $internal): string
{
return Settings::get('base_url') . str($internal)->start('/') . (request()->query() ? '?' . http_build_query(request()->query()) : '');
}
}