|
8 | 8 |
|
9 | 9 | namespace Webfactory\Bundle\LegacyIntegrationBundle\Integration; |
10 | 10 |
|
| 11 | +use Psr\Log\LoggerInterface; |
| 12 | +use Psr\Log\NullLogger; |
11 | 13 | use Webfactory\Dom\BaseParsingHelper; |
| 14 | +use Webfactory\Dom\Exception\ParsingException; |
12 | 15 |
|
13 | 16 | class XPathHelperFactory |
14 | 17 | { |
15 | | - |
16 | 18 | /** @var BaseParsingHelper */ |
17 | 19 | protected $parser; |
18 | 20 |
|
19 | 21 | /** @var LegacyApplication */ |
20 | 22 | protected $legacyApplication; |
21 | 23 |
|
22 | | - public function __construct(BaseParsingHelper $parser, LegacyApplication $legacy) |
| 24 | + /** |
| 25 | + * @var LoggerInterface |
| 26 | + */ |
| 27 | + private $logger; |
| 28 | + |
| 29 | + public function __construct(BaseParsingHelper $parser, LegacyApplication $legacy, LoggerInterface $logger = null) |
23 | 30 | { |
24 | 31 | $this->parser = $parser; |
25 | 32 | $this->legacyApplication = $legacy; |
| 33 | + $this->logger = $logger ?: new NullLogger(); |
26 | 34 | } |
27 | 35 |
|
28 | 36 | public function createHelper() |
29 | 37 | { |
30 | | - return new XPathHelper($this->parser, $this->legacyApplication->getResponse()->getContent()); |
| 38 | + $content = $this->legacyApplication->getResponse()->getContent(); |
| 39 | + |
| 40 | + try { |
| 41 | + return new XPathHelper($this->parser, $content); |
| 42 | + } catch (ParsingException $exception) { |
| 43 | + if (function_exists('tidy_repair_string')) { |
| 44 | + $this->logger->notice('Failed parsing the legacy response as XHTML, trying to clean up with Tidy.', ['exception' => $exception, 'legacy_response' => $exception->getXmlInput()]); |
| 45 | + |
| 46 | + return new XPathHelper($this->parser, tidy_repair_string($content, ['output-xhtml' => true], 'utf8')); |
| 47 | + } else { |
| 48 | + $this->logger->warning('Failed to process legacy response as XHTML.', ['exception' => $exception, 'legacy_response' => $exception->getXmlInput()]); |
| 49 | + |
| 50 | + throw $exception; |
| 51 | + } |
| 52 | + } |
31 | 53 | } |
32 | 54 | } |
0 commit comments