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
|
|
|
|
|
{
|
|
|
|
|
private string $instance;
|
|
|
|
|
private ?string $token;
|
|
|
|
|
|
|
|
|
|
public function __construct(string $instance, ?string $token = null)
|
|
|
|
|
{
|
2025-08-09 02:51:18 +02:00
|
|
|
// Handle both full URLs and just domain names
|
|
|
|
|
$this->instance = $this->normalizeInstance($instance);
|
2025-06-29 21:20:45 +02:00
|
|
|
$this->token = $token;
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-09 02:51:18 +02:00
|
|
|
/**
|
|
|
|
|
* Normalize instance URL to just the domain name
|
|
|
|
|
*/
|
|
|
|
|
private function normalizeInstance(string $instance): string
|
|
|
|
|
{
|
|
|
|
|
// Remove protocol if present
|
|
|
|
|
$instance = preg_replace('/^https?:\/\//', '', $instance);
|
|
|
|
|
|
|
|
|
|
// Remove trailing slash if present
|
|
|
|
|
$instance = rtrim($instance, '/');
|
|
|
|
|
|
|
|
|
|
return $instance;
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
{
|
|
|
|
|
$url = "https://{$this->instance}/api/v3/{$endpoint}";
|
|
|
|
|
|
|
|
|
|
$request = Http::timeout(30);
|
|
|
|
|
|
|
|
|
|
if ($this->token) {
|
|
|
|
|
$request = $request->withToken($this->token);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
{
|
|
|
|
|
$url = "https://{$this->instance}/api/v3/{$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;
|
|
|
|
|
}
|
|
|
|
|
}
|