XmlValidator.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Dhl\Model\Validator;
  7. use Magento\Sales\Exception\DocumentValidationException;
  8. /**
  9. * Validates XML responses from DHL's web service
  10. */
  11. class XmlValidator
  12. {
  13. /**
  14. * @var \Magento\Framework\Xml\Security
  15. */
  16. private $xmlSecurity;
  17. /**
  18. * @var ResponseErrorProcessor
  19. */
  20. private $errorProcessor;
  21. /**
  22. * Initialize XmlValidator dependencies
  23. *
  24. * @param \Magento\Framework\Xml\Security $xmlSecurity
  25. * @param ResponseErrorProcessor $errorProcessor
  26. */
  27. public function __construct(
  28. \Magento\Framework\Xml\Security $xmlSecurity,
  29. ResponseErrorProcessor $errorProcessor
  30. ) {
  31. $this->xmlSecurity = $xmlSecurity;
  32. $this->errorProcessor = $errorProcessor;
  33. }
  34. /**
  35. * Validate DHL XML responses
  36. *
  37. * @param string $xmlResponse
  38. * @param bool $isShippingLabel
  39. * @return void
  40. * @throws DocumentValidationException
  41. */
  42. public function validate($xmlResponse, $isShippingLabel = false)
  43. {
  44. if (strlen(trim($xmlResponse)) > 0 && strpos(trim($xmlResponse), '<?xml') === 0) {
  45. if (!$this->xmlSecurity->scan($xmlResponse)) {
  46. throw new DocumentValidationException(__('The security validation of the XML document has failed.'));
  47. }
  48. $xml = simplexml_load_string($xmlResponse, \Magento\Shipping\Model\Simplexml\Element::class);
  49. if (in_array($xml->getName(), ['ErrorResponse', 'ShipmentValidateErrorResponse'])
  50. || isset($xml->GetQuoteResponse->Note->Condition)
  51. ) {
  52. /** @var \Magento\Framework\Phrase $exceptionPhrase */
  53. $exceptionPhrase = $this->errorProcessor->process($xml, $isShippingLabel);
  54. throw new DocumentValidationException($exceptionPhrase, null, $exceptionPhrase->getArguments()[0]);
  55. }
  56. } else {
  57. throw new DocumentValidationException(__('The response is in the wrong format'));
  58. }
  59. }
  60. }