SwatchAttributeOptionAddTest.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Swatches\Model;
  7. use Magento\Catalog\Api\ProductAttributeOptionManagementInterface;
  8. use Magento\Eav\Api\Data\AttributeOptionInterface;
  9. use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory;
  10. /**
  11. * Test add option of swatch attribute
  12. *
  13. */
  14. class SwatchAttributeOptionAddTest extends \PHPUnit\Framework\TestCase
  15. {
  16. /**
  17. * @var \Magento\Framework\ObjectManagerInterface
  18. */
  19. private $objectManager;
  20. protected function setUp()
  21. {
  22. $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
  23. }
  24. /**
  25. * @magentoAppArea adminhtml
  26. * @magentoDbIsolation enabled
  27. * @magentoDataFixture Magento/Swatches/_files/swatch_attribute.php
  28. */
  29. public function testSwatchOptionAdd()
  30. {
  31. /** @var \Magento\Catalog\Api\Data\ProductAttributeInterface $attribute */
  32. $attribute = $this->objectManager
  33. ->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class)
  34. ->load('color_swatch', 'attribute_code');
  35. $optionsPerAttribute = 3;
  36. $data['options']['option'] = array_reduce(
  37. range(10, $optionsPerAttribute),
  38. function ($values, $index) use ($optionsPerAttribute) {
  39. $values[] = [
  40. 'label' => 'option ' . $index,
  41. 'value' => 'option_' . $index
  42. ];
  43. return $values;
  44. },
  45. []
  46. );
  47. /** @var AttributeOptionInterface[] $options */
  48. $options = [];
  49. foreach ($data['options']['option'] as $optionData) {
  50. $options[] = $this->objectManager
  51. ->get(AttributeOptionInterfaceFactory::class)
  52. ->create(['data' => $optionData]);
  53. }
  54. /** @var ProductAttributeOptionManagementInterface $optionManagement */
  55. $optionManagement = $this->objectManager->get(ProductAttributeOptionManagementInterface::class);
  56. foreach ($options as $option) {
  57. $optionManagement->add(
  58. $attribute->getAttributeCode(),
  59. $option
  60. );
  61. }
  62. $items = $optionManagement->getItems($attribute->getAttributeCode());
  63. array_walk(
  64. $items,
  65. function (&$item) {
  66. /** @var AttributeOptionInterface $item */
  67. $item = $item->getLabel();
  68. }
  69. );
  70. foreach ($options as $option) {
  71. $this->assertTrue(in_array($option->getLabel(), $items));
  72. }
  73. }
  74. }