Skip to content

2.2 develop 11032 Unable to add new options to swatch attribute #11628

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 218 additions & 0 deletions app/code/Magento/Swatches/Plugin/Catalog/AddSwatchDataToAddOption.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\Swatches\Plugin\Catalog;

use Magento\Catalog\Model\Product;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Model\Config;
use Magento\Eav\Model\Entity\Attribute\OptionManagement;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory as OptionCollectionFactory;
use Magento\Swatches\Helper\Data as SwatchHelper;

/**
* Class AddSwatchDataToAddOption
*
* @package Magento\Swatches\Plugin\Catalog
*/
class AddSwatchDataToAddOption
{
const SWATCH_VISUAL = 'visual';
const SWATCH_TEXT = 'text';
const PREFIX_OPTION = 'option';
const PREFIX_SWATCH = 'swatch';

/**
* @var Config
*/
private $eavConfig;

/**
* @var SwatchHelper
*/
private $swatchHelper;

/**
* @var OptionCollectionFactory
*/
private $optionCollectionFactory;

/**
* @param Config $eavConfig
* @param SwatchHelper $swatchHelper
* @param OptionCollectionFactory $attrOptionCollectionFactory
*/
public function __construct(
Config $eavConfig,
SwatchHelper $swatchHelper,
OptionCollectionFactory $attrOptionCollectionFactory
) {
$this->eavConfig = $eavConfig;
$this->swatchHelper = $swatchHelper;
$this->optionCollectionFactory = $attrOptionCollectionFactory;
}

/**
* @param OptionManagement $subject
* @param int $entityType
* @param string $attributeCode
* @param AttributeOptionInterface $option
*
* @return array []
* @throws \Magento\Framework\Exception\LocalizedException
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function beforeAdd(OptionManagement $subject, $entityType, $attributeCode, $option)
{
$attribute = $this->eavConfig->getAttribute(Product::ENTITY, $attributeCode);

if (! $this->isSwatch($attribute)) {
return [$entityType, $attributeCode, $option];
}

$swatchType = $this->getSwatchType($attribute);
$optionKey = self::PREFIX_OPTION . $swatchType;
$swatchKey = self::PREFIX_SWATCH . $swatchType;

if ($attribute->getData($optionKey) !== null || $attribute->getData($swatchKey) !== null) {
return [$entityType, $attributeCode, $option];
}

$optionId = $option->getValue();
$optionOrder = $option->getSortOrder();
$prefix = $optionId;
if ($optionId === '') {
$attributeData = $this->prepareAttributeDataForNewOption($attribute->getAttributeId(), $optionKey);
$optionId = count($attributeData[$optionKey]['value']);
if ($optionOrder === null) {
$optionOrder = $optionId + 1;
}
$prefix = 'option_' . $optionId;
$option->setValue($prefix);
}

$storeLabels = $option->getStoreLabels();
$attributeData[$optionKey]['delete'][$prefix] = '';
$attributeData[$optionKey]['order'][$prefix] = $optionOrder;
if ($swatchType === self::SWATCH_VISUAL) {
$attributeData[$swatchKey]['value'][$prefix] = '';
}
foreach ($storeLabels as $storeLabel) {
$attributeData[$optionKey]['value'][$prefix][$storeLabel->getStoreId()] = $storeLabel->getLabel();
if ($swatchType === self::SWATCH_TEXT) {
$attributeData[$swatchKey]['value'][$prefix][$storeLabel->getStoreId()] = $storeLabel->getLabel();
}
}
$attribute->addData($attributeData);

return [$entityType, $attributeCode, $option];
}

/**
* @param $attribute
*
* @return boolean
*/
private function isSwatch($attribute)
{
if ($this->swatchHelper->isVisualSwatch($attribute)) {
return true;
} elseif ($this->swatchHelper->isTextSwatch($attribute)) {
return true;
}

return false;
}

/**
* @param $attribute
*
* @return null|string
*/
private function getSwatchType($attribute)
{
if ($this->swatchHelper->isVisualSwatch($attribute)) {
return self::SWATCH_VISUAL;
} elseif ($this->swatchHelper->isTextSwatch($attribute)) {
return self::SWATCH_TEXT;
}

return null;
}

/**
* @param int $attributeId
* @param string $optionKey
*
* @return array
*/
private function prepareAttributeDataForNewOption($attributeId, $optionKey)
{
$options = $this->getOptionsByAttributeIdWithSortOrder($attributeId);
return $this->getOptionsForSwatch($options, $optionKey);
}

/**
* @param [] $options
* @param string $optionKey
*
* @return array
*/
private function getOptionsForSwatch(array $options, $optionKey)
{
$optionsArray = [];

if (count($options) === 0) {
$optionsArray[$optionKey]['value'] = [];
$optionsArray[$optionKey]['delete'] = [];

return $optionsArray;
}

foreach ($options as $sortOrder => $optionId) {
$optionsArray[$optionKey]['value'][$optionId] = $this->getStoreLabels($optionId);
$optionsArray[$optionKey]['delete'][$optionId] = '';
$optionsArray[$optionKey]['order'][$optionId] = (string)$sortOrder;
}

return $optionsArray;
}

/**
* @param int $optionId
*
* @return array
*/
private function getStoreLabels($optionId)
{
$optionCollectionFactory = $this->optionCollectionFactory->create();
$connection = $optionCollectionFactory->getConnection();
$optionValueTable = $optionCollectionFactory->getTable('eav_attribute_option_value');
$select = $connection->select()->from(
['eaov' => $optionValueTable],
[]
)->where('option_id = ?', $optionId)->columns(['store_id', 'value']);

return $connection->fetchPairs($select);
}

/**
* @param int $attributeId
*
* @return array
*/
private function getOptionsByAttributeIdWithSortOrder($attributeId)
{
$optionCollectionFactory = $this->optionCollectionFactory->create();
$options = $optionCollectionFactory
->setAttributeFilter($attributeId)
->setPositionOrder()
->addFieldToSelect('option_id')
->getAllIds();

return array_values($options);
}
}
3 changes: 3 additions & 0 deletions app/code/Magento/Swatches/etc/di.xml
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,7 @@
</argument>
</arguments>
</type>
<type name="Magento\Eav\Model\Entity\Attribute\OptionManagement">
<plugin name="addSwatchDataToAddOption" type="Magento\Swatches\Plugin\Catalog\AddSwatchDataToAddOption" />
</type>
</config>
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Swatches\Api;

use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Api\Data\AttributeOptionLabelInterface;
use Magento\TestFramework\TestCase\WebapiAbstract;

class ProductAttributeOptionManagementInterfaceTest extends WebapiAbstract
{
const SERVICE_NAME = 'catalogProductAttributeOptionManagementV1';
const SERVICE_VERSION = 'V1';
const RESOURCE_PATH = '/V1/products/attributes';

/**
* @magentoApiDataFixture Magento/Swatches/_files/swatch_attribute.php
* @dataProvider addDataProvider
*/
public function testAdd($optionData)
{
$testAttributeCode = 'color_swatch';
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $testAttributeCode . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'add',
],
];

$response = $this->_webApiCall(
$serviceInfo,
[
'attributeCode' => $testAttributeCode,
'option' => $optionData,
]
);

$this->assertTrue($response);
$updatedData = $this->getAttributeOptions($testAttributeCode);
$lastOption = array_pop($updatedData);
$this->assertEquals(
$optionData[AttributeOptionInterface::STORE_LABELS][1][AttributeOptionLabelInterface::LABEL],
$lastOption['label']
);
}

/**
* @return array
*/
public function addDataProvider()
{
$optionPayload = [
AttributeOptionInterface::LABEL => 'new color',
AttributeOptionInterface::SORT_ORDER => 100,
AttributeOptionInterface::IS_DEFAULT => true,
AttributeOptionInterface::STORE_LABELS => [
[
AttributeOptionLabelInterface::LABEL => 'new color',
AttributeOptionLabelInterface::STORE_ID => 0,
],
[
AttributeOptionLabelInterface::LABEL => 'DE label',
AttributeOptionLabelInterface::STORE_ID => 1,
],
],
AttributeOptionInterface::VALUE => ''
];

return [
'option_without_value_node' => [
$optionPayload
]
];
}

/**
* @param $testAttributeCode
* @return array|bool|float|int|string
*/
private function getAttributeOptions($testAttributeCode)
{
$serviceInfo = [
'rest' => [
'resourcePath' => self::RESOURCE_PATH . '/' . $testAttributeCode . '/options',
'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
],
'soap' => [
'service' => self::SERVICE_NAME,
'serviceVersion' => self::SERVICE_VERSION,
'operation' => self::SERVICE_NAME . 'getItems',
],
];
return $this->_webApiCall($serviceInfo, ['attributeCode' => $testAttributeCode]);
}
}