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.

58 lines
1.5 KiB

7 years ago
7 years ago
  1. <?php
  2. use Symfony\Component\HttpFoundation\Request;
  3. use Symfony\Component\HttpFoundation\Response;
  4. class Rels {
  5. public $http;
  6. private $_pretty = false;
  7. public function __construct() {
  8. $this->http = new p3k\HTTP();
  9. }
  10. private function respond(Response $response, $code, $params, $headers=[]) {
  11. $response->setStatusCode($code);
  12. foreach($headers as $k=>$v) {
  13. $response->headers->set($k, $v);
  14. }
  15. $response->headers->set('Content-Type', 'application/json');
  16. $opts = JSON_UNESCAPED_SLASHES;
  17. if($this->_pretty) $opts += JSON_PRETTY_PRINT;
  18. $response->setContent(json_encode($params, $opts)."\n");
  19. return $response;
  20. }
  21. public function fetch(Request $request, Response $response) {
  22. $opts = [];
  23. if($request->get('timeout')) {
  24. // We might make 2 HTTP requests, so each request gets half the desired timeout
  25. $opts['timeout'] = $request->get('timeout') / 2;
  26. }
  27. if($request->get('max_redirects')) {
  28. $opts['max_redirects'] = (int)$request->get('max_redirects');
  29. }
  30. if($request->get('pretty')) {
  31. $this->_pretty = true;
  32. }
  33. $url = $request->get('url');
  34. if(!$url) {
  35. return $this->respond($response, 400, [
  36. 'error' => 'missing_url',
  37. 'error_description' => 'Provide a URL to fetch'
  38. ]);
  39. }
  40. $xray = new p3k\XRay();
  41. $xray->http = $this->http;
  42. $res = $xray->rels($url, $opts);
  43. return $this->respond($response, !empty($res['error']) ? 400 : 200, $res);
  44. }
  45. }