fedi-feed-router/backend/app/Modules/Lemmy/LemmyRequest.php
2025-08-09 13:48:25 +02:00

90 lines
2.3 KiB
PHP

<?php
namespace App\Modules\Lemmy;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
class LemmyRequest
{
private string $host;
private string $scheme;
private ?string $token;
public function __construct(string $instance, ?string $token = null)
{
// Handle both full URLs and just domain names
[$this->scheme, $this->host] = $this->parseInstance($instance);
$this->token = $token;
}
/**
* Parse instance into scheme and host. Defaults to https when scheme missing.
*
* @return array{0:string,1:string} [scheme, host]
*/
private function parseInstance(string $instance): array
{
$scheme = 'https';
// If instance includes a scheme, honor it
if (preg_match('/^(https?):\/\//i', $instance, $m)) {
$scheme = strtolower($m[1]);
}
// Remove protocol if present
$host = preg_replace('/^https?:\/\//i', '', $instance);
// Remove trailing slash if present
$host = rtrim($host ?? '', '/');
return [$scheme, $host];
}
/**
* @param array<string, mixed> $params
*/
public function get(string $endpoint, array $params = []): Response
{
$url = sprintf('%s://%s/api/v3/%s', $this->scheme, $this->host, ltrim($endpoint, '/'));
$request = Http::timeout(30);
if ($this->token) {
$request = $request->withToken($this->token);
}
return $request->get($url, $params);
}
/**
* @param array<string, mixed> $data
*/
public function post(string $endpoint, array $data = []): Response
{
$url = sprintf('%s://%s/api/v3/%s', $this->scheme, $this->host, ltrim($endpoint, '/'));
$request = Http::timeout(30);
if ($this->token) {
$request = $request->withToken($this->token);
}
return $request->post($url, $data);
}
public function withToken(string $token): self
{
$this->token = $token;
return $this;
}
/**
* Return a cloned request with a different scheme (http or https)
*/
public function withScheme(string $scheme): self
{
$clone = clone $this;
$clone->scheme = strtolower($scheme) === 'http' ? 'http' : 'https';
return $clone;
}
}