ConfigurableAttributeData.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\ConfigurableProduct\Model;
  7. use Magento\Catalog\Model\Product;
  8. use Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute;
  9. /**
  10. * Class ConfigurableAttributeData
  11. * @api
  12. * @since 100.0.2
  13. */
  14. class ConfigurableAttributeData
  15. {
  16. /**
  17. * Get product attributes
  18. *
  19. * @param Product $product
  20. * @param array $options
  21. * @return array
  22. */
  23. public function getAttributesData(Product $product, array $options = [])
  24. {
  25. $defaultValues = [];
  26. $attributes = [];
  27. foreach ($product->getTypeInstance()->getConfigurableAttributes($product) as $attribute) {
  28. $attributeOptionsData = $this->getAttributeOptionsData($attribute, $options);
  29. if ($attributeOptionsData) {
  30. $productAttribute = $attribute->getProductAttribute();
  31. $attributeId = $productAttribute->getId();
  32. $attributes[$attributeId] = [
  33. 'id' => $attributeId,
  34. 'code' => $productAttribute->getAttributeCode(),
  35. 'label' => $productAttribute->getStoreLabel($product->getStoreId()),
  36. 'options' => $attributeOptionsData,
  37. 'position' => $attribute->getPosition(),
  38. ];
  39. $defaultValues[$attributeId] = $this->getAttributeConfigValue($attributeId, $product);
  40. }
  41. }
  42. return [
  43. 'attributes' => $attributes,
  44. 'defaultValues' => $defaultValues,
  45. ];
  46. }
  47. /**
  48. * @param Attribute $attribute
  49. * @param array $config
  50. * @return array
  51. */
  52. protected function getAttributeOptionsData($attribute, $config)
  53. {
  54. $attributeOptionsData = [];
  55. foreach ($attribute->getOptions() as $attributeOption) {
  56. $optionId = $attributeOption['value_index'];
  57. $attributeOptionsData[] = [
  58. 'id' => $optionId,
  59. 'label' => $attributeOption['label'],
  60. 'products' => isset($config[$attribute->getAttributeId()][$optionId])
  61. ? $config[$attribute->getAttributeId()][$optionId]
  62. : [],
  63. ];
  64. }
  65. return $attributeOptionsData;
  66. }
  67. /**
  68. * @param int $attributeId
  69. * @param Product $product
  70. * @return mixed|null
  71. */
  72. protected function getAttributeConfigValue($attributeId, $product)
  73. {
  74. return $product->hasPreconfiguredValues()
  75. ? $product->getPreconfiguredValues()->getData('super_attribute/' . $attributeId)
  76. : null;
  77. }
  78. }