. */ class tmdb_interface { const BASE_API_URL = 'https://api.themoviedb.org/3'; public function read_header($ch, $str) { $header = explode(':', $str, 2); if (count($header) == 2) { $key = strtolower(trim($header[0])); $this->headers[$key] = trim($header[1]); } return strlen($str); } public function read_body($ch, $str) { $this->body_str = $str; $this->body_json = json_decode($str); $j_err = json_last_error(); $this->query_duration = microtime(true) - $this->start_time; if ($j_err !== JSON_ERROR_NONE) { $this->errors[] = $str; $this->errors[] = __METHOD__ . ", JSON error: " . get_json_error(json_last_error()); } return strlen($str); } public function query($api_path, $api_key, $query_str) { $this->start_time = microtime(true); $this->request_str = tmdb_interface::BASE_API_URL . '/' . $api_path . '?api_key=' . $api_key . '&query=' . urlencode($query_str); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $this->request_str); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLINFO_HEADER_OUT, true); curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'read_header')); curl_setopt($ch, CURLOPT_WRITEFUNCTION, array($this, 'read_body')); $response = curl_exec($ch); $this->info = curl_getinfo($ch); $err = curl_error($ch); curl_close($ch); if ($err) { $this->errors[] = $err; return null; } $valid_reponse_codes = [200,304]; if (!in_array($this->info['http_code'], $valid_reponse_codes, true)) { $this->errors[] = __METHOD__ . ", invalid response code: " . $this->info['http_code']; return null; } return $this->body_json; } public $request_str = ""; public $headers = []; public $body_str = ""; public $body_json; public $info; public $query_duration = 0; public $errors = []; private function get_json_error($error_enum) { $err = ''; switch($error_enum) { case JSON_ERROR_NONE: $err = 'No error has occurred'; break; case JSON_ERROR_DEPTH: $err = 'The maximum stack depth has been exceeded'; break; case JSON_ERROR_STATE_MISMATCH: $err ='Invalid or malformed JSON'; break; case JSON_ERROR_CTRL_CHAR: $err = 'Control character error, possibly incorrectly encoded'; break; case JSON_ERROR_SYNTAX: $err = 'Syntax error'; break; case JSON_ERROR_UTF8: $err = 'Malformed UTF-8 characters, possibly incorrectly encoded'; break; case JSON_ERROR_RECURSION: $err = 'One or more recursive references in the value to be encoded'; break; case JSON_ERROR_INF_OR_NAN: $err = 'One or more NAN or INF values in the value to be encoded'; break; case JSON_ERROR_UNSUPPORTED_TYPE: $err = 'A value of a type that cannot be encoded was given'; break; case JSON_ERROR_INVALID_PROPERTY_NAME: $err = 'A property name that cannot be encoded was given'; break; case JSON_ERROR_UTF16: $err = 'Malformed UTF-16 characters, possibly incorrectly encoded'; break; } return $err; } private $start_time = 0; } ?>