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.

68 lines
2.0 KiB

  1. <?php
  2. namespace p3k\XRay;
  3. use p3k\XRay\Formats;
  4. class Parser {
  5. private $http;
  6. public function __construct($http) {
  7. $this->http = $http;
  8. }
  9. public function parse($body, $url, $opts=[]) {
  10. if(isset($opts['timeout']))
  11. $this->http->set_timeout($opts['timeout']);
  12. if(isset($opts['max_redirects']))
  13. $this->http->set_max_redirects($opts['max_redirects']);
  14. // Check if the URL matches a special parser
  15. if(Formats\Instagram::matches($url)) {
  16. return Formats\Instagram::parse($this->http, $body, $url);
  17. }
  18. if(Formats\GitHub::matches($url)) {
  19. return Formats\GitHub::parse($body, $url);
  20. }
  21. if(Formats\Twitter::matches($url)) {
  22. return Formats\Twitter::parse($body, $url);
  23. }
  24. if(Formats\Facebook::matches($url)) {
  25. return Formats\Facebook::parse($body, $url);
  26. }
  27. if(Formats\XKCD::matches($url)) {
  28. return Formats\XKCD::parse($body, $url);
  29. }
  30. if(Formats\Hackernews::matches($url)) {
  31. return Formats\Hackernews::parse($body, $url);
  32. }
  33. // Check if an mf2 JSON object was passed in
  34. if(is_array($body) && isset($body['items'][0]['type']) && isset($body['items'][0]['properties'])) {
  35. return Formats\Mf2::parse($body, $url, $this->http, $opts);
  36. }
  37. if(substr($body, 0, 5) == '<?xml') {
  38. return Formats\XML::parse($body, $url);
  39. }
  40. if(substr($body, 0, 1) == '{') {
  41. $feeddata = json_decode($body, true);
  42. if($feeddata && isset($feeddata['version']) && $feeddata['version'] == 'https://jsonfeed.org/version/1') {
  43. return Formats\JSONFeed::parse($feeddata, $url);
  44. } elseif($feeddata && isset($feeddata['items'][0]['type']) && isset($feeddata['items'][0]['properties'])) {
  45. // Check if an mf2 JSON object was passed in
  46. return Formats\Mf2::parse($feeddata, $url, $this->http, $opts);
  47. }
  48. }
  49. // No special parsers matched, parse for Microformats now
  50. return Formats\HTML::parse($this->http, $body, $url, $opts);
  51. }
  52. }