You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.4 KiB

  1. <?php
  2. namespace Adafruit\FeedMangler;
  3. use \Doctrine\Common\Cache\FilesystemCache;
  4. class Mangler {
  5. public static function getSearchData ($term)
  6. {
  7. return json_decode(self::getSearchJson($term), true /* use assoc array */);
  8. }
  9. public static function getSearchJson ($term)
  10. {
  11. // example: https://api.hackaday.io/v1/search?api_key=7yRgvQsCczOev&search_term=test
  12. $query = http_build_query([
  13. 'api_key' => API_KEY,
  14. 'search_term' => $term,
  15. ]);
  16. $search_url = 'https://api.hackaday.io/v1/search/projects?' . $query;
  17. $raw_search_json = self::getOrSetCache("search-{$term}", function () use ($search_url) {
  18. return file_get_contents($search_url);
  19. });
  20. return $raw_search_json;
  21. }
  22. /**
  23. * Get a cached value by key, or stash the value returned from $callback
  24. * under that key and return it.
  25. */
  26. protected static function getOrSetCache ($key, $callback, $expire = 600)
  27. {
  28. $cache = new FilesystemCache('/tmp');
  29. $cache->setNamespace('hackaday_projecten');
  30. // Juuuuuuust in case anyone gets clever with input - I don't know that I
  31. // especially trust this cache implementation not to dump user input onto the
  32. // filesystem:
  33. $hashed_key = hash('sha256', $key);
  34. if ($cache->contains($hashed_key)) {
  35. return $cache->fetch($hashed_key);
  36. }
  37. $callback_result = call_user_func($callback);
  38. $cache->save($hashed_key, $callback_result, $expire);
  39. return $callback_result;
  40. }
  41. }