Files
RomhackPlaza/app/Services/XenforoApiService.php

75 lines
2.1 KiB
PHP

<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class XenforoApiService {
private string $apiKey;
private int $superUserId;
private string $apiUrl;
public function __construct(){
$this->apiKey = config('services.xf_api.key');
$this->superUserId = config('services.xf_api.user');
$this->apiUrl = config('services.xf_api.url');
}
/**
* @throws ConnectionException
*/
private function get(string $endpoint, ?int $customUserId = null ): mixed
{
$response = Http::withHeaders([
'XF-Api-Key' => $this->apiKey,
'XF-Api-User' => $customUserId ?? $this->superUserId,
])->get("{$this->apiUrl}/{$endpoint}");
if( !$response->ok() )
return null;
return $response->json();
}
private function post(string $endpoint, ?int $customUserId = null, array $data = [] ): mixed
{
$response = Http::withHeaders([
'XF-Api-Key' => $this->apiKey,
'XF-Api-User' => $customUserId ?? $this->superUserId,
])->post("{$this->apiUrl}/{$endpoint}", $data);
if( !$response->ok() )
return null;
return $response->json();
}
public function getUserAlerts(int $userId): mixed
{
if( app(XenforoService::class)->getXfUser($userId)?->alerts_unviewed > 0 ) {
Cache::forget("xf_alerts_{$userId}");
}
return Cache::remember("xf_alerts_{$userId}", 60, function() use($userId) {
return $this->get("alerts?page=1&cutoff=7days", $userId);
});
}
public function markAllNotificationsRead(int $userId): void
{
Cache::forget("xf_alerts_{$userId}");
$this->post("alerts/marl-all", $userId );
}
public function getConversations(int $userId): mixed
{
return Cache::remember("xf_conversations_{$userId}", 60, function() use($userId) {
return $this->get("conversations?page=1&receiver_id={$userId}", $userId);
});
}
}