SubscriptionListParser.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace PicoFeed\Serialization;
  3. use PicoFeed\Parser\MalformedXmlException;
  4. use PicoFeed\Parser\XmlParser;
  5. use SimpleXMLElement;
  6. /**
  7. * Class SubscriptionListParser
  8. *
  9. * @package PicoFeed\Serialization
  10. * @author Frederic Guillot
  11. */
  12. class SubscriptionListParser
  13. {
  14. /**
  15. * @var SubscriptionList
  16. */
  17. protected $subscriptionList;
  18. /**
  19. * @var string
  20. */
  21. protected $data;
  22. /**
  23. * Constructor
  24. *
  25. * @access public
  26. * @param string $data
  27. */
  28. public function __construct($data)
  29. {
  30. $this->subscriptionList = new SubscriptionList();
  31. $this->data = trim($data);
  32. }
  33. /**
  34. * Get object instance
  35. *
  36. * @static
  37. * @access public
  38. * @param string $data
  39. * @return SubscriptionListParser
  40. */
  41. public static function create($data)
  42. {
  43. return new static($data);
  44. }
  45. /**
  46. * Parse a subscription list entry
  47. *
  48. * @access public
  49. * @throws MalformedXmlException
  50. * @return SubscriptionList
  51. */
  52. public function parse()
  53. {
  54. $xml = XmlParser::getSimpleXml($this->data);
  55. if (! $xml || !isset($xml->head) || !isset($xml->body)) {
  56. throw new MalformedXmlException('Unable to parse OPML file: invalid XML');
  57. }
  58. $this->parseTitle($xml->head);
  59. $this->parseEntries($xml->body);
  60. return $this->subscriptionList;
  61. }
  62. /**
  63. * Parse title
  64. *
  65. * @access protected
  66. * @param SimpleXMLElement $xml
  67. */
  68. protected function parseTitle(SimpleXMLElement $xml)
  69. {
  70. $this->subscriptionList->setTitle((string) $xml->title);
  71. }
  72. /**
  73. * Parse entries
  74. *
  75. * @access protected
  76. * @param SimpleXMLElement $body
  77. */
  78. private function parseEntries(SimpleXMLElement $body)
  79. {
  80. foreach ($body->outline as $outlineElement) {
  81. if (isset($outlineElement->outline)) {
  82. $this->parseEntries($outlineElement);
  83. } else {
  84. $this->subscriptionList->subscriptions[] = SubscriptionParser::create($body, $outlineElement)->parse();
  85. }
  86. }
  87. }
  88. }