fedi-feed-router/app/Modules/Lemmy/LemmyRequest.php

89 lines
2.2 KiB
PHP
Raw Normal View History

2025-06-29 21:20:45 +02:00
<?php
namespace App\Modules\Lemmy;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
class LemmyRequest
{
2025-08-10 01:26:56 +02:00
private string $instance;
2025-06-29 21:20:45 +02:00
private ?string $token;
2025-08-10 01:26:56 +02:00
private string $scheme = 'https';
2025-06-29 21:20:45 +02:00
public function __construct(string $instance, ?string $token = null)
{
2025-08-10 01:26:56 +02:00
// Detect scheme if provided in the instance string
if (preg_match('/^(https?):\/\//i', $instance, $m)) {
$this->scheme = strtolower($m[1]);
}
// Handle both full URLs and just domain names
2025-08-10 01:26:56 +02:00
$this->instance = $this->normalizeInstance($instance);
2025-06-29 21:20:45 +02:00
$this->token = $token;
}
/**
2025-08-10 01:26:56 +02:00
* Normalize instance URL to just the domain name
*/
2025-08-10 01:26:56 +02:00
private function normalizeInstance(string $instance): string
{
// Remove protocol if present
2025-08-10 01:26:56 +02:00
$instance = preg_replace('/^https?:\/\//i', '', $instance);
// Remove trailing slash if present
2025-08-10 01:26:56 +02:00
$instance = rtrim($instance, '/');
2025-08-09 13:48:25 +02:00
2025-08-10 01:26:56 +02:00
return $instance;
}
/**
* Explicitly set the scheme (http or https) for subsequent requests.
*/
public function withScheme(string $scheme): self
{
$scheme = strtolower($scheme);
if (in_array($scheme, ['http', 'https'], true)) {
$this->scheme = $scheme;
}
return $this;
}
2025-07-07 00:51:32 +02:00
/**
* @param array<string, mixed> $params
*/
2025-06-29 21:20:45 +02:00
public function get(string $endpoint, array $params = []): Response
{
2025-08-10 01:26:56 +02:00
$url = sprintf('%s://%s/api/v3/%s', $this->scheme, $this->instance, $endpoint);
2025-08-09 13:48:25 +02:00
2025-06-29 21:20:45 +02:00
$request = Http::timeout(30);
2025-08-09 13:48:25 +02:00
2025-06-29 21:20:45 +02:00
if ($this->token) {
$request = $request->withToken($this->token);
}
2025-08-09 13:48:25 +02:00
2025-06-29 21:20:45 +02:00
return $request->get($url, $params);
}
2025-07-07 00:51:32 +02:00
/**
* @param array<string, mixed> $data
*/
2025-06-29 21:20:45 +02:00
public function post(string $endpoint, array $data = []): Response
{
2025-08-10 01:26:56 +02:00
$url = sprintf('%s://%s/api/v3/%s', $this->scheme, $this->instance, $endpoint);
2025-08-09 13:48:25 +02:00
2025-06-29 21:20:45 +02:00
$request = Http::timeout(30);
2025-08-09 13:48:25 +02:00
2025-06-29 21:20:45 +02:00
if ($this->token) {
$request = $request->withToken($this->token);
}
2025-08-09 13:48:25 +02:00
2025-06-29 21:20:45 +02:00
return $request->post($url, $data);
}
public function withToken(string $token): self
{
$this->token = $token;
return $this;
}
}