1 | <?php |
||
56 | class Parser |
||
57 | { |
||
58 | /** |
||
59 | * Micro information formats |
||
60 | * |
||
61 | * @var int |
||
62 | */ |
||
63 | protected $formats; |
||
64 | /** |
||
65 | * Logger |
||
66 | * |
||
67 | * @var LoggerInterface |
||
68 | */ |
||
69 | protected $logger; |
||
70 | |||
71 | /** |
||
72 | * Parser constructor |
||
73 | * |
||
74 | * @param int $formats Micro information formats to extract |
||
75 | * @param LoggerInterface|null $logger PSR-3 compatible logger |
||
76 | * |
||
77 | * @api |
||
78 | */ |
||
79 | 1 | public function __construct($formats = Format::ALL, LoggerInterface $logger = null) |
|
84 | |||
85 | /** |
||
86 | * Extract micro information items out of a URI or piece of source |
||
87 | * |
||
88 | * @param string $uri URI |
||
89 | * @param string|null $source Source code |
||
90 | * @param int $formats Micro information formats to extract |
||
91 | * @param array $httpOptions HTTP request options |
||
92 | * |
||
93 | * @return ItemObjectModelInterface Item object model |
||
94 | * @api |
||
95 | */ |
||
96 | 1 | public function __invoke($uri, $source = null, $formats = null, array $httpOptions = []) |
|
97 | { |
||
98 | 1 | $dom = new \DOMDocument(); |
|
99 | 1 | $items = []; |
|
100 | |||
101 | try { |
||
102 | 1 | $parsers = ParserFactory::createParsersFromFormats( |
|
103 | 1 | intval($formats ?: $this->formats), |
|
104 | 1 | Http::createFromString($uri), |
|
105 | 1 | $this->logger |
|
106 | ); |
||
107 | 1 | $dom = $this->createDom($uri, $source, $httpOptions); |
|
108 | 1 | $items = $this->extractItems($dom, $parsers); |
|
109 | |||
110 | // In case of exceptions: Log if possible |
||
111 | } catch (\Exception $exception) { |
||
112 | $this->logger->critical($exception->getMessage(), ['exception' => $exception]); |
||
113 | } |
||
114 | |||
115 | 1 | return new ItemObjectModel($dom, $items); |
|
116 | } |
||
117 | |||
118 | /** |
||
119 | * Create the DOM document to parse |
||
120 | * |
||
121 | * @param string $uri URI |
||
122 | * @param string|null $source Source code |
||
123 | * @param array $httpOptions HTTP request options |
||
124 | * |
||
125 | * @return \DOMDocument DOM document |
||
126 | */ |
||
127 | 1 | protected function createDom($uri, $source = null, array $httpOptions = []) |
|
132 | |||
133 | /** |
||
134 | * Extract all items from a DOM using particular parsers |
||
135 | * |
||
136 | * @param \DOMDocument $dom DOM document |
||
137 | * @param \Generator $parsers Parsers |
||
138 | * |
||
139 | * @return ItemInterface[] Items |
||
140 | */ |
||
141 | 1 | protected function extractItems(\DOMDocument $dom, \Generator $parsers) |
|
152 | } |
||
153 |