-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI_OPS.php
More file actions
89 lines (70 loc) · 2.62 KB
/
Copy pathAPI_OPS.php
File metadata and controls
89 lines (70 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
require_once __DIR__ . '/Env.php';
\Env::load(__DIR__ . '/.env');
define('OMDB_KEY', (string) ($_ENV['OMDB_API_KEY'] ?? getenv('OMDB_API_KEY') ?: 'c7d849bf'));
define('OMDB_BASE', 'https://www.omdbapi.com/');
function omdbFetch(string $url): ?array {
$options = [
'http' => [
'method' => 'GET',
'header' => "User-Agent: PHP\r\n",
'timeout' => 10,
'ignore_errors' => true
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
];
$context = stream_context_create($options);
$result = @file_get_contents($url, false, $context);
if ($result === false) {
return null;
}
return json_decode($result, true);
}
function getMoviesData(string $query, string $type, int $page): array {
// Default return structure
$out = ['movies' => [], 'totalResults' => 0, 'totalPages' => 0, 'error' => ''];
if (empty($query)) return $out;
// Build search URL
$url = OMDB_BASE . '?s=' . urlencode($query)
. '&page=' . $page
. '&apikey=' . OMDB_KEY;
if (!empty($type)) $url .= '&type=' . urlencode($type);
$data = omdbFetch($url);
if (!$data || $data['Response'] !== 'True') {
$out['error'] = $data['Error'] ?? 'No results found.';
return $out;
}
$out['totalResults'] = (int) $data['totalResults'];
$out['totalPages'] = (int) ceil($out['totalResults'] / 10);
$out['movies'] = $data['Search']; // basic info: Title, Year, imdbID, Type, Poster
return $out;
}
// For single movie page (used in movie.php)
function getMovieById(string $imdbID): ?array {
$url = OMDB_BASE . '?i=' . urlencode($imdbID) . '&plot=full&apikey=' . OMDB_KEY;
$data = omdbFetch($url);
return ($data && $data['Response'] === 'True') ? $data : null;
}
/**
* Fetches data for the index page, including a featured movie and trending movies.
*/
function getIndexData(): array {
$queries = ['Batman', 'Avengers', 'Star Wars', 'John Wick', 'Interstellar', 'Inception'];
$randomQuery = $queries[array_rand($queries)];
$trending = getMoviesData($randomQuery, 'movie', 1);
$movies = $trending['movies'] ?? [];
$featured = null;
if (!empty($movies)) {
// Use the first movie as featured, get full details
$featured = getMovieById($movies[0]['imdbID']);
}
return [
'hasFeatured' => !empty($featured),
'featured' => $featured,
'trendingMovies' => array_slice($movies, 1, 8), // Show up to 8 more as trending
'randomQuery' => $randomQuery
];
}