movie-night-nuevo/app/Services/OmdbService.php

76 lines
2.2 KiB
PHP
Raw Permalink Normal View History

2025-12-12 23:07:04 -06:00
<?php
namespace App\Services;
use App\Models\Interfaces\MovieDbInterface;
use App\Models\Movie;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Http;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
2025-12-13 19:33:52 -06:00
use function Symfony\Component\Translation\t;
2025-12-12 23:07:04 -06:00
class OmdbService implements MovieDbInterface
{
private string $url;
private User $user;
public function __construct(private Movie $movie)
{
$this->url = config('services.omdb.api_url') . config('services.omdb.api_key');
$this->user = auth()->user();
}
2025-12-13 19:33:52 -06:00
public function search(string $query, array $options = []): array|Movie
2025-12-12 23:07:04 -06:00
{
2025-12-13 19:33:52 -06:00
$searchType = $options["type"] ?? "title";
$result = match ($searchType) {
'imdb' => $this->searchByImdbId($query),
'title' => $this->searchByTitle($query),
default => $this->searchByTitle($query),
};
return $result;
}
public function searchByImdbId(string $imdbId)
{
$movie = Http::get($this->url . "&i=" . $imdbId)->json();
2025-12-12 23:07:04 -06:00
if ($movie['Response'] !== 'True') {
throw new NotFoundHttpException("Movie not found");
}
try {
$existing_movie = $this->movie->where('imdb_id', $movie['imdbID'])->firstOrFail();
return $existing_movie;
} catch (Exception $e) {
return Movie::fromOmdb(array_merge(
$movie,
["added_by" => $this->user->id])
);
}
}
2025-12-13 19:33:52 -06:00
public function searchByTitle(string $title)
{
$search_results = Http::get($this->url . "&s=" . $title . "&type=movie")->json();
if ($search_results['Response'] !== 'True') {
throw new NotFoundHttpException("Movie not found");
}
$movies = [];
foreach ($search_results['Search'] as $result) {
$movies[] = [
'title' => $result['Title'] ?? "",
'year' => $result['Year'] ?? "",
'imdb_id' => $result['imdbID'] ?? "",
'type' => $result['Type'] ?? "",
'poster' => $result['Poster'] ?? ""
];
}
return $movies;
}
2025-12-12 23:07:04 -06:00
}