ImageExtractor.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Catalog\Model;
  7. use Magento\Catalog\Helper\Image;
  8. use Magento\Catalog\Model\Product\Attribute\Backend\Media\ImageEntryConverter;
  9. use Magento\Framework\View\Xsd\Media\TypeDataExtractorInterface;
  10. /**
  11. * Image extractor from xml configuration
  12. */
  13. class ImageExtractor implements TypeDataExtractorInterface
  14. {
  15. /**
  16. * Extract configuration data of images from the DOM structure
  17. *
  18. * @param \DOMElement $mediaNode
  19. * @param string $mediaParentTag
  20. * @return array
  21. * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  22. */
  23. public function process(\DOMElement $mediaNode, $mediaParentTag)
  24. {
  25. $result = [];
  26. /** @var \DOMElement $node */
  27. $moduleNameImage = $mediaNode->getAttribute('module');
  28. foreach ($mediaNode->getElementsByTagName(ImageEntryConverter::MEDIA_TYPE_CODE) as $node) {
  29. $imageId = $node->getAttribute('id');
  30. $result[$mediaParentTag][$moduleNameImage][Image::MEDIA_TYPE_CONFIG_NODE][$imageId]['type']
  31. = $node->getAttribute('type');
  32. foreach ($node->childNodes as $attribute) {
  33. if ($attribute->nodeType != XML_ELEMENT_NODE) {
  34. continue;
  35. }
  36. $attributeTagName = $attribute->tagName;
  37. if ((bool)$attribute->getAttribute('xsi:nil') !== true) {
  38. if ($attributeTagName === 'background') {
  39. $nodeValue = $this->processImageBackground($attribute->nodeValue);
  40. } elseif ($attributeTagName === 'width' || $attributeTagName === 'height') {
  41. $nodeValue = (int) $attribute->nodeValue;
  42. } elseif ($attributeTagName === 'constrain'
  43. || $attributeTagName === 'aspect_ratio'
  44. || $attributeTagName === 'frame'
  45. || $attributeTagName === 'transparency'
  46. ) {
  47. $nodeValue = in_array($attribute->nodeValue, [true, 1, 'true', '1'], true) ?? false;
  48. } else {
  49. $nodeValue = $attribute->nodeValue;
  50. }
  51. } else {
  52. $nodeValue = null;
  53. }
  54. $result[$mediaParentTag][$moduleNameImage][Image::MEDIA_TYPE_CONFIG_NODE][$imageId][$attribute->tagName]
  55. = $nodeValue;
  56. }
  57. }
  58. return $result;
  59. }
  60. /**
  61. * Convert rgb background string into array
  62. *
  63. * @param string $backgroundString
  64. * @return int[]
  65. */
  66. private function processImageBackground($backgroundString)
  67. {
  68. $pattern = '#\[(\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\]#';
  69. $backgroundArray = [];
  70. if (preg_match($pattern, $backgroundString, $backgroundArray)) {
  71. array_shift($backgroundArray);
  72. $backgroundArray = array_map('intval', $backgroundArray);
  73. }
  74. return $backgroundArray;
  75. }
  76. }