|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Obadiah\NetBible; |
| 4 | + |
| 5 | +use Obadiah\App; |
| 6 | +use Obadiah\Helpers\Log; |
| 7 | + |
| 8 | +App::check(); |
| 9 | + |
| 10 | +class Api |
| 11 | +{ |
| 12 | + /** |
| 13 | + * Create API object. |
| 14 | + * |
| 15 | + */ |
| 16 | + public function __construct() {} |
| 17 | + |
| 18 | + /** |
| 19 | + * Get a passage from the NET Bible API. |
| 20 | + * |
| 21 | + * @param string $passage The passage to retrieve - multiple passages should be separated by a semi-colon. |
| 22 | + * @param string $type The return type - either 'text' (default) or 'json'. |
| 23 | + * @return mixed If $passage is a valid Bible reference, the NET Bible text of that passage. |
| 24 | + */ |
| 25 | + private function get(string $passage, string $type = "text"): mixed |
| 26 | + { |
| 27 | + // build URL from data |
| 28 | + $formatting = match($type) { |
| 29 | + "text" => "para", |
| 30 | + default => "plain" |
| 31 | + }; |
| 32 | + $url = sprintf("https://labs.bible.org/api/?passage=%s&type=%s&formatting=%s", urlencode($passage), $type, $formatting); |
| 33 | + |
| 34 | + // create curl request |
| 35 | + $handle = curl_init($url); |
| 36 | + if ($handle === false) { |
| 37 | + _l("Unable to create cURL request for %s.", $url); |
| 38 | + return null; |
| 39 | + } |
| 40 | + |
| 41 | + curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); |
| 42 | + |
| 43 | + // make request - on error log and return null |
| 44 | + $response = curl_exec($handle); |
| 45 | + if (!is_string($response)) { |
| 46 | + _l(print_r(curl_error($handle), true)); |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + // if type is JSON, decode and return |
| 51 | + if ($type === "json") { |
| 52 | + $json = json_decode($response); |
| 53 | + if (!$json) { |
| 54 | + _l("Unable to decode JSON response from %s.", $url); |
| 55 | + return null; |
| 56 | + } |
| 57 | + |
| 58 | + return $json; |
| 59 | + } |
| 60 | + |
| 61 | + // otherwise return as text |
| 62 | + return $response; |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Get Bible passage as JSON. |
| 67 | + * |
| 68 | + * @param string $passage The passage to retrieve - multiple passages should be separated by a semi-colon. |
| 69 | + * @return mixed If $passage is a valid Bible reference, the NET Bible text of that passage. |
| 70 | + */ |
| 71 | + public function get_json(string $passage): mixed |
| 72 | + { |
| 73 | + return $this->get($passage, "json"); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * Get Bible passage as (HTML-formatted) text. |
| 78 | + * |
| 79 | + * @param string $passage The passage to retrieve - multiple passages should be separated by a semi-colon. |
| 80 | + * @return ?string If $passage is a valid Bible reference, the NET Bible text of that passage. |
| 81 | + */ |
| 82 | + public function get_text(string $passage): ?string |
| 83 | + { |
| 84 | + return $this->get($passage, "text"); |
| 85 | + } |
| 86 | +} |
0 commit comments