swatch_attribute.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. use Magento\Eav\Api\Data\AttributeOptionInterface;
  7. /** @var \Magento\Framework\ObjectManagerInterface $objectManager */
  8. $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
  9. $data = [
  10. 'is_required' => 1,
  11. 'is_visible_on_front' => 1,
  12. 'is_visible_in_advanced_search' => 0,
  13. 'attribute_code' => 'color_swatch',
  14. 'backend_type' => '',
  15. 'is_searchable' => 0,
  16. 'is_filterable' => 0,
  17. 'is_filterable_in_search' => 0,
  18. 'frontend_label' => 'Attribute ',
  19. 'entity_type_id' => 4
  20. ];
  21. $optionsPerAttribute = 3;
  22. $data['frontend_input'] = 'swatch_visual';
  23. $data['swatch_input_type'] = 'visual';
  24. $data['swatchvisual']['value'] = array_reduce(
  25. range(1, $optionsPerAttribute),
  26. function ($values, $index) use ($optionsPerAttribute) {
  27. $values['option_' . $index] = '#'
  28. . str_repeat(
  29. dechex(255 * $index / $optionsPerAttribute),
  30. 3
  31. );
  32. return $values;
  33. },
  34. []
  35. );
  36. $data['optionvisual']['value'] = array_reduce(
  37. range(1, $optionsPerAttribute),
  38. function ($values, $index) use ($optionsPerAttribute) {
  39. $values['option_' . $index] = ['option ' . $index];
  40. return $values;
  41. },
  42. []
  43. );
  44. $data['options']['option'] = array_reduce(
  45. range(1, $optionsPerAttribute),
  46. function ($values, $index) use ($optionsPerAttribute) {
  47. $values[] = [
  48. 'label' => 'option ' . $index,
  49. 'value' => 'option_' . $index,
  50. ];
  51. return $values;
  52. },
  53. []
  54. );
  55. $options = [];
  56. foreach ($data['options']['option'] as $optionData) {
  57. $options[] = $objectManager->get(AttributeOptionInterface::class)
  58. ->setLabel($optionData['label'])
  59. ->setValue($optionData['value']);
  60. }
  61. $attribute = $objectManager->create(
  62. \Magento\Catalog\Api\Data\ProductAttributeInterface::class,
  63. ['data' => $data]
  64. );
  65. $attribute->setOptions($options);
  66. $attribute->save();