chore(*.php): use pint for php formatting

This commit is contained in:
Cory Dransfeldt 2025-06-14 16:55:03 -07:00
parent bd1855a65e
commit 753f3433ce
No known key found for this signature in database
40 changed files with 2261 additions and 1900 deletions

View file

@ -1,11 +1,13 @@
<?php
namespace App\Classes;
namespace App\Classes;
abstract class ApiHandler extends BaseHandler
{
abstract class ApiHandler extends BaseHandler
{
protected function ensureCliAccess(): void
{
if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') redirectTo404();
if (php_sapi_name() !== 'cli' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
redirectTo404();
}
}
}
}

View file

@ -1,24 +1,28 @@
<?php
namespace App\Classes;
namespace App\Classes;
class ArtistFetcher extends PageFetcher
{
class ArtistFetcher extends PageFetcher
{
public function fetch(string $url): ?array
{
$cacheKey = "artist_" . md5($url);
$cached = $this->cacheGet($cacheKey);
$cacheKey = 'artist_'.md5($url);
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$artist = $this->fetchSingleFromApi("optimized_artists", $url);
$artist = $this->fetchSingleFromApi('optimized_artists', $url);
if (!$artist) return null;
if (! $artist) {
return null;
}
$artist['globals'] = $this->getGlobals();
$artist['globals'] = $this->getGlobals();
$this->cacheSet($cacheKey, $artist);
$this->cacheSet($cacheKey, $artist);
return $artist;
return $artist;
}
}
}

View file

@ -1,100 +1,106 @@
<?php
namespace App\Classes;
namespace App\Classes;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
abstract class BaseHandler
{
abstract class BaseHandler
{
protected string $postgrestUrl;
protected string $postgrestApiKey;
protected ?\Redis $cache = null;
public function __construct()
{
$this->loadEnvironment();
$this->initializeCache();
$this->loadEnvironment();
$this->initializeCache();
}
private function loadEnvironment(): void
{
$this->postgrestUrl = $_ENV["POSTGREST_URL"] ?? getenv("POSTGREST_URL") ?? "";
$this->postgrestApiKey = $_ENV["POSTGREST_API_KEY"] ?? getenv("POSTGREST_API_KEY") ?? "";
$this->postgrestUrl = $_ENV['POSTGREST_URL'] ?? getenv('POSTGREST_URL') ?? '';
$this->postgrestApiKey = $_ENV['POSTGREST_API_KEY'] ?? getenv('POSTGREST_API_KEY') ?? '';
}
protected function initializeCache(): void
{
if (class_exists("Redis")) {
try {
$redis = new \Redis();
$redis->connect("127.0.0.1", 6379);
if (class_exists('Redis')) {
try {
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$this->cache = $redis;
} catch (\Exception $e) {
error_log("Redis connection failed: " . $e->getMessage());
$this->cache = $redis;
} catch (\Exception $e) {
error_log('Redis connection failed: '.$e->getMessage());
$this->cache = null;
$this->cache = null;
}
} else {
error_log('Redis extension not found — caching disabled.');
$this->cache = null;
}
} else {
error_log("Redis extension not found — caching disabled.");
$this->cache = null;
}
}
protected function makeRequest(string $method, string $endpoint, array $options = []): array
{
$client = new Client();
$url = rtrim($this->postgrestUrl, "/") . "/" . ltrim($endpoint, "/");
$client = new Client();
$url = rtrim($this->postgrestUrl, '/').'/'.ltrim($endpoint, '/');
try {
$response = $client->request($method, $url, array_merge_recursive([
"headers" => [
"Authorization" => "Bearer {$this->postgrestApiKey}",
"Content-Type" => "application/json",
]
], $options));
try {
$response = $client->request($method, $url, array_merge_recursive([
'headers' => [
'Authorization' => "Bearer {$this->postgrestApiKey}",
'Content-Type' => 'application/json',
],
], $options));
$responseBody = $response->getBody()->getContents();
$responseBody = $response->getBody()->getContents();
if (empty($responseBody)) return [];
if (empty($responseBody)) {
return [];
}
$data = json_decode($responseBody, true);
$data = json_decode($responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) throw new \Exception("Invalid JSON: " . json_last_error_msg());
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \Exception('Invalid JSON: '.json_last_error_msg());
}
return $data;
} catch (RequestException $e) {
$response = $e->getResponse();
$statusCode = $response ? $response->getStatusCode() : 'N/A';
$responseBody = $response ? $response->getBody()->getContents() : 'No response';
return $data;
} catch (RequestException $e) {
$response = $e->getResponse();
$statusCode = $response ? $response->getStatusCode() : 'N/A';
$responseBody = $response ? $response->getBody()->getContents() : 'No response';
throw new \Exception("HTTP {$method} {$url} failed with status {$statusCode}: {$responseBody}");
} catch (\Exception $e) {
throw new \Exception("Request error: " . $e->getMessage());
}
throw new \Exception("HTTP {$method} {$url} failed with status {$statusCode}: {$responseBody}");
} catch (\Exception $e) {
throw new \Exception('Request error: '.$e->getMessage());
}
}
protected function fetchFromApi(string $endpoint, string $query = ""): array
protected function fetchFromApi(string $endpoint, string $query = ''): array
{
$url = $endpoint . ($query ? "?{$query}" : "");
$url = $endpoint.($query ? "?{$query}" : '');
return $this->makeRequest("GET", $url);
return $this->makeRequest('GET', $url);
}
protected function sendResponse(array $data, int $statusCode = 200): void
{
http_response_code($statusCode);
header("Content-Type: application/json");
http_response_code($statusCode);
header('Content-Type: application/json');
echo json_encode($data);
echo json_encode($data);
exit();
exit();
}
protected function sendErrorResponse(string $message, int $statusCode = 500): void
{
$this->sendResponse(["error" => $message], $statusCode);
$this->sendResponse(['error' => $message], $statusCode);
}
}
}

View file

@ -1,24 +1,28 @@
<?php
namespace App\Classes;
namespace App\Classes;
class BookFetcher extends PageFetcher
{
class BookFetcher extends PageFetcher
{
public function fetch(string $url): ?array
{
$cacheKey = "book_" . md5($url);
$cached = $this->cacheGet($cacheKey);
$cacheKey = 'book_'.md5($url);
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$book = $this->fetchSingleFromApi("optimized_books", $url);
$book = $this->fetchSingleFromApi('optimized_books', $url);
if (!$book) return null;
if (! $book) {
return null;
}
$book['globals'] = $this->getGlobals();
$book['globals'] = $this->getGlobals();
$this->cacheSet($cacheKey, $book);
$this->cacheSet($cacheKey, $book);
return $book;
return $book;
}
}
}

View file

@ -1,24 +1,28 @@
<?php
namespace App\Classes;
namespace App\Classes;
class GenreFetcher extends PageFetcher
{
class GenreFetcher extends PageFetcher
{
public function fetch(string $url): ?array
{
$cacheKey = "genre_" . md5($url);
$cached = $this->cacheGet($cacheKey);
$cacheKey = 'genre_'.md5($url);
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$genre = $this->fetchSingleFromApi("optimized_genres", $url);
$genre = $this->fetchSingleFromApi('optimized_genres', $url);
if (!$genre) return null;
if (! $genre) {
return null;
}
$genre['globals'] = $this->getGlobals();
$genre['globals'] = $this->getGlobals();
$this->cacheSet($cacheKey, $genre);
$this->cacheSet($cacheKey, $genre);
return $genre;
return $genre;
}
}
}

View file

@ -1,22 +1,26 @@
<?php
namespace App\Classes;
namespace App\Classes;
class GlobalsFetcher extends PageFetcher
{
class GlobalsFetcher extends PageFetcher
{
public function fetch(): ?array
{
$cacheKey = "globals";
$cached = $this->cacheGet($cacheKey);
$cacheKey = 'globals';
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$globals = $this->fetchFromApi("optimized_globals");
$globals = $this->fetchFromApi('optimized_globals');
if (empty($globals)) return null;
if (empty($globals)) {
return null;
}
$this->cacheSet($cacheKey, $globals[0]);
$this->cacheSet($cacheKey, $globals[0]);
return $globals[0];
return $globals[0];
}
}
}

View file

@ -2,68 +2,73 @@
namespace App\Classes;
use App\Classes\BaseHandler;
class LatestListenHandler extends BaseHandler
{
protected int $cacheTTL = 60;
protected int $cacheTTL = 60;
public function __construct()
{
parent::__construct();
$this->initializeCache();
}
public function handleRequest(): void
{
$data = $this->getLatestListen();
if (!$data) {
$this->sendResponse(["message" => "No recent tracks found"], 404);
return;
public function __construct()
{
parent::__construct();
$this->initializeCache();
}
$this->sendResponse($data);
}
public function handleRequest(): void
{
$data = $this->getLatestListen();
public function getLatestListen(): ?array
{
try {
$cachedData = $this->cache ? $this->cache->get("latest_listen") : null;
if (! $data) {
$this->sendResponse(['message' => 'No recent tracks found'], 404);
if ($cachedData) return json_decode($cachedData, true);
return;
}
$data = $this->makeRequest("GET", "optimized_latest_listen?select=*");
if (!is_array($data) || empty($data[0])) return null;
$latestListen = $this->formatLatestListen($data[0]);
if ($this->cache) $this->cache->set("latest_listen", json_encode($latestListen), $this->cacheTTL);
return $latestListen;
} catch (\Exception $e) {
error_log("LatestListenHandler::getLatestListen error: " . $e->getMessage());
return null;
$this->sendResponse($data);
}
}
private function formatLatestListen(array $latestListen): array
{
$emoji = $latestListen["artist_emoji"] ?? ($latestListen["genre_emoji"] ?? "🎧");
$trackName = htmlspecialchars($latestListen["track_name"] ?? "Unknown Track", ENT_QUOTES, "UTF-8");
$artistName = htmlspecialchars($latestListen["artist_name"] ?? "Unknown Artist", ENT_QUOTES, "UTF-8");
$url = htmlspecialchars($latestListen["url"] ?? "/", ENT_QUOTES, "UTF-8");
public function getLatestListen(): ?array
{
try {
$cachedData = $this->cache ? $this->cache->get('latest_listen') : null;
return [
"content" => sprintf(
'%s %s by <a href="%s">%s</a>',
$emoji,
$trackName,
$url,
$artistName
),
];
}
if ($cachedData) {
return json_decode($cachedData, true);
}
$data = $this->makeRequest('GET', 'optimized_latest_listen?select=*');
if (! is_array($data) || empty($data[0])) {
return null;
}
$latestListen = $this->formatLatestListen($data[0]);
if ($this->cache) {
$this->cache->set('latest_listen', json_encode($latestListen), $this->cacheTTL);
}
return $latestListen;
} catch (\Exception $e) {
error_log('LatestListenHandler::getLatestListen error: '.$e->getMessage());
return null;
}
}
private function formatLatestListen(array $latestListen): array
{
$emoji = $latestListen['artist_emoji'] ?? ($latestListen['genre_emoji'] ?? '🎧');
$trackName = htmlspecialchars($latestListen['track_name'] ?? 'Unknown Track', ENT_QUOTES, 'UTF-8');
$artistName = htmlspecialchars($latestListen['artist_name'] ?? 'Unknown Artist', ENT_QUOTES, 'UTF-8');
$url = htmlspecialchars($latestListen['url'] ?? '/', ENT_QUOTES, 'UTF-8');
return [
'content' => sprintf(
'%s %s by <a href="%s">%s</a>',
$emoji,
$trackName,
$url,
$artistName
),
];
}
}

View file

@ -1,24 +1,28 @@
<?php
namespace App\Classes;
namespace App\Classes;
class MovieFetcher extends PageFetcher
{
class MovieFetcher extends PageFetcher
{
public function fetch(string $url): ?array
{
$cacheKey = "movie_" . md5($url);
$cached = $this->cacheGet($cacheKey);
$cacheKey = 'movie_'.md5($url);
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$movie = $this->fetchSingleFromApi("optimized_movies", $url);
$movie = $this->fetchSingleFromApi('optimized_movies', $url);
if (!$movie) return null;
if (! $movie) {
return null;
}
$movie['globals'] = $this->getGlobals();
$movie['globals'] = $this->getGlobals();
$this->cacheSet($cacheKey, $movie);
$this->cacheSet($cacheKey, $movie);
return $movie;
return $movie;
}
}
}

View file

@ -4,23 +4,27 @@ namespace App\Classes;
class MusicDataHandler extends BaseHandler
{
protected int $cacheTTL = 300;
protected int $cacheTTL = 300;
public function getThisWeekData(): array
{
$cacheKey = 'music_week_data';
$cached = $this->cache ? $this->cache->get($cacheKey) : null;
public function getThisWeekData(): array
{
$cacheKey = 'music_week_data';
$cached = $this->cache ? $this->cache->get($cacheKey) : null;
if ($cached) return json_decode($cached, true);
if ($cached) {
return json_decode($cached, true);
}
$response = $this->makeRequest('GET', 'optimized_week_music?select=*');
$music = $response[0]['week_music'] ?? [];
$music['total_tracks'] = $music['week_summary']['total_tracks'] ?? 0;
$music['total_artists'] = $music['week_summary']['total_artists'] ?? 0;
$music['total_albums'] = $music['week_summary']['total_albums'] ?? 0;
$response = $this->makeRequest('GET', 'optimized_week_music?select=*');
$music = $response[0]['week_music'] ?? [];
$music['total_tracks'] = $music['week_summary']['total_tracks'] ?? 0;
$music['total_artists'] = $music['week_summary']['total_artists'] ?? 0;
$music['total_albums'] = $music['week_summary']['total_albums'] ?? 0;
if ($this->cache) $this->cache->set($cacheKey, json_encode($music), $this->cacheTTL);
if ($this->cache) {
$this->cache->set($cacheKey, json_encode($music), $this->cacheTTL);
}
return $music;
}
return $music;
}
}

View file

@ -2,43 +2,44 @@
namespace App\Classes;
use App\Classes\BaseHandler;
use App\Classes\GlobalsFetcher;
abstract class PageFetcher extends BaseHandler
{
protected ?array $globals = null;
protected ?array $globals = null;
protected function cacheGet(string $key): mixed
{
return $this->cache && $this->cache->exists($key) ? json_decode($this->cache->get($key), true) : null;
}
protected function cacheGet(string $key): mixed
{
return $this->cache && $this->cache->exists($key) ? json_decode($this->cache->get($key), true) : null;
}
protected function cacheSet(string $key, mixed $value, int $ttl = 300): void
{
if ($this->cache) $this->cache->setex($key, $ttl, json_encode($value));
}
protected function cacheSet(string $key, mixed $value, int $ttl = 300): void
{
if ($this->cache) {
$this->cache->setex($key, $ttl, json_encode($value));
}
}
protected function fetchSingleFromApi(string $endpoint, string $url): ?array
{
$data = $this->fetchFromApi($endpoint, "url=eq./{$url}");
protected function fetchSingleFromApi(string $endpoint, string $url): ?array
{
$data = $this->fetchFromApi($endpoint, "url=eq./{$url}");
return $data[0] ?? null;
}
return $data[0] ?? null;
}
protected function fetchPostRpc(string $endpoint, array $body): ?array
{
return $this->makeRequest("POST", $endpoint, ['json' => $body]);
}
protected function fetchPostRpc(string $endpoint, array $body): ?array
{
return $this->makeRequest('POST', $endpoint, ['json' => $body]);
}
public function getGlobals(): ?array
{
if ($this->globals !== null) return $this->globals;
public function getGlobals(): ?array
{
if ($this->globals !== null) {
return $this->globals;
}
$fetcher = new GlobalsFetcher();
$fetcher = new GlobalsFetcher();
$this->globals = $fetcher->fetch();
$this->globals = $fetcher->fetch();
return $this->globals;
}
return $this->globals;
}
}

View file

@ -4,33 +4,37 @@ namespace App\Classes;
class RecentMediaHandler extends BaseHandler
{
protected int $cacheTTL = 300;
protected int $cacheTTL = 300;
public function getRecentMedia(): array
{
try {
$cacheKey = 'recent_media';
public function getRecentMedia(): array
{
try {
$cacheKey = 'recent_media';
if ($this->cache) {
$cached = $this->cache->get($cacheKey);
if ($this->cache) {
$cached = $this->cache->get($cacheKey);
if ($cached) return json_decode($cached, true);
}
if ($cached) {
return json_decode($cached, true);
}
}
$response = $this->makeRequest("GET", "optimized_recent_media?select=*");
$activity = $response[0]['recent_activity'] ?? [];
$data = [
'recentMusic' => $activity['recentMusic'] ?? [],
'recentWatchedRead' => $activity['recentWatchedRead'] ?? [],
];
$response = $this->makeRequest('GET', 'optimized_recent_media?select=*');
$activity = $response[0]['recent_activity'] ?? [];
$data = [
'recentMusic' => $activity['recentMusic'] ?? [],
'recentWatchedRead' => $activity['recentWatchedRead'] ?? [],
];
if ($this->cache) $this->cache->set($cacheKey, json_encode($data), $this->cacheTTL);
if ($this->cache) {
$this->cache->set($cacheKey, json_encode($data), $this->cacheTTL);
}
return $data;
} catch (\Exception $e) {
error_log("RecentMediaHandler error: " . $e->getMessage());
return $data;
} catch (\Exception $e) {
error_log('RecentMediaHandler error: '.$e->getMessage());
return ['recentMusic' => [], 'recentWatchedRead' => []];
return ['recentMusic' => [], 'recentWatchedRead' => []];
}
}
}
}

View file

@ -1,24 +1,28 @@
<?php
namespace App\Classes;
namespace App\Classes;
class ShowFetcher extends PageFetcher
{
class ShowFetcher extends PageFetcher
{
public function fetch(string $url): ?array
{
$cacheKey = "show_" . md5($url);
$cached = $this->cacheGet($cacheKey);
$cacheKey = 'show_'.md5($url);
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$show = $this->fetchSingleFromApi("optimized_shows", $url);
$show = $this->fetchSingleFromApi('optimized_shows', $url);
if (!$show) return null;
if (! $show) {
return null;
}
$show['globals'] = $this->getGlobals();
$show['globals'] = $this->getGlobals();
$this->cacheSet($cacheKey, $show);
$this->cacheSet($cacheKey, $show);
return $show;
return $show;
}
}
}

View file

@ -4,26 +4,30 @@ namespace App\Classes;
class TagFetcher extends PageFetcher
{
public function fetch(string $tag, int $page = 1, int $pageSize = 20): ?array
{
$offset = ($page - 1) * $pageSize;
$cacheKey = "tag_" . md5("{$tag}_{$page}");
$cached = $this->cacheGet($cacheKey);
public function fetch(string $tag, int $page = 1, int $pageSize = 20): ?array
{
$offset = ($page - 1) * $pageSize;
$cacheKey = 'tag_'.md5("{$tag}_{$page}");
$cached = $this->cacheGet($cacheKey);
if ($cached) return $cached;
if ($cached) {
return $cached;
}
$results = $this->fetchPostRpc("rpc/get_tagged_content", [
"tag_query" => $tag,
"page_size" => $pageSize,
"page_offset" => $offset
]);
$results = $this->fetchPostRpc('rpc/get_tagged_content', [
'tag_query' => $tag,
'page_size' => $pageSize,
'page_offset' => $offset,
]);
if (!$results || count($results) === 0) return null;
if (! $results || count($results) === 0) {
return null;
}
$results[0]['globals'] = $this->getGlobals();
$results[0]['globals'] = $this->getGlobals();
$this->cacheSet($cacheKey, $results);
$this->cacheSet($cacheKey, $results);
return $results;
}
return $results;
}
}