Guest User

DuckDuckGoInstantAnswer.php

a guest
Oct 11th, 2024
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. <?php
  2.  
  3. namespace spark\drivers\Http;
  4.  
  5. /**
  6. * DuckDuckGo Instant Answer API Consumer
  7. */
  8. class DuckDuckGoInstantAnswer
  9. {
  10.     const ENDPOINT = 'https://api.duckduckgo.com/?q=John+Wick&format=json&skip_disambig=1&t=Based';
  11.  
  12.     public function getAnswer($query)
  13.     {
  14.         if (filter_var($query, FILTER_VALIDATE_URL)) {
  15.             return false;
  16.         }
  17.  
  18.         $query = mb_strtolower(trim($query));
  19.         $requestURI = static::ENDPOINT . "?q={$query}&format=json&skip_disambig=1&t=Based";
  20.  
  21.         $pool = app()->cache;
  22.  
  23.         $handle = base64_encode($query);
  24.  
  25.         $item = $pool->getItem("answers/{$handle}");
  26.         $data = $item->get();
  27.  
  28.  
  29.         if ($item->isHit()) {
  30.             return $data;
  31.         }
  32.  
  33.         $http = Http::getSession();
  34.  
  35.         try {
  36.             $request = $http->get($requestURI, [], ['verify' => false]);
  37.             $response = json_decode($request->body, true);
  38.         } catch (\Exception $e) {
  39.             return false;
  40.         }
  41.  
  42.         if (!empty($response['Abstract'])) {
  43.             $item->set($response);
  44.             $item->expiresAfter(strtotime('+1 Year'));
  45.             $pool->save($item);
  46.         }
  47.  
  48.         return $response;
  49.     }
  50. }
  51.  
Add Comment
Please, Sign In to add comment