ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,238 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Block\Product\Image;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\Store;
use Magento\Swatches\Model\Plugin\ProductImage;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for displaying configurable product image with swatch attributes.
*
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoAppArea frontend
*/
class ListProductTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var ProductAttributeRepositoryInterface
*/
private $attributeRepository;
/**
* @var RequestInterface
*/
private $request;
/**
* @var LayoutInterface
*/
private $layout;
/**
* @var ListProduct
*/
private $listingBlock;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productResource = $this->objectManager->get(ProductResource::class);
$this->attributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$this->request = $this->objectManager->get(RequestInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->listingBlock = $this->layout->createBlock(ListProduct::class);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_text_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @dataProvider getImageDataProvider
* @param array $images
* @param string $area
* @param array $expectation
* @return void
*/
public function testGetImageForTextSwatchConfigurable(array $images, string $area, array $expectation): void
{
$this->updateAttributePreviewImageFlag('text_swatch_attribute');
$this->addFilterToRequest('text_swatch_attribute', 'option 1');
$this->assertProductImage($images, $area, $expectation);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_visual_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @dataProvider getImageDataProvider
* @param array $images
* @param string $area
* @param array $expectation
* @return void
*/
public function testGetImageForVisualSwatchConfigurable(array $images, string $area, array $expectation): void
{
$this->updateAttributePreviewImageFlag('visual_swatch_attribute');
$this->addFilterToRequest('visual_swatch_attribute', 'option 1');
$this->assertProductImage($images, $area, $expectation);
}
/**
* @return array
*/
public function getImageDataProvider(): array
{
return [
'without_images_and_display_grid' => [
'images' => [],
'display_area' => ProductImage::CATEGORY_PAGE_GRID_LOCATION,
'expectation' => ['image_url' => 'placeholder/small_image.jpg', 'label' => 'Configurable Product'],
],
'without_images_and_display_list' => [
'images' => [],
'display_area' => ProductImage::CATEGORY_PAGE_LIST_LOCATION,
'expectation' => ['image_url' => 'placeholder/small_image.jpg', 'label' => 'Configurable Product'],
],
'with_image_on_configurable_and_display_grid' => [
'images' => ['configurable' => '/m/a/magento_image.jpg'],
'display_area' => ProductImage::CATEGORY_PAGE_GRID_LOCATION,
'expectation' => ['image_url' => '/m/a/magento_image.jpg', 'label' => 'Image Alt Text'],
],
'with_image_on_configurable_and_display_list' => [
'images' => ['configurable' => '/m/a/magento_image.jpg'],
'display_area' => ProductImage::CATEGORY_PAGE_LIST_LOCATION,
'expectation' => ['image_url' => '/m/a/magento_image.jpg', 'label' => 'Image Alt Text'],
],
'with_image_on_simple' => [
'images' => ['simple_option_1' => '/m/a/magento_small_image.jpg'],
'display_area' => ProductImage::CATEGORY_PAGE_GRID_LOCATION,
'expectation' => ['image_url' => '/m/a/magento_small_image.jpg', 'label' => 'Image Alt Text'],
],
'with_image_on_simple_and_configurable' => [
'images' => [
'configurable' => '/m/a/magento_image.jpg',
'simple_option_1' => '/m/a/magento_small_image.jpg',
],
'display_area' => ProductImage::CATEGORY_PAGE_GRID_LOCATION,
'expectation' => ['image_url' => '/m/a/magento_small_image.jpg', 'label' => 'Image Alt Text'],
],
];
}
/**
* Asserts image data.
*
* @param array $images
* @param string $area
* @param array $expectation
* @return void
*/
private function assertProductImage(array $images, string $area, array $expectation): void
{
$this->updateProductImages($images);
$productImage = $this->listingBlock->getImage($this->productRepository->get('configurable'), $area);
$this->assertInstanceOf(Image::class, $productImage);
$this->assertEquals($productImage->getCustomAttributes(), []);
$this->assertEquals($productImage->getClass(), 'product-image-photo');
$this->assertEquals($productImage->getRatio(), 1.25);
$this->assertEquals($productImage->getLabel(), $expectation['label']);
$this->assertStringEndsWith($expectation['image_url'], $productImage->getImageUrl());
$this->assertEquals($productImage->getWidth(), 240);
$this->assertEquals($productImage->getHeight(), 300);
}
/**
* Updates products images.
*
* @param array $images
* @return void
*/
private function updateProductImages(array $images): void
{
foreach ($images as $sku => $imageName) {
$product = $this->productRepository->get($sku);
$product->setStoreId(Store::DEFAULT_STORE_ID)
->setImage($imageName)
->setSmallImage($imageName)
->setThumbnail($imageName)
->setData(
'media_gallery',
[
'images' => [
[
'file' => $imageName,
'position' => 1,
'label' => 'Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
],
],
]
)
->setCanSaveCustomOptions(true);
$this->productResource->save($product);
}
}
/**
* Updates attribute "Update Product Preview Image" flag.
*
* @param string $attributeCode
* @return void
*/
private function updateAttributePreviewImageFlag(string $attributeCode): void
{
$attribute = $this->attributeRepository->get($attributeCode);
$attribute->setData('update_product_preview_image', 1);
$this->attributeRepository->save($attribute);
}
/**
* Adds attribute param to request.
*
* @param string $attributeCode
* @param string $optionLabel
* @return void
*/
private function addFilterToRequest(string $attributeCode, string $optionLabel): void
{
$attribute = $this->attributeRepository->get($attributeCode);
$this->request->setParams(
[$attributeCode => $attribute->getSource()->getOptionId($optionLabel)]
);
}
}
@@ -0,0 +1,109 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\Renderer\Configurable\Listing;
use Magento\Swatches\Block\Product\Renderer\Configurable\ProductPageViewTest;
use Magento\Swatches\Block\Product\Renderer\Listing\Configurable;
/**
* Test class to check configurable product with swatch attributes view behaviour on category page
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class CategoryPageViewTest extends ProductPageViewTest
{
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->block = $this->layout->createBlock(Configurable::class);
$this->template = 'Magento_Swatches::product/listing/renderer.phtml';
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_visual_swatch_attribute.php
*
* @dataProvider expectedVisualSwatchDataProvider
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @return void
*/
public function testCategoryPageVisualSwatchAttributeView(array $expectedConfig, array $expectedSwatchConfig): void
{
$this->checkProductViewCategoryPage($expectedConfig, $expectedSwatchConfig, ['visual_swatch_attribute']);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_text_swatch_attribute.php
*
* @dataProvider expectedTextSwatchDataProvider
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @return void
*/
public function testCategoryPageTextSwatchAttributeView(array $expectedConfig, array $expectedSwatchConfig): void
{
$this->checkProductViewCategoryPage($expectedConfig, $expectedSwatchConfig, ['text_swatch_attribute']);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_two_attributes.php
*
* @dataProvider expectedTwoAttributesProvider
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @return void
*/
public function testCategoryPageTwoAttributesView(array $expectedConfig, array $expectedSwatchConfig): void
{
$this->checkProductViewCategoryPage(
$expectedConfig,
$expectedSwatchConfig,
['visual_swatch_attribute', 'text_swatch_attribute']
);
}
/**
* Check configurable product view on category view page
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @param array $attributes
* @return void
*/
private function checkProductViewCategoryPage(
array $expectedConfig,
array $expectedSwatchConfig,
array $attributes
): void {
$this->setAttributeUsedInProductListing($attributes);
$this->checkProductView($expectedConfig, $expectedSwatchConfig);
}
/**
* Set used in product listing attributes value to true
*
* @param array $attributeCodes
* @return void
*/
private function setAttributeUsedInProductListing(array $attributeCodes): void
{
foreach ($attributeCodes as $attributeCode) {
$attribute = $this->productAttributeRepository->get($attributeCode);
$attribute->setUsedInProductListing('1');
$this->productAttributeRepository->save($attribute);
}
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\Renderer\Configurable\Listing;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Module\Manager;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Swatches\Block\Product\Renderer\Listing\Configurable;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for configurable products options block with swatch attribute.
*
* @magentoDbIsolation enabled
* @magentoAppArea frontend
*/
class ConfigurableTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @var Configurable
*/
private $block;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var RequestInterface
*/
private $request;
/**
* @inheritdoc
*/
public static function setUpBeforeClass(): void
{
$objectManager = Bootstrap::getObjectManager();
/** @var Manager $moduleManager */
$moduleManager = $objectManager->get(Manager::class);
if (!$moduleManager->isEnabled('Magento_Catalog')) {
self::markTestSkipped('Magento_Catalog module disabled.');
}
}
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->serializer = $this->objectManager->get(SerializerInterface::class);
$this->productAttributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(Configurable::class);
$this->request = $this->objectManager->get(RequestInterface::class);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_with_images.php
* @return void
*/
public function testPreSelectedGalleryConfig(): void
{
$product = $this->productRepository->get('configurable');
$this->block->setProduct($product);
$configurableAttribute = $this->productAttributeRepository->get('visual_swatch_attribute');
$this->request->setQueryValue('visual_swatch_attribute', $configurableAttribute->getOptions()[1]->getValue());
$jsonConfig = $this->serializer->unserialize($this->block->getJsonConfig());
$this->assertArrayHasKey('preSelectedGallery', $jsonConfig);
$this->assertStringEndsWith('/m/a/magento_image.jpg', $jsonConfig['preSelectedGallery']['large']);
$this->assertStringEndsWith('/m/a/magento_image.jpg', $jsonConfig['preSelectedGallery']['medium']);
$this->assertStringEndsWith('/m/a/magento_image.jpg', $jsonConfig['preSelectedGallery']['small']);
}
}
@@ -0,0 +1,190 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\Renderer\Configurable;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\Data\TierPriceInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Customer\Model\Group;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\Result\Page;
use Magento\Swatches\Block\Product\Renderer\Configurable;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Check configurable product price
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoAppArea frontend
*/
class PriceTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Registry */
private $registry;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Page */
private $page;
/** @var SerializerInterface */
private $json;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->registry = $this->objectManager->get(Registry::class);
$this->page = $this->objectManager->get(Page::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->json = $this->objectManager->get(SerializerInterface::class);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->registry->unregister('product');
parent::tearDown();
}
/**
* @dataProvider childProductsDataProvider
* @magentoDataFixture Magento/Swatches/_files/configurable_product_visual_swatch_attribute.php
* @magentoCache config disabled
*
* @param array $updateData
* @param array $expectedData
* @return void
*/
public function testConfigurableOptionPrices(array $updateData, array $expectedData): void
{
$this->updateProducts($updateData);
$product = $this->productRepository->get('configurable');
$this->registerProduct($product);
$configurableOptions = $this->getProductSwatchOptionsBlock()->getJsonConfig();
$optionsData = $this->json->unserialize($configurableOptions);
$this->assertArrayHasKey('optionPrices', $optionsData);
$this->assertEquals($expectedData, array_values($optionsData['optionPrices']));
}
/**
* @return array
*/
public function childProductsDataProvider(): array
{
return [
[
'update_data' => [
'simple_option_1' => [
'special_price' => 50,
],
'simple_option_2' => [
'special_price' => 58.55,
],
'simple_option_3' => [
'tier_price' => [
[
'website_id' => 0,
'cust_group' => Group::CUST_GROUP_ALL,
'price_qty' => 1,
'value_type' => TierPriceInterface::PRICE_TYPE_FIXED,
'price' => 75,
],
],
],
],
'expected_data' => [
[
'baseOldPrice' => ['amount' => 150],
'oldPrice' => ['amount' => 150],
'basePrice' => ['amount' => 50],
'finalPrice' => ['amount' => 50],
'tierPrices' => [],
'msrpPrice' => ['amount' => null],
],
[
'baseOldPrice' => ['amount' => 150],
'oldPrice' => ['amount' => 150],
'basePrice' => ['amount' => 58.55],
'finalPrice' => ['amount' => 58.55],
'tierPrices' => [],
'msrpPrice' => ['amount' => null],
],
[
'baseOldPrice' => ['amount' => 150],
'oldPrice' => ['amount' => 150],
'basePrice' => ['amount' => 75],
'finalPrice' => ['amount' => 75],
'tierPrices' => [],
'msrpPrice' => ['amount' => null],
],
]
],
];
}
/**
* Update products.
*
* @param array $data
* @return void
*/
private function updateProducts(array $data): void
{
foreach ($data as $sku => $updateData) {
$product = $this->productRepository->get($sku);
$product->addData($updateData);
$this->productRepository->save($product);
}
}
/**
* Register the product.
*
* @param ProductInterface $product
* @return void
*/
private function registerProduct(ProductInterface $product): void
{
$this->registry->unregister('product');
$this->registry->register('product', $product);
}
/**
* Get product swatch options block.
*
* @return Configurable
*/
private function getProductSwatchOptionsBlock(): Configurable
{
$this->page->addHandle([
'default',
'catalog_product_view',
'catalog_product_view_type_configurable',
]);
$this->page->getLayout()->generateXml();
return $this->page->getLayout()->getChildBlock('product.info.options.wrapper', 'swatch_options');
}
}
@@ -0,0 +1,414 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\Renderer\Configurable;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Swatches\Block\Product\Renderer\Configurable;
use Magento\Swatches\Model\Swatch;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test class to check configurable product with swatch attributes view behaviour on product page
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
class ProductPageViewTest extends TestCase
{
/** @var ObjectManagerInterface */
protected $objectManager;
/** @var Configurable */
protected $block;
/** @var string */
protected $template;
/** @var ProductAttributeRepositoryInterface */
protected $productAttributeRepository;
/** @var LayoutInterface */
protected $layout;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var Registry */
private $registry;
/** @var SerializerInterface */
private $json;
/** @var ProductResource */
private $productResource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->layout = $this->objectManager->get(LayoutInterface::class);
$this->block = $this->layout->createBlock(Configurable::class);
$this->registry = $this->objectManager->get(Registry::class);
$this->json = $this->objectManager->get(SerializerInterface::class);
$this->productAttributeRepository = $this->objectManager->create(ProductAttributeRepositoryInterface::class);
$this->productResource = $this->objectManager->create(ProductResource::class);
$this->template = Configurable::SWATCH_RENDERER_TEMPLATE;
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_text_swatch_attribute.php
*
* @dataProvider expectedTextSwatchDataProvider
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @return void
*/
public function testProductPageTextSwatchAttributeView(array $expectedConfig, array $expectedSwatchConfig): void
{
$this->checkProductView($expectedConfig, $expectedSwatchConfig);
}
/**
* @return array
*/
public function expectedTextSwatchDataProvider(): array
{
return [
[
'json_config' => [
'text_swatch_attribute' => [
'label' => 'Text swatch attribute',
'options' => [
['label' => 'Option 3', 'skus' => ['simple_option_3']],
['label' => 'Option 1', 'skus' => ['simple_option_1']],
['label' => 'Option 2', 'skus' => ['simple_option_2']],
],
],
],
'json_swatch_config' => [
Swatch::SWATCH_INPUT_TYPE_TEXT => [
[
'type' => Swatch::SWATCH_TYPE_TEXTUAL,
'value' => 'Swatch 3',
'label' => 'Option 3',
],
[
'type' => Swatch::SWATCH_TYPE_TEXTUAL,
'value' => 'Swatch 1',
'label' => 'Option 1',
],
[
'type' => Swatch::SWATCH_TYPE_TEXTUAL,
'value' => 'Swatch 2',
'label' => 'Option 2',
],
'additional_data' => "{\"swatch_input_type\":\"text\"}",
],
],
],
];
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_visual_swatch_attribute.php
*
* @dataProvider expectedVisualSwatchDataProvider
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @return void
*/
public function testProductPageVisualSwatchAttributeView(array $expectedConfig, array $expectedSwatchConfig): void
{
$this->checkProductView($expectedConfig, $expectedSwatchConfig);
}
/**
* @return array
*/
public function expectedVisualSwatchDataProvider(): array
{
return [
[
'json_config' => [
'visual_swatch_attribute' => [
'label' => 'Visual swatch attribute',
'options' => [
['label' => 'option 3', 'skus' => ['simple_option_3']],
['label' => 'option 2', 'skus' => ['simple_option_2']],
['label' => 'option 1', 'skus' => ['simple_option_1']],
],
],
],
'json_swatch_config' => [
Swatch::SWATCH_INPUT_TYPE_VISUAL => [
[
'type' => Swatch::SWATCH_TYPE_VISUAL_COLOR,
'value' => '#555555',
'label' => 'option 1',
],
[
'type' => Swatch::SWATCH_TYPE_VISUAL_COLOR,
'value' => '#aaaaaa',
'label' => 'option 2',
],
[
'type' => Swatch::SWATCH_TYPE_VISUAL_COLOR,
'value' => '#ffffff',
'label' => 'option 3',
],
'additional_data' => "{\"swatch_input_type\":\"visual\"}",
],
],
],
];
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_two_attributes.php
*
* @dataProvider expectedTwoAttributesProvider
*
* @param array $expectedConfig
* @param array $expectedSwatchConfig
* @return void
*/
public function testProductPageTwoAttributesView(array $expectedConfig, array $expectedSwatchConfig): void
{
$this->checkProductView($expectedConfig, $expectedSwatchConfig);
}
/**
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
* @return array
*/
public function expectedTwoAttributesProvider(): array
{
return [
[
'json_config' => [
'visual_swatch_attribute' => [
'label' => 'Visual swatch attribute',
'options' => [
[
'label' => 'option 3',
'skus' => [
'simple_option_3_option_3',
'simple_option_1_option_3',
'simple_option_2_option_3',
],
],
[
'label' => 'option 2',
'skus' => [
'simple_option_3_option_2',
'simple_option_1_option_2',
'simple_option_2_option_2',
],
],
[
'label' => 'option 1',
'skus' => [
'simple_option_3_option_1',
'simple_option_1_option_1',
'simple_option_2_option_1',
],
],
],
],
'text_swatch_attribute' => [
'label' => 'Text swatch attribute',
'options' => [
[
'label' => 'Option 3',
'skus' => [
'simple_option_3_option_1',
'simple_option_3_option_2',
'simple_option_3_option_3',
],
],
[
'label' => 'Option 2',
'skus' => [
'simple_option_2_option_1',
'simple_option_2_option_2',
'simple_option_2_option_3',
],
],
[
'label' => 'Option 1',
'skus' => [
'simple_option_1_option_1',
'simple_option_1_option_2',
'simple_option_1_option_3',
],
],
],
],
],
'json_swatch_config' => [
Swatch::SWATCH_INPUT_TYPE_VISUAL => [
[
'type' => Swatch::SWATCH_TYPE_VISUAL_COLOR,
'value' => '#555555',
'label' => 'option 1',
],
[
'type' => Swatch::SWATCH_TYPE_VISUAL_COLOR,
'value' => '#aaaaaa',
'label' => 'option 2',
],
[
'type' => Swatch::SWATCH_TYPE_VISUAL_COLOR,
'value' => '#ffffff',
'label' => 'option 3',
],
'additional_data' => "{\"swatch_input_type\":\"visual\"}",
],
Swatch::SWATCH_INPUT_TYPE_TEXT => [
[
'type' => Swatch::SWATCH_TYPE_TEXTUAL,
'value' => 'Swatch 3',
'label' => 'Option 3',
],
[
'type' => Swatch::SWATCH_TYPE_TEXTUAL,
'value' => 'Swatch 1',
'label' => 'Option 1',
],
[
'type' => Swatch::SWATCH_TYPE_TEXTUAL,
'value' => 'Swatch 2',
'label' => 'Option 2',
],
'additional_data' => "{\"swatch_input_type\":\"text\"}",
],
],
],
];
}
/**
* Check configurable product view
*
* @param $expectedConfig
* @param $expectedSwatchConfig
* @return void
*/
protected function checkProductView($expectedConfig, $expectedSwatchConfig): void
{
$actualConfig = $this->generateBlockJsonConfigData();
$this->checkResultIsNotEmpty($actualConfig);
$this->assertConfig($actualConfig['json_config'], $expectedConfig);
$this->assertSwatchConfig($actualConfig['json_swatch_config'], $expectedSwatchConfig);
}
/**
* Generate block config data
*
* @return array
*/
private function generateBlockJsonConfigData(): array
{
$product = $this->productRepository->get('configurable');
$this->block->setProduct($product);
$this->block->setTemplate($this->template);
$jsonConfig = $this->json->unserialize($this->block->getJsonConfig())['attributes'] ?? [];
$jsonSwatchConfig = $this->json->unserialize($this->block->getJsonSwatchConfig());
return ['json_config' => $jsonConfig, 'json_swatch_config' => $jsonSwatchConfig];
}
/**
* Assert that correct data was generated
*
* @param array $actualData
* @param array $expectedData
* @return void
*/
private function assertSwatchConfig(array $actualData, array $expectedData): void
{
foreach ($actualData as $actualDataItem) {
$currentType = $this->json->unserialize($actualDataItem['additional_data'])['swatch_input_type'] ?? null;
$this->assertNotNull($currentType);
$this->assertEquals($expectedData[$currentType]['additional_data'], $actualDataItem['additional_data']);
unset($actualDataItem['additional_data']);
foreach ($actualDataItem as $item) {
$this->assertContainsEquals($item, $expectedData[$currentType]);
}
}
}
/**
* Assert that correct swatch data was generated
*
* @param array $actualData
* @param array $expectedData
* @return void
*/
private function assertConfig(array $actualData, array $expectedData): void
{
foreach ($actualData as $actualDataItem) {
$expectedItem = $expectedData[$actualDataItem['code']];
$this->assertEquals($expectedItem['label'], $actualDataItem['label']);
$this->checkOptions($actualDataItem, $expectedItem);
}
}
/**
* Check result is not not empty
*
* @param array $result
*/
private function checkResultIsNotEmpty(array $result): void
{
foreach ($result as $item) {
$this->assertNotEmpty($item);
}
}
/**
* Check attribute options
*
* @param array $actualDataItem
* @param array $expectedItem
* @return void
*/
private function checkOptions(array $actualDataItem, array $expectedItem): void
{
foreach ($expectedItem['options'] as $expectedOption) {
$expectedSkus = array_values($expectedOption['skus']);
$expectedIds = array_values($this->productResource->getProductsIdsBySkus($expectedSkus));
foreach ($actualDataItem['options'] as $option) {
if ($option['label'] === $expectedOption['label']) {
$this->assertEquals(
sort($expectedIds),
sort($option['products']),
'Wrong product linked as option'
);
}
}
}
}
}
@@ -0,0 +1,282 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\Renderer;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Image\UrlBuilder;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\ConfigurableProduct\Block\Product\View\Type\Configurable;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\Store\Model\Store;
use Magento\Swatches\Block\Product\Renderer\Configurable as ConfigurableBlock;
use Magento\Swatches\Helper\Media;
use Magento\Swatches\Model\Swatch;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for configurable products options block with swatch attribute.
*
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
* @magentoAppArea frontend
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ConfigurableTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var SerializerInterface
*/
private $serializer;
/**
* @var Media
*/
private $swatchHelper;
/**
* @var UrlBuilder
*/
private $imageUrlBuilder;
/**
* @var Configurable
*/
private $block;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ProductAttributeRepositoryInterface
*/
private $productAttributeRepository;
/**
* @var ProductResource
*/
private $productResource;
/**
* @var ProductAttributeInterface
*/
private $configurableAttribute;
/**
* @var ProductInterface
*/
private $product;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->serializer = $this->objectManager->get(SerializerInterface::class);
$this->swatchHelper = $this->objectManager->get(Media::class);
$this->imageUrlBuilder = $this->objectManager->get(UrlBuilder::class);
$this->productAttributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$this->configurableAttribute = $this->productAttributeRepository->get('test_configurable');
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->product = $this->productRepository->get('configurable');
$this->productResource = $this->objectManager->get(ProductResource::class);
$this->block = $this->objectManager->get(LayoutInterface::class)->createBlock(ConfigurableBlock::class);
$this->block->setProduct($this->product);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_with_visual_swatch_attribute.php
* @return void
*/
public function testGetJsonSwatchConfig(): void
{
$expectedOptions = $this->getDefaultOptionsList();
$expectedOptions['option 2']['value'] = $this->swatchHelper->getSwatchAttributeImage(
Swatch::SWATCH_IMAGE_NAME,
'/visual_swatch_attribute_option_type_image.jpg'
);
$expectedOptions['option 2']['thumb'] = $this->swatchHelper->getSwatchAttributeImage(
Swatch::SWATCH_THUMBNAIL_NAME,
'/visual_swatch_attribute_option_type_image.jpg'
);
$config = $this->serializer->unserialize($this->block->getJsonSwatchConfig());
$this->assertOptionsData($config, $expectedOptions, ['swatch_input_type' => 'visual']);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_with_visual_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @return void
*/
public function testGetJsonSwatchConfigUsedProductImage(): void
{
$this->updateAttributeUseProductImageFlag();
$this->updateProductImage('simple_option_2', '/m/a/magento_image.jpg');
$expectedOptions = $this->getDefaultOptionsList();
$expectedOptions['option 2']['value'] = $this->imageUrlBuilder->getUrl(
'/m/a/magento_image.jpg',
'swatch_image_base'
);
$expectedOptions['option 2']['thumb'] = $this->imageUrlBuilder->getUrl(
'/m/a/magento_image.jpg',
'swatch_thumb_base'
);
$this->assertOptionsData(
$this->serializer->unserialize($this->block->getJsonSwatchConfig()),
$expectedOptions,
['swatch_input_type' => 'visual', 'use_product_image_for_swatch' => 1]
);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_with_visual_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_image.php
* @return void
*/
public function testGetJsonSwatchConfigUsedWithSwatchImageType(): void
{
$this->updateAttributeUseProductImageFlag();
$this->updateProductImage('simple_option_2', '/m/a/magento_image.jpg', ['swatch_image']);
$expectedOptions = $this->getDefaultOptionsList();
$expectedOptions['option 2']['value'] = $this->imageUrlBuilder->getUrl(
'/m/a/magento_image.jpg',
'swatch_image_base'
);
$expectedOptions['option 2']['thumb'] = $this->imageUrlBuilder->getUrl(
'/m/a/magento_image.jpg',
'swatch_thumb_base'
);
$this->assertOptionsData(
$this->serializer->unserialize($this->block->getJsonSwatchConfig()),
$expectedOptions,
['swatch_input_type' => 'visual', 'use_product_image_for_swatch' => 1]
);
}
/**
* @magentoDataFixture Magento/Swatches/_files/configurable_product_with_visual_swatch_attribute.php
* @return void
*/
public function testGetJsonSwatchConfigUsedEmptyProductImage(): void
{
$this->updateAttributeUseProductImageFlag();
$expectedOptions = $this->getDefaultOptionsList();
$expectedOptions['option 2']['value'] = $this->swatchHelper->getSwatchAttributeImage(
Swatch::SWATCH_IMAGE_NAME,
'/visual_swatch_attribute_option_type_image.jpg'
);
$expectedOptions['option 2']['thumb'] = $this->swatchHelper->getSwatchAttributeImage(
Swatch::SWATCH_THUMBNAIL_NAME,
'/visual_swatch_attribute_option_type_image.jpg'
);
$this->assertOptionsData(
$this->serializer->unserialize($this->block->getJsonSwatchConfig()),
$expectedOptions,
['swatch_input_type' => 'visual', 'use_product_image_for_swatch' => 1]
);
}
/**
* @return array
*/
private function getDefaultOptionsList(): array
{
return [
'option 1' => ['type' => '1', 'value' => '#000000', 'label' => 'option 1'],
'option 2' => ['type' => '2', 'value' => '', 'thumb' => '', 'label' => 'option 2'],
'option 3' => ['type' => '3', 'value' => null, 'label' => 'option 3'],
];
}
/**
* Asserts swatch options data.
*
* @param array $config
* @param array $expectedOptions
* @param array $expectedAdditional
* @return void
*/
private function assertOptionsData(array $config, array $expectedOptions, array $expectedAdditional): void
{
$this->assertNotEmpty($config);
$resultOptions = $config[$this->configurableAttribute->getAttributeId()];
foreach ($expectedOptions as $label => $data) {
$resultOption = $resultOptions[$this->configurableAttribute->getSource()->getOptionId($label)];
$this->assertEquals($data['type'], $resultOption['type']);
$this->assertEquals($data['label'], $resultOption['label']);
$this->assertEquals($data['value'], $resultOption['value']);
if (!empty($data['thumb'])) {
$this->assertEquals($data['thumb'], $resultOption['thumb']);
}
}
$this->assertEquals($expectedAdditional, $this->serializer->unserialize($resultOptions['additional_data']));
}
/**
* Updates attribute 'use_product_image_for_swatch' flag.
*
* @return void
*/
private function updateAttributeUseProductImageFlag(): void
{
$this->configurableAttribute->setData('use_product_image_for_swatch', 1);
$this->configurableAttribute = $this->productAttributeRepository->save($this->configurableAttribute);
}
/**
* Updates Product image.
*
* @param string $sku
* @param string $imageName
* @param array $imageRoles
* @return void
*/
private function updateProductImage(
string $sku,
string $imageName,
array $imageRoles = ['image', 'small_image', 'thumbnail']
): void {
$product = $this->productRepository->get($sku);
$product->setStoreId(Store::DEFAULT_STORE_ID)
->setData(
'media_gallery',
[
'images' => [
[
'file' => $imageName,
'position' => 1,
'label' => 'Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
],
]
]
)
->setCanSaveCustomOptions(true);
foreach ($imageRoles as $role) {
$product->setData($role, $imageName);
}
$this->productResource->save($product);
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\View\Attribute;
use Magento\Catalog\Block\Product\View\Attribute\AbstractAttributeTest;
/**
* Class checks text attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class TextSwatchAttributeTest extends AbstractAttributeTest
{
/**
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('Option 2');
$this->processAttributeView('simple2', $attributeValue, 'Option 2');
}
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('Option 2');
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, 'Option 2');
}
/**
* @return void
*/
public function tesAttributeWithDefaultValueView(): void
{
$this->processDefaultValueAttributeView('simple2', 'Option 1');
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'text_swatch_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getSource()->getOptionId('Option 1');
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Block\Product\View\Attribute;
use Magento\Catalog\Block\Product\View\Attribute\AbstractAttributeTest;
/**
* Class checks visual swatch attribute displaying on frontend
*
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class VisualSwatchAttributeTest extends AbstractAttributeTest
{
/**
* @return void
*/
public function testAttributeView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('option 2');
$this->processAttributeView('simple2', $attributeValue, 'option 2');
}
/**
* @return void
*/
public function testAttributeWithNonDefaultValueView(): void
{
$attributeValue = $this->getAttribute()->getSource()->getOptionId('option 2');
$this->processNonDefaultAttributeValueView('simple2', $attributeValue, 'option 2');
}
/**
* @return void
*/
public function tesAttributeWithDefaultValueView(): void
{
$this->processDefaultValueAttributeView('simple2', 'option 1');
}
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'visual_swatch_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getSource()->getOptionId('option 1');
}
}
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Swatches\Controller\Adminhtml\Iframe;
use Magento\TestFramework\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class ShowTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* Check Swatch Acl Access
*/
public function testAclAccess()
{
/** @var $acl \Magento\Framework\Acl */
$acl = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Acl\Builder::class)
->getAcl();
$acl->allow(
Bootstrap::ADMIN_ROLE_ID,
\Magento\Swatches\Controller\Adminhtml\Iframe\Show::ADMIN_RESOURCE
);
$this->dispatch('backend/swatches/iframe/show/');
$this->assertEquals(200, $this->getResponse()->getHttpResponseCode());
$this->assertStringNotContainsString(
'Sorry, you need permissions to view this content.',
$this->getResponse()->getBody()
);
}
/**
* Check Swatch Acl Access Denied
*/
public function testAclAccessDenied()
{
/** @var $acl \Magento\Framework\Acl */
$acl = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Acl\Builder::class)
->getAcl();
$acl->deny(
Bootstrap::ADMIN_ROLE_ID,
\Magento\Swatches\Controller\Adminhtml\Iframe\Show::ADMIN_RESOURCE
);
$this->dispatch('backend/swatches/iframe/show/');
$this->assertEquals(403, $this->getResponse()->getHttpResponseCode());
$this->assertStringContainsString(
'Sorry, you need permissions to view this content.',
$this->getResponse()->getBody()
);
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Delete;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Delete\AbstractDeleteAttributeControllerTest;
/**
* Delete catalog product attributes with input types like "swatch_text" and "swatch_visual".
* Attributes from Magento_Swatches module.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class SwatchesAttributesControllerTest extends AbstractDeleteAttributeControllerTest
{
/**
* Assert that attribute with input type "swatch_text" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
*
* @return void
*/
public function testDeleteSwatchTextAttribute(): void
{
$this->dispatchDeleteAttribute('text_swatch_attribute');
$this->assertAttributeIsDeleted('text_swatch_attribute');
}
/**
* Assert that attribute with input type "swatch_visual" will be deleted
* after dispatch delete product attribute action.
*
* @magentoDataFixture Magento/Swatches/_files/swatch_attribute.php
*
* @return void
*/
public function testDeleteSwatchVisualAttribute(): void
{
$this->dispatchDeleteAttribute('color_swatch');
$this->assertAttributeIsDeleted('color_swatch');
}
}
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Save\InputType;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\AbstractSaveAttributeTest;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
/**
* Test cases related to create attribute with input type text swatch.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class TextSwatchTest extends AbstractSaveAttributeTest
{
/**
* Test create attribute and compare attribute data and input data.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\TextSwatch::getAttributeDataWithCheckArray
*
* @param array $attributePostData
* @param array $checkArray
* @return void
*/
public function testCreateAttribute(array $attributePostData, array $checkArray): void
{
$this->createAttributeUsingDataAndAssert($attributePostData, $checkArray);
}
/**
* Test create attribute with error.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\TextSwatch::getAttributeDataWithErrorMessage
*
* @param array $attributePostData
* @param string $errorMessage
* @return void
*/
public function testCreateAttributeWithError(array $attributePostData, string $errorMessage): void
{
$this->createAttributeUsingDataWithErrorAndAssert($attributePostData, $errorMessage);
}
/**
* @inheritdoc
*/
protected function assertAttributeOptions(AttributeInterface $attribute, array $optionsData): void
{
/** @var Table $attributeSource */
$attributeSource = $attribute->getSource();
$swatchOptions = $attributeSource->getAllOptions(true, true);
foreach ($optionsData as $optionData) {
$optionVisualValueArr = $optionData['optiontext']['value'];
$optionVisualValue = reset($optionVisualValueArr)[0];
$optionFounded = false;
foreach ($swatchOptions as $attributeOption) {
if ($attributeOption['label'] === $optionVisualValue) {
$optionFounded = true;
break;
}
}
$this->assertTrue($optionFounded);
}
}
}
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Save\InputType;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Save\AbstractSaveAttributeTest;
use Magento\Eav\Api\Data\AttributeInterface;
use Magento\Eav\Model\Entity\Attribute\Source\Table;
/**
* Test cases related to create attribute with input type visual swatch.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class VisualSwatchTest extends AbstractSaveAttributeTest
{
/**
* Test create attribute and compare attribute data and input data.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\VisualSwatch::getAttributeDataWithCheckArray
*
* @param array $attributePostData
* @param array $checkArray
* @return void
*/
public function testCreateAttribute(array $attributePostData, array $checkArray): void
{
$this->createAttributeUsingDataAndAssert($attributePostData, $checkArray);
}
/**
* Test create attribute with error.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\VisualSwatch::getAttributeDataWithErrorMessage
*
* @param array $attributePostData
* @param string $errorMessage
* @return void
*/
public function testCreateAttributeWithError(array $attributePostData, string $errorMessage): void
{
$this->createAttributeUsingDataWithErrorAndAssert($attributePostData, $errorMessage);
}
/**
* @inheritdoc
*/
protected function assertAttributeOptions(AttributeInterface $attribute, array $optionsData): void
{
/** @var Table $attributeSource */
$attributeSource = $attribute->getSource();
$swatchOptions = $attributeSource->getAllOptions(true, true);
foreach ($optionsData as $optionData) {
$optionVisualValueArr = $optionData['optionvisual']['value'];
$optionVisualValue = reset($optionVisualValueArr)[0];
$optionFounded = false;
foreach ($swatchOptions as $attributeOption) {
if ($attributeOption['label'] === $optionVisualValue) {
$optionFounded = true;
break;
}
}
$this->assertTrue($optionFounded);
}
}
}
@@ -0,0 +1,146 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Update;
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Controller\Adminhtml\Product\Attribute\Update\AbstractUpdateAttributeTest;
use Magento\Swatches\Model\ResourceModel\Swatch\CollectionFactory as SwatchCollectionFactory;
use Magento\Swatches\Model\Swatch;
use Magento\Swatches\Model\SwatchAttributeType;
/**
* Base update and assert swatch attribute data.
*/
abstract class AbstractUpdateSwatchAttributeTest extends AbstractUpdateAttributeTest
{
/** @var SwatchAttributeType */
private $swatchAttributeType;
/** @var SwatchCollectionFactory */
private $swatchCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->swatchAttributeType = $this->_objectManager->get(SwatchAttributeType::class);
$this->swatchCollectionFactory = $this->_objectManager->get(SwatchCollectionFactory::class);
}
/**
* @inheritdoc
*/
protected function replaceStoreCodeWithId(array $optionsArray): array
{
$optionsArray = parent::replaceStoreCodeWithId($optionsArray);
foreach ($optionsArray as $key => $option) {
if (isset($option['swatch'])) {
$optionsArray[$key]['swatch'] = $this->prepareStoresData($option['swatch']);
}
}
return $optionsArray;
}
/**
* @inheritdoc
*/
protected function getActualOptionsData(string $attributeId): array
{
$actualOptionsData = parent::getActualOptionsData($attributeId);
foreach (array_keys($actualOptionsData) as $optionId) {
$actualOptionsData[$optionId]['swatch'] = $this->getAttributeOptionSwatchValues($optionId);
}
return $actualOptionsData;
}
/**
* @inheritdoc
*/
protected function prepareStoreOptionsPostData(array $optionsData): array
{
$optionsPostData = parent::prepareStoreOptionsPostData($optionsData);
$swatchType = $this->getSwatchType();
$swatchOptionsPostData = [];
foreach ($optionsData as $optionId => $option) {
$data = [];
$data['option' . $swatchType] = $optionsPostData[$optionId]['option'];
$optionSwatch = $swatchType == Swatch::SWATCH_INPUT_TYPE_VISUAL ? $option['swatch'][0] : $option['swatch'];
$data['swatch' . $swatchType] = [
'value' => [
$optionId => $optionSwatch,
],
];
if (isset($optionsPostData[$optionId]['default'])) {
$data['default' . $swatchType] = $optionsPostData[$optionId]['default'];
}
$swatchOptionsPostData[] = $data;
}
return $swatchOptionsPostData;
}
/**
* @inheritdoc
*/
protected function prepareStoreOptionsExpectedData(array $optionsData): array
{
$optionsExpectedData = parent::prepareStoreOptionsExpectedData($optionsData);
$optionsArray = $optionsExpectedData['options_array'];
foreach (array_keys($optionsArray) as $optionId) {
$optionsArray[$optionId]['swatch'] = $optionsData[$optionId]['swatch'];
}
return [
'options_array' => $optionsArray,
'default_value' => $optionsExpectedData['default_value'],
];
}
/**
* @inheritdoc
*/
protected function assertUpdateAttributeData(
ProductAttributeInterface $attribute,
array $expectedData
): void {
$this->swatchAttributeType->isSwatchAttribute($attribute);
parent::assertUpdateAttributeData($attribute, $expectedData);
}
/**
* Get attribute option swatch values by option id.
*
* @param int $optionId
* @return array
*/
private function getAttributeOptionSwatchValues(int $optionId): array
{
$swatchValues = [];
$collection = $this->swatchCollectionFactory->create();
$collection->addFieldToFilter('option_id', $optionId);
foreach ($collection as $item) {
$swatchValues[$item->getData('store_id')] = $item->getData('value');
}
return $swatchValues;
}
/**
* Get swatch type.
*
* @return string
*/
abstract protected function getSwatchType(): string;
}
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Update\InputType;
use Magento\Swatches\Controller\Adminhtml\Product\Attribute\Update\AbstractUpdateSwatchAttributeTest;
use Magento\Swatches\Model\Swatch;
/**
* Test cases related to update attribute with input type text swatch.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class TextSwatchTest extends AbstractUpdateSwatchAttributeTest
{
/**
* Test update attribute.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\TextSwatch::getUpdateProvider
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateAttribute(array $postData, array $expectedData): void
{
$this->updateAttributeUsingData('text_swatch_attribute', $postData);
$this->assertUpdateAttributeProcess('text_swatch_attribute', $postData, $expectedData);
}
/**
* Test update attribute with error.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\TextSwatch::getUpdateProviderWithErrorMessage
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
*
* @param array $postData
* @param string $errorMessage
* @return void
*/
public function testUpdateAttributeWithError(array $postData, string $errorMessage): void
{
$this->updateAttributeUsingData('text_swatch_attribute', $postData);
$this->assertErrorSessionMessages($errorMessage);
}
/**
* Test update attribute frontend labels on stores.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\TextSwatch::getUpdateFrontendLabelsProvider
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateFrontendLabelOnStores(array $postData, array $expectedData): void
{
$this->processUpdateFrontendLabelOnStores('text_swatch_attribute', $postData, $expectedData);
}
/**
* Test update attribute options on stores.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\TextSwatch::getUpdateOptionsProvider
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
*
* @param array $postData
* @return void
*/
public function testUpdateOptionsOnStores(array $postData): void
{
$this->processUpdateOptionsOnStores('text_swatch_attribute', $postData);
}
/**
* @inheritdoc
*/
protected function getSwatchType(): string
{
return Swatch::SWATCH_INPUT_TYPE_TEXT;
}
}
@@ -0,0 +1,91 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product\Attribute\Update\InputType;
use Magento\Swatches\Controller\Adminhtml\Product\Attribute\Update\AbstractUpdateSwatchAttributeTest;
use Magento\Swatches\Model\Swatch;
/**
* Test cases related to update attribute with input type visual swatch.
*
* @magentoDbIsolation enabled
* @magentoAppArea adminhtml
*/
class VisualSwatchTest extends AbstractUpdateSwatchAttributeTest
{
/**
* Test update attribute.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\VisualSwatch::getUpdateProvider
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateAttribute(array $postData, array $expectedData): void
{
$this->updateAttributeUsingData('visual_swatch_attribute', $postData);
$this->assertUpdateAttributeProcess('visual_swatch_attribute', $postData, $expectedData);
}
/**
* Test update attribute with error.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\VisualSwatch::getUpdateProviderWithErrorMessage
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
*
* @param array $postData
* @param string $errorMessage
* @return void
*/
public function testUpdateAttributeWithError(array $postData, string $errorMessage): void
{
$this->updateAttributeUsingData('visual_swatch_attribute', $postData);
$this->assertErrorSessionMessages($errorMessage);
}
/**
* Test update attribute frontend labels on stores.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\VisualSwatch::getUpdateFrontendLabelsProvider
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
*
* @param array $postData
* @param array $expectedData
* @return void
*/
public function testUpdateFrontendLabelOnStores(array $postData, array $expectedData): void
{
$this->processUpdateFrontendLabelOnStores('visual_swatch_attribute', $postData, $expectedData);
}
/**
* Test update attribute options on stores.
*
* @dataProvider \Magento\TestFramework\Swatches\Model\Attribute\DataProvider\VisualSwatch::getUpdateOptionsProvider
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
*
* @param array $postData
* @return void
*/
public function testUpdateOptionsOnStores(array $postData): void
{
$this->processUpdateOptionsOnStores('visual_swatch_attribute', $postData);
}
/**
* @inheritdoc
*/
protected function getSwatchType(): string
{
return Swatch::SWATCH_INPUT_TYPE_VISUAL;
}
}
@@ -0,0 +1,236 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Controller\Adminhtml\Product;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\Exception\LocalizedException;
/**
* Test for product attribute save controller.
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class AttributeTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
/**
* @var FormKey
*/
private $formKey;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->formKey = $this->_objectManager->get(FormKey::class);
}
/**
* Generate random hex color.
*
* @return string
*/
private function getRandomColor() : string
{
return '#' . str_pad(dechex(random_int(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}
/**
* Get visual swatches data set.
*
* @param int $optionsCount
* @return array
*/
private function getSwatchVisualDataSet(int $optionsCount) : array
{
$optionsData = [];
$expectedOptionsLabels = [];
for ($i = 0; $i < $optionsCount; $i++) {
$expectedOptionLabelOnStoreView = 'value_' . $i .'_store_1';
$expectedOptionsLabels[$i+1] = $expectedOptionLabelOnStoreView;
$optionId = 'option_' .$i;
$optionRowData = [];
$optionRowData['optionvisual']['order'][$optionId] = $i + 1;
$optionRowData['defaultvisual'][] = $optionId;
$optionRowData['swatchvisual']['value'][$optionId] = $this->getRandomColor();
$optionRowData['optionvisual']['value'][$optionId][0] = 'value_' . $i .'_admin';
$optionRowData['optionvisual']['value'][$optionId][1] = $expectedOptionLabelOnStoreView;
$optionRowData['optionvisual']['delete'][$optionId] = '';
$optionsData[] = http_build_query($optionRowData);
}
return [
'attribute_data' => array_merge_recursive(
[
'serialized_options' => json_encode($optionsData),
],
[
'visual_swatch_validation' => '',
'visual_swatch_validation_unique' => '',
],
$this->getAttributePreset(),
[
'frontend_input' => 'swatch_visual'
]
),
'expected_options_count' => $optionsCount + 1,
'expected_store_labels' => $expectedOptionsLabels
];
}
/**
* Get text swatches data set.
*
* @param int $optionsCount
* @return array
*/
private function getSwatchTextDataSet(int $optionsCount) : array
{
$optionsData = [];
$expectedOptionsLabels = [];
for ($i = 0; $i < $optionsCount; $i++) {
$expectedOptionLabelOnStoreView = 'value_' . $i . '_store_1';
$expectedOptionsLabels[$i+1] = $expectedOptionLabelOnStoreView;
$optionId = 'option_' . $i;
$optionRowData = [];
$optionRowData['optiontext']['order'][$optionId] = $i + 1;
$optionRowData['defaulttext'][] = $optionId;
$optionRowData['swatchtext']['value'][$optionId][] = 'x' . $i ;
$optionRowData['optiontext']['value'][$optionId][0] = 'value_' . $i . '_admin';
$optionRowData['optiontext']['value'][$optionId][1]= $expectedOptionLabelOnStoreView;
$optionRowData['optiontext']['delete'][$optionId]='';
$optionsData[] = http_build_query($optionRowData);
}
return [
'attribute_data' => array_merge_recursive(
[
'serialized_options' => json_encode($optionsData),
],
[
'text_swatch_validation' => '',
'text_swatch_validation_unique' => '',
],
$this->getAttributePreset(),
[
'frontend_input' => 'swatch_text'
]
),
'expected_options_count' => $optionsCount + 1,
'expected_store_labels' => $expectedOptionsLabels
];
}
/**
* Get data preset for new attribute.
*
* @return array
*/
private function getAttributePreset() : array
{
return [
'form_key' => 'XxtpPYjm2YPYUlAt',
'frontend_label' => [
0 => 'asdasd',
1 => '',
2 => '',
],
'is_required' => '0',
'update_product_preview_image' => '0',
'use_product_image_for_swatch' => '0',
'is_global' => '0',
'default_value_text' => '512',
'default_value_yesno' => '1',
'default_value_date' => '1/1/70',
'default_value_textarea' => '512',
'is_unique' => '0',
'is_used_in_grid' => '1',
'is_visible_in_grid' => '1',
'is_filterable_in_grid' => '1',
'is_searchable' => '0',
'is_comparable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'position' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'attribute_code' => 'test_many_swatches',
];
}
/**
* Data provider for large swatches amount test.
*
* @return array
*/
public function getLargeSwatchesAmountAttributeData() : array
{
$swatchVisualOptionsCount = 2000;
$swatchTextOptionsCount = 2000;
return [
'visual swatches' => $this->getSwatchVisualDataSet($swatchVisualOptionsCount),
'text swatches' => $this->getSwatchTextDataSet($swatchTextOptionsCount)
];
}
/**
* Test attribute saving with large amount of options exceeding maximum allowed by max_input_vars limit.
* @dataProvider getLargeSwatchesAmountAttributeData()
* @param array $attributeData
* @param int $expectedOptionsCount
* @param array $expectedLabels
* @return void
*/
public function testLargeOptionsDataSet(
array $attributeData,
int $expectedOptionsCount,
array $expectedLabels
) : void {
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($attributeData);
$this->getRequest()->setPostValue('form_key', $this->formKey->getFormKey());
$this->dispatch('backend/catalog/product_attribute/save');
$entityTypeId = $this->_objectManager->create(
\Magento\Eav\Model\Entity::class
)->setType(
\Magento\Catalog\Model\Product::ENTITY
)->getTypeId();
/** @var $attribute \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$attribute = $this->_objectManager->create(
\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class
)->setEntityTypeId(
$entityTypeId
);
try {
$attribute->loadByCode($entityTypeId, 'test_many_swatches');
$options = $attribute->getOptions();
// assert that all options are saved without truncation
$this->assertEquals(
$expectedOptionsCount,
count($options),
'Expected options count does not match (regarding first empty option for non-required attribute)'
);
foreach ($expectedLabels as $optionOrderNum => $label) {
$this->assertEquals(
$label,
$options[$optionOrderNum]->getLabel(),
"Label for option #{$optionOrderNum} does not match expected."
);
}
} catch (LocalizedException $e) {
$this->fail('Test failed with exception on attribute model load: ' . $e);
}
}
}
@@ -0,0 +1,66 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Helper;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Tests for product swatch attribute helper.
*
* @see \Magento\Swatches\Helper\Data
* @magentoDbIsolation enabled
*/
class DataTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Data */
private $helper;
/** @var ProductRepositoryInterface */
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->helper = $this->objectManager->get(Data::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
}
/**
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*
* @return void
*/
public function testGetSwatchAttributesAsArray(): void
{
$product = $this->productRepository->get('simple2');
$this->assertEmpty($this->helper->getSwatchAttributesAsArray($product));
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_with_disabled_image.php
*
* @return void
*/
public function testGetProductMediaGalleryWithHiddenImage(): void
{
$result = $this->helper->getProductMediaGallery($this->productRepository->get('simple_with_disabled_img'));
$this->assertEmpty($result);
}
}
@@ -0,0 +1,88 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Swatches\Model;
use Magento\Catalog\Api\Data\ProductAttributeInterfaceFactory;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory;
/**
* Test save of swatch attribute
*
*/
class AttributeCreateTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
public function testSetScopeDefault()
{
$om = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$data = [
'is_required' => 1,
'is_visible_on_front' => 1,
'is_visible_in_advanced_search' => 0,
'attribute_code' => 'color_swatch',
'backend_type' => '',
'is_searchable' => 0,
'is_filterable' => 0,
'is_filterable_in_search' => 0,
'frontend_label' => 'Attribute ',
];
$optionsPerAttribute = 3;
$data['frontend_input'] = 'swatch_visual';
$data['swatch_input_type'] = 'visual';
$data['swatchvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = '#'
. str_repeat(
dechex(255 * $index / $optionsPerAttribute),
3
);
return $values;
},
[]
);
$data['optionvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) {
$values['option_' . $index] = ['option ' . $index];
return $values;
},
[]
);
$data['options']['option'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) {
$values[] = [
'label' => 'option ' . $index,
'value' => 'option_' . $index
];
return $values;
},
[]
);
$options = [];
foreach ($data['options']['option'] as $optionData) {
$options[] = $om->get(AttributeOptionInterfaceFactory::class)->create(['data' => $optionData]);
}
$attribute = $om->get(ProductAttributeInterfaceFactory::class)
->create(['data' => $data]);
$attribute->setOptions($options);
$attribute->setNote('auto');
$attribute = $om->get(ProductAttributeRepositoryInterface::class)->save($attribute);
$this->assertNotEmpty($attribute->getId());
$this->assertEquals('swatch_visual', $attribute->getFrontendInput());
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Model;
use Magento\Catalog\Model\Product\Attribute\Save\AbstractAttributeTest;
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class AttributeTextSwatchTest extends AbstractAttributeTest
{
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'text_swatch_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getSource()->getOptionId('Option 2');
}
/**
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/Catalog/_files/product_simple_out_of_stock.php
* @dataProvider uniqueAttributeValueProvider
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
* @inheritdoc
*/
public function testUniqueAttribute(string $firstSku, string $secondSku): void
{
parent::testUniqueAttribute($firstSku, $secondSku);
}
/**
* @inheritdoc
*/
public function productProvider(): array
{
return [
[
'product_sku' => 'simple2',
],
];
}
/**
* @inheritdoc
*/
public function uniqueAttributeValueProvider(): array
{
return [
[
'first_product_sku' => 'simple2',
'second_product_sku' => 'simple-out-of-stock',
],
];
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Model;
use Magento\Catalog\Model\Product\Attribute\Save\AbstractAttributeTest;
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
class AttributeVisualSwatchTest extends AbstractAttributeTest
{
/**
* @inheritdoc
*/
protected function getAttributeCode(): string
{
return 'visual_swatch_attribute';
}
/**
* @inheritdoc
*/
protected function getDefaultAttributeValue(): string
{
return $this->getAttribute()->getSource()->getOptionId('option 2');
}
/**
* @magentoDataFixture Magento/Swatches/_files/product_visual_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @magentoDataFixture Magento/Catalog/_files/product_simple_out_of_stock.php
* @dataProvider uniqueAttributeValueProvider
* phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod
* @inheritdoc
*/
public function testUniqueAttribute(string $firstSku, string $secondSku): void
{
parent::testUniqueAttribute($firstSku, $secondSku);
}
/**
* @inheritdoc
*/
public function productProvider(): array
{
return [
[
'product_sku' => 'simple2',
],
];
}
/**
* @inheritdoc
*/
public function uniqueAttributeValueProvider(): array
{
return [
[
'first_product_sku' => 'simple2',
'second_product_sku' => 'simple-out-of-stock',
],
];
}
}
@@ -0,0 +1,122 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Model\Plugin;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Eav\Attribute;
use Magento\Framework\ObjectManagerInterface;
use Magento\Swatches\Model\ResourceModel\Swatch as SwatchResource;
use Magento\Swatches\Model\Swatch;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Interception\PluginList;
use PHPUnit\Framework\TestCase;
/**
* Checks swatches attribute save behaviour
*
* @see \Magento\Swatches\Model\Plugin\EavAttribute
*
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class EavAttributeTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var ProductAttributeRepositoryInterface */
private $productAttributeRepository;
/** @var SwatchResource */
private $swatchResource;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->productAttributeRepository = $this->objectManager->get(ProductAttributeRepositoryInterface::class);
$this->swatchResource = $this->objectManager->get(SwatchResource::class);
}
/**
* @return void
*/
public function testEavAttributePluginIsRegistered(): void
{
$pluginInfo = $this->objectManager->get(PluginList::class)->get(Attribute::class);
$this->assertSame(EavAttribute::class, $pluginInfo['save_swatches_option_params']['instance']);
}
/**
* @magentoDataFixture Magento/Swatches/_files/text_swatch_attribute.php
*
* @return void
*/
public function testChangeAttributeToDropdown(): void
{
$attribute = $this->productAttributeRepository->get('test_configurable');
$options = $attribute->getOptions();
unset($options[0]);
$optionsIds = $this->collectOptionsIds($options);
$attribute->addData($this->prepareOptions($options));
$attribute->setData(Swatch::SWATCH_INPUT_TYPE_KEY, Swatch::SWATCH_INPUT_TYPE_DROPDOWN);
$attribute->beforeSave();
$this->assertEmpty($this->fetchSwatchOptions($optionsIds), 'Swatch options were not deleted');
}
/**
* Prepare options
*
* @param array $options
* @return array
*/
private function prepareOptions(array $options): array
{
foreach ($options as $key => $option) {
$preparedOptions['option']['order'][$option->getValue()] = $key;
$preparedOptions['option']['value'][$option->getValue()] = [$option->getLabel()];
$preparedOptions['option']['delete'][$option->getValue()] = '';
}
return $preparedOptions ?? [];
}
/**
* Collect options ids
*
* @param array $options
* @return array
*/
private function collectOptionsIds(array $options): array
{
foreach ($options as $option) {
$optionsIds[] = $option->getValue();
}
return $optionsIds ?? [];
}
/**
* Fetch related to provided ids records from eav_attribute_option_swatch table
*
* @param $optionsIds
* @return array
*/
private function fetchSwatchOptions(array $optionsIds): array
{
$connection = $this->swatchResource->getConnection();
$select = $connection->select()->from(['main_table' => $this->swatchResource->getMainTable()])
->where('main_table.option_id IN (?)', $optionsIds);
return $connection->fetchAll($select);
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Swatches\Model;
class SwatchAttributeCodesTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Swatches\Model\SwatchAttributeCodes */
private $swatchAttributeCodes;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->swatchAttributeCodes = $this->objectManager->create(
\Magento\Swatches\Model\SwatchAttributeCodes::class
);
}
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Swatches/_files/swatch_attribute.php
*/
public function testGetCodes()
{
$attribute = $this->objectManager
->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class)
->load('color_swatch', 'attribute_code');
$expected = [
$attribute->getAttributeId() => $attribute->getAttributeCode()
];
$swatchAttributeCodes = $this->swatchAttributeCodes->getCodes();
$this->assertEquals($expected, $swatchAttributeCodes);
}
}
@@ -0,0 +1,82 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Swatches\Model;
use Magento\Catalog\Api\ProductAttributeOptionManagementInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Eav\Api\Data\AttributeOptionInterfaceFactory;
/**
* Test add option of swatch attribute
*
*/
class SwatchAttributeOptionAddTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Swatches/_files/swatch_attribute.php
*/
public function testSwatchOptionAdd()
{
/** @var \Magento\Catalog\Api\Data\ProductAttributeInterface $attribute */
$attribute = $this->objectManager
->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class)
->load('color_swatch', 'attribute_code');
$optionsPerAttribute = 4;
$data['options']['option'] = array_reduce(
range(10, $optionsPerAttribute),
function ($values, $index) {
$values[] = [
'label' => 'option ' . $index,
'value' => 'option_' . $index
];
return $values;
},
[]
);
/** @var AttributeOptionInterface[] $options */
$options = [];
foreach ($data['options']['option'] as $optionData) {
$options[] = $this->objectManager
->get(AttributeOptionInterfaceFactory::class)
->create(['data' => $optionData]);
}
/** @var ProductAttributeOptionManagementInterface $optionManagement */
$optionManagement = $this->objectManager->get(ProductAttributeOptionManagementInterface::class);
foreach ($options as $option) {
$optionManagement->add(
$attribute->getAttributeCode(),
$option
);
}
$items = $optionManagement->getItems($attribute->getAttributeCode());
array_walk(
$items,
function (&$item) {
/** @var AttributeOptionInterface $item */
$item = $item->getLabel();
}
);
foreach ($options as $option) {
$this->assertTrue(in_array($option->getLabel(), $items));
}
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Observer;
use Magento\Framework\DataObject;
use Magento\Swatches\Model\Swatch;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Event\ManagerInterface;
/**
* Test checks that swatch types are added to the other attribute types
*/
class AddSwatchAttributeTypeObserverTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppArea adminhtml
*/
public function testAddSwatchAttributeTypes()
{
$objectManager = Bootstrap::getObjectManager();
$eventManager = $objectManager->get(ManagerInterface::class);
$response = new DataObject();
$response->setTypes([]);
$eventManager->dispatch(
'adminhtml_product_attribute_types',
['response' => $response]
);
$responseTypes = $response->getTypes();
self::assertGreaterThan(0, count($responseTypes));
/* Iterate through values since other types (not swatches) might be added by observers */
$responseTypeValues = [];
foreach ($responseTypes as $responseType) {
$responseTypeValues[] = $responseType['value'];
}
self::assertTrue(in_array(Swatch::SWATCH_TYPE_VISUAL_ATTRIBUTE_FRONTEND_INPUT, $responseTypeValues));
self::assertTrue(in_array(Swatch::SWATCH_TYPE_TEXTUAL_ATTRIBUTE_FRONTEND_INPUT, $responseTypeValues));
}
}
@@ -0,0 +1,65 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Ui\DataProvider\Product\Form\Modifier\Eav;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Eav\SelectAttributeTest;
/**
* Provides tests for product form eav modifier with custom text swatch attribute.
*
* @magentoDataFixture Magento/Swatches/_files/product_text_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation enabled
*/
class TextSwatchAttributeTest extends SelectAttributeTest
{
/**
* @return void
*/
public function testModifyMeta(): void
{
$this->callModifyMetaAndAssert(
$this->getProduct(),
$this->addMetaNesting($this->getAttributeMeta(), 'product-details', 'text_swatch_attribute')
);
}
/**
* @return void
*/
public function testModifyData(): void
{
$product = $this->getProduct();
$optionValue = $this->getOptionValueByLabel('text_swatch_attribute', 'Option 1');
$attributeData = ['text_swatch_attribute' => $optionValue];
$this->saveProduct($product, $attributeData);
$expectedData = $this->addDataNesting($attributeData);
$this->callModifyDataAndAssert($product, $expectedData);
}
/**
* @return array
*/
private function getAttributeMeta(): array
{
return [
'dataType' => 'select',
'formElement' => 'select',
'visible' => '1',
'required' => '0',
'label' => 'Text swatch attribute',
'code' => 'text_swatch_attribute',
'source' => 'product-details',
'scopeLabel' => '[GLOBAL]',
'globalScope' => true,
'sortOrder' => '__placeholder__',
'options' => $this->getAttributeOptions('text_swatch_attribute'),
'componentType' => 'field',
];
}
}
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Swatches\Ui\DataProvider\Product\Form\Modifier\Eav;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Eav\SelectAttributeTest;
/**
* Provides tests for product form eav modifier with custom visual swatch attribute.
*
* @magentoDataFixture Magento/Swatches/_files/product_swatch_attribute.php
* @magentoDataFixture Magento/Catalog/_files/product_simple.php
* @magentoDbIsolation enabled
*/
class VisualSwatchAttributeTest extends SelectAttributeTest
{
/**
* @return void
*/
public function testModifyMeta(): void
{
$expectedMeta = $this->addMetaNesting(
$this->getAttributeMeta(),
'product-details',
'color_swatch'
);
$this->callModifyMetaAndAssert($this->getProduct(), $expectedMeta);
}
/**
* @return void
*/
public function testModifyData(): void
{
$product = $this->getProduct();
$attributeData = [
'color_swatch' => $this->getOptionValueByLabel('color_swatch', 'option 1')
];
$this->saveProduct($product, $attributeData);
$expectedData = $this->addDataNesting($attributeData);
$this->callModifyDataAndAssert($product, $expectedData);
}
/**
* @return array
*/
private function getAttributeMeta(): array
{
return [
'dataType' => 'swatch_visual',
'formElement' => 'swatch_visual',
'visible' => '1',
'required' => '1',
'label' => 'Attribute ',
'code' => 'color_swatch',
'source' => 'product-details',
'scopeLabel' => '[GLOBAL]',
'globalScope' => true,
'sortOrder' => '__placeholder__',
'options' => $this->getAttributeOptions('color_swatch'),
'componentType' => 'field',
'validation' => [
'required-entry' => true,
],
];
}
}
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductExtensionFactory;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type as ProductType;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_text_swatch_attribute.php');
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('text_swatch_attribute');
$options = $attribute->getOptions();
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$baseWebsite = $websiteRepository->get('base');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
$attributeValues = [];
$associatedProductIds = [];
$rootCategoryId = $baseWebsite->getDefaultStore()->getRootCategoryId();
array_shift($options);
foreach ($options as $option) {
$product = $productFactory->create();
$product->setTypeId(ProductType::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('Configurable Option ' . $option->getLabel())
->setSku(strtolower(str_replace(' ', '_', 'simple ' . $option->getLabel())))
->setPrice(150)
->setTextSwatchAttribute($option->getValue())
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setCategoryIds([$rootCategoryId])
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]);
$product = $productRepository->save($product);
$attributeValues[] = [
'label' => 'test',
'attribute_id' => $attribute->getId(),
'value_index' => $option->getValue(),
];
$associatedProductIds[] = $product->getId();
}
/** @var Factory $optionsFactory */
$optionsFactory = $objectManager->get(Factory::class);
$configurableAttributesData = [
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attributeValues,
],
];
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$product = $productFactory->create();
/** @var ProductExtensionFactory $extensionAttributesFactory */
$extensionAttributesFactory = $objectManager->get(ProductExtensionFactory::class);
$extensionConfigurableAttributes = $product->getExtensionAttributes() ?: $extensionAttributesFactory->create();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);
$product->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('Configurable Product')
->setSku('configurable')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setCategoryIds([$rootCategoryId])
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->save($product);
@@ -0,0 +1,45 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('text_swatch_attribute');
$options = $attribute->getOptions();
array_shift($options);
$productsArray = [];
foreach ($options as $option) {
$productsArray [] = strtolower(str_replace(' ', '_', 'simple ' . $option->getLabel()));
}
$productsArray[] = 'configurable';
foreach ($productsArray as $sku) {
try {
$productRepository->deleteById($sku);
} catch (NoSuchEntityException $e) {
//Product already removed
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_text_swatch_attribute_rollback.php');
@@ -0,0 +1,123 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductExtensionFactory;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type as ProductType;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Setup\CategorySetup;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_text_swatch_attribute.php');
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_visual_swatch_attribute.php');
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('text_swatch_attribute');
$secondAttribute = $productAttributeRepository->get('visual_swatch_attribute');
$options = $attribute->getOptions();
$secondAttributeOptions = $secondAttribute->getOptions();
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$baseWebsite = $websiteRepository->get('base');
/** @var ProductAttributeRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
$attributeValues = [];
$secondAttributeValues = [];
$associatedProductIds = [];
$associatedProductIdsViaSecondAttribute = [];
$attributeSetId = $installer->getAttributeSetId(Product::ENTITY, 'Default');
$productFactory = $objectManager->get(ProductFactory::class);
$rootCategoryId = $baseWebsite->getDefaultStore()->getRootCategoryId();
array_shift($options);
array_shift($secondAttributeOptions);
foreach ($options as $option) {
foreach ($secondAttributeOptions as $secondAttrOption) {
$product = $productFactory->create();
$product->setTypeId(ProductType::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('Configurable Option ' . $option->getLabel())
->setSku(
strtolower(
str_replace(' ', '_', 'simple ' . $option->getLabel() . '_' . $secondAttrOption->getLabel())
)
)
->setPrice(150)
->setTextSwatchAttribute($option->getValue())
->setVisualSwatchAttribute($secondAttrOption->getValue())
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setCategoryIds([$rootCategoryId])
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]);
$product = $productRepository->save($product, true);
$associatedProductIds[] = $product->getId();
}
$attributeValues[] = [
'label' => 'test1',
'attribute_id' => $attribute->getId(),
'value_index' => $option->getValue(),
];
}
foreach ($secondAttributeOptions as $secondAttrOption) {
$secondAttributeValues[] = [
'label' => 'test2',
'attribute_id' => $secondAttribute->getId(),
'value_index' => $secondAttrOption->getValue(),
];
}
$allAttributes = [$attribute, $secondAttribute];
$optionsFactory = $objectManager->get(Factory::class);
foreach ($allAttributes as $attribute) {
$configurableAttributesData[] =
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attribute->getAttributeCode() === 'text_swatch_attribute'
? $attributeValues
: $secondAttributeValues,
];
}
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$product = $productFactory->create();
/** @var ProductExtensionFactory $extensionAttributesFactory */
$extensionAttributesFactory = $objectManager->get(ProductExtensionFactory::class);
$extensionConfigurableAttributes = $product->getExtensionAttributes() ?: $extensionAttributesFactory->create();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);
$product->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('Configurable Product')
->setSku('configurable')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setCategoryIds([$rootCategoryId])
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->save($product);
@@ -0,0 +1,53 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$options = $productAttributeRepository->get('text_swatch_attribute')->getOptions();
$secondAttributeOptions = $productAttributeRepository->get('visual_swatch_attribute')->getOptions();
array_shift($options);
array_shift($secondAttributeOptions);
$productsArray = [];
foreach ($options as $option) {
foreach ($secondAttributeOptions as $secondAttrOption) {
$productsArray[] = strtolower(
str_replace(' ', '_', 'simple ' . $option->getLabel() . '_' . $secondAttrOption->getLabel())
);
}
}
$productsArray[] = 'configurable';
foreach ($productsArray as $sku) {
try {
$productRepository->deleteById($sku);
} catch (NoSuchEntityException $e) {
//Product already removed
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_text_swatch_attribute_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_visual_swatch_attribute_rollback.php');
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductExtensionFactory;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type as ProductType;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_visual_swatch_attribute.php');
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('visual_swatch_attribute');
$options = $attribute->getOptions();
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$baseWebsite = $websiteRepository->get('base');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
$attributeValues = [];
$associatedProductIds = [];
$rootCategoryId = $baseWebsite->getDefaultStore()->getRootCategoryId();
array_shift($options);
foreach ($options as $option) {
$product = $productFactory->create();
$product->setTypeId(ProductType::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('Configurable Option ' . $option->getLabel())
->setSku(strtolower(str_replace(' ', '_', 'simple ' . $option->getLabel())))
->setPrice(150)
->setVisualSwatchAttribute($option->getValue())
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setCategoryIds([$rootCategoryId])
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]);
$product = $productRepository->save($product);
$attributeValues[] = [
'label' => 'test',
'attribute_id' => $attribute->getId(),
'value_index' => $option->getValue(),
];
$associatedProductIds[] = $product->getId();
}
/** @var Factory $optionsFactory */
$optionsFactory = $objectManager->get(Factory::class);
$configurableAttributesData = [
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attributeValues,
],
];
$configurableOptions = $optionsFactory->create($configurableAttributesData);
$product = $productFactory->create();
/** @var ProductExtensionFactory $extensionAttributesFactory */
$extensionAttributesFactory = $objectManager->get(ProductExtensionFactory::class);
$extensionConfigurableAttributes = $product->getExtensionAttributes() ?: $extensionAttributesFactory->create();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$product->setExtensionAttributes($extensionConfigurableAttributes);
$product->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$baseWebsite->getId()])
->setName('Configurable Product')
->setSku('configurable')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setCategoryIds([$rootCategoryId])
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->save($product);
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
/** @var ObjectManagerInterface $objectManager */
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('visual_swatch_attribute');
$options = $attribute->getOptions();
array_shift($options);
$productsArray = [];
foreach ($options as $option) {
$productsArray [] = strtolower(str_replace(' ', '_', 'simple ' . $option->getLabel()));
}
$productsArray[] = 'configurable';
foreach ($productsArray as $sku) {
try {
$productRepository->deleteById($sku);
} catch (NoSuchEntityException $e) {
//Product already removed
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/product_visual_swatch_attribute_rollback.php');
@@ -0,0 +1,41 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductExtensionInterfaceFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture(
'Magento/Catalog/_files/product_image.php'
);
Resolver::getInstance()->requireDataFixture(
'Magento/Swatches/_files/configurable_product_visual_swatch_attribute.php'
);
$objectManager = Bootstrap::getObjectManager();
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$configurableProduct = $productRepository->get('configurable');
$children = $configurableProduct->getTypeInstance()->getUsedProducts($configurableProduct);
$images = ['magento_image.jpg', 'magento_small_image.jpg', 'magento_thumbnail.jpg'];
foreach ($children as $index => $product) {
$product->setImage('/m/a/' . $images[$index])
->setSmallImage('/m/a/' . $images[$index])
->setThumbnail('/m/a/' . $images[$index])
->setData('media_gallery', ['images' => [
[
'file' => '/m/a/' . $images[$index],
'position' => 1,
'label' => 'Image Alt Text',
'disabled' => 0,
'media_type' => 'image',
],
]])
->setCanSaveCustomOptions(true)
->save();
}
@@ -0,0 +1,15 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture(
'Magento/Swatches/_files/configurable_product_visual_swatch_attribute_rollback.php'
);
Resolver::getInstance()->requireDataFixture(
'Magento/Catalog/_files/product_image_rollback.php'
);
@@ -0,0 +1,93 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductExtensionInterfaceFactory;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\ConfigurableProduct\Helper\Product\Options\Factory;
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
use Magento\Store\Api\WebsiteRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture(
'Magento/Swatches/_files/visual_swatch_attribute_with_different_options_type.php'
);
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeRepositoryInterface $productAttributeRepository */
$productAttributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
$attribute = $productAttributeRepository->get('test_configurable');
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductFactory $productFactory */
$productFactory = $objectManager->get(ProductFactory::class);
/** @var Factory $optionsFactory */
$optionsFactory = $objectManager->get(Factory::class);
/** @var ProductExtensionInterfaceFactory $productExtensionAttributes */
$productExtensionAttributesFactory = $objectManager->get(ProductExtensionInterfaceFactory::class);
/** @var WebsiteRepositoryInterface $websiteRepository */
$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class);
$defaultWebsiteId = $websiteRepository->get('base')->getId();
$attributeValues = $associatedProductIds = [];
$options = $attribute->getSource()->getAllOptions();
array_shift($options);
foreach ($options as $option) {
/** @var Product $product */
$product = $productFactory->create();
$product->setTypeId(Type::TYPE_SIMPLE)
->setAttributeSetId($product->getDefaultAttributeSetId())
->setWebsiteIds([$defaultWebsiteId])
->setName('Configurable Option' . $option['label'])
->setSku('simple_' . str_replace(' ', '_', $option['label']))
->setPrice(100)
->setData('test_configurable', $option['value'])
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1]);
$product = $productRepository->save($product);
$attributeValues[] = [
'label' => 'test',
'attribute_id' => $attribute->getId(),
'value_index' => $option['value'],
];
$associatedProductIds[] = $product->getId();
}
/** @var Product $configurableProduct */
$configurableProduct = $productFactory->create();
$configurableOptions = $optionsFactory->create(
[
[
'attribute_id' => $attribute->getId(),
'code' => $attribute->getAttributeCode(),
'label' => $attribute->getStoreLabel(),
'position' => '0',
'values' => $attributeValues,
],
]
);
$extensionConfigurableAttributes = $configurableProduct->getExtensionAttributes()
?: $productExtensionAttributesFactory->create();
$extensionConfigurableAttributes->setConfigurableProductOptions($configurableOptions);
$extensionConfigurableAttributes->setConfigurableProductLinks($associatedProductIds);
$configurableProduct->setExtensionAttributes($extensionConfigurableAttributes);
$configurableProduct->setTypeId(Configurable::TYPE_CODE)
->setAttributeSetId($configurableProduct->getDefaultAttributeSetId())
->setWebsiteIds([$defaultWebsiteId])
->setName('Configurable Product')
->setSku('configurable')
->setVisibility(Visibility::VISIBILITY_BOTH)
->setStatus(Status::STATUS_ENABLED)
->setStockData(['use_config_manage_stock' => 1, 'is_in_stock' => 1]);
$productRepository->save($configurableProduct);
@@ -0,0 +1,47 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Registry;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
/** @var ProductAttributeRepositoryInterface $attributeRepository */
$attributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$attribute = $attributeRepository->get('test_configurable');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$options = $attribute->getSource()->getAllOptions();
array_shift($options);
foreach ($options as $option) {
try {
$productRepository->deleteById('simple_' . str_replace(' ', '_', $option['label']));
} catch (NoSuchEntityException $e) {
//Product already removed
}
}
try {
$productRepository->deleteById('configurable');
} catch (NoSuchEntityException $e) {
//Product already removed
}
Resolver::getInstance()->requireDataFixture(
'Magento/Swatches/_files/visual_swatch_attribute_with_different_options_type_rollback.php'
);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,32 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
use Magento\Catalog\Setup\CategorySetup;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/swatch_attribute.php');
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
$attributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$entityType = $installer->getEntityTypeId(ProductAttributeInterface::ENTITY_TYPE_CODE);
$attribute = $objectManager->create(AttributeFactory::class)->create()
->loadByCode($entityType, 'color_swatch');
if ($attribute->getAttributeId()) {
/* Assign attribute to attribute set */
$installer->addAttributeToGroup(
ProductAttributeInterface::ENTITY_TYPE_CODE,
'Default',
'General',
$attribute->getAttributeId()
);
}
@@ -0,0 +1,10 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Swatches/_files/swatch_attribute_rollback.php');
@@ -0,0 +1,68 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
use Magento\Catalog\Setup\CategorySetup;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
$attribute = $objectManager->create(AttributeFactory::class)->create();
$attributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$entityType = $installer->getEntityTypeId(ProductAttributeInterface::ENTITY_TYPE_CODE);
if (!$attribute->loadByCode($entityType, 'text_swatch_attribute')->getAttributeId()) {
$attribute->setData(
[
'frontend_label' => ['Text swatch attribute'],
'entity_type_id' => $entityType,
'frontend_input' => 'select',
'backend_type' => 'int',
'is_required' => '0',
'attribute_code' => 'text_swatch_attribute',
'is_global' => '1',
'is_user_defined' => 1,
'is_unique' => '0',
'is_searchable' => '0',
'is_comparable' => '0',
'is_filterable' => '1',
'is_filterable_in_search' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'used_in_product_listing' => '1',
'used_for_sort_by' => '0',
'swatch_input_type' => 'text',
'optiontext' => [
'order' => [
'option_0' => 1,
'option_1' => 2,
'option_3' => 3,
],
'value' => [
'option_0' => ['Option 1'],
'option_1' => ['Option 2'],
'option_2' => ['Option 3'],
],
],
'swatchtext' => [
'value' => [
'option_0' => ['Swatch 1'],
'option_1' => ['Swatch 2'],
'option_2' => ['Swatch 3'],
],
],
]
);
$attribute->save();
$installer->addAttributeToGroup(
ProductAttributeInterface::ENTITY_TYPE_CODE,
'Default',
'General',
$attribute->getId()
);
}
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Registry;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
$objectManager = Bootstrap::getObjectManager();
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductAttributeRepositoryInterface $attributeRepository */
$attributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
try {
$attributeRepository->deleteById('text_swatch_attribute');
} catch (NoSuchEntityException $e) {
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,70 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Eav\AttributeFactory;
use Magento\Catalog\Setup\CategorySetup;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
$attribute = $objectManager->create(AttributeFactory::class)->create();
$attributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
$entityType = $installer->getEntityTypeId(ProductAttributeInterface::ENTITY_TYPE_CODE);
if (!$attribute->loadByCode($entityType, 'visual_swatch_attribute')->getAttributeId()) {
$attribute->setData(
[
'frontend_label' => ['Visual swatch attribute'],
'entity_type_id' => $entityType,
'frontend_input' => 'select',
'backend_type' => 'int',
'is_required' => '0',
'attribute_code' => 'visual_swatch_attribute',
'is_global' => '1',
'is_user_defined' => 1,
'is_unique' => '0',
'is_searchable' => '0',
'is_comparable' => '0',
'is_filterable' => '1',
'is_filterable_in_search' => '0',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'used_in_product_listing' => '1',
'used_for_sort_by' => '0',
'swatch_input_type' => 'visual',
'swatchvisual' => [
'value' => [
'option_1' => '#555555',
'option_2' => '#aaaaaa',
'option_3' => '#ffffff',
],
],
'optionvisual' => [
'value' => [
'option_1' => ['option 1'],
'option_2' => ['option 2'],
'option_3' => ['option 3']
],
],
'options' => [
'option' => [
['label' => 'Option 1', 'value' => 'option_1'],
['label' => 'Option 2', 'value' => 'option_2'],
['label' => 'Option 3', 'value' => 'option_3'],
],
],
]
);
$attributeRepository->save($attribute);
$installer->addAttributeToGroup(
ProductAttributeInterface::ENTITY_TYPE_CODE,
'Default',
'General',
$attribute->getId()
);
}
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Framework\Registry;
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var ProductAttributeRepositoryInterface $attributeRepository */
$attributeRepository = $objectManager->create(ProductAttributeRepositoryInterface::class);
try {
$attributeRepository->deleteById('visual_swatch_attribute');
} catch (NoSuchEntityException $e) {
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,208 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Helper\Bootstrap;
use Magento\Eav\Api\Data\AttributeOptionInterface;
/** @var \Magento\Framework\ObjectManagerInterface $objectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var $installer \Magento\Catalog\Setup\CategorySetup */
$installer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Setup\CategorySetup::class);
$data = [
'attribute_code' => 'color_swatch',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 1,
'is_visible_in_advanced_search' => 1,
'is_comparable' => 1,
'is_filterable' => 1,
'is_filterable_in_search' => 1,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 1,
'used_in_product_listing' => 1,
'used_for_sort_by' => 1,
'frontend_label' => ['Test Swatch'],
'backend_type' => 'int',
'use_product_image_for_swatch' => 0,
'update_product_preview_image' => 0,
];
$optionsPerAttribute = 3;
$data['swatch_input_type'] = 'visual';
$data['swatchvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = '#'
. str_repeat(
dechex(255 * $index / $optionsPerAttribute),
3
);
return $values;
},
[]
);
$data['optionvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = ['option ' . $index];
return $values;
},
[]
);
$data['options']['option'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values[] = [
'label' => 'option ' . $index,
'value' => 'option_' . $index,
];
return $values;
},
[]
);
$options = [];
foreach ($data['options']['option'] as $optionData) {
$options[] = $objectManager->get(AttributeOptionInterface::class)
->setLabel($optionData['label'])
->setValue($optionData['value']);
}
$attribute = $objectManager->create(
\Magento\Catalog\Api\Data\ProductAttributeInterface::class,
['data' => $data]
);
$attribute->setOptions($options);
$attribute->save();
/* Assign attribute to attribute set */
$installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());
/** @var \Magento\Eav\Model\Config $eavConfig */
$eavConfig = Bootstrap::getObjectManager()->get(\Magento\Eav\Model\Config::class);
$eavConfig->clear();
$attribute = $eavConfig->getAttribute('catalog_product', 'color_swatch');
$options = $attribute->getOptions();
// workaround for saved attribute
$attribute->setDefaultValue($options[1]->getValue());
$attribute->save();
$eavConfig->clear();
/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->isObjectNew(true);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setId(10)
->setAttributeSetId(4)
->setName('Simple Product1')
->setSku('simple1')
->setTaxClassId('none')
->setDescription('description')
->setShortDescription('short description')
->setOptionsContainer('container1')
->setMsrpDisplayActualPriceType(\Magento\Msrp\Model\Product\Attribute\Source\Type::TYPE_IN_CART)
->setPrice(10)
->setWeight(1)
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setWebsiteIds([1])
->setCategoryIds([])
->setStockData(['use_config_manage_stock' => 1, 'qty' => 100, 'is_qty_decimal' => 0, 'is_in_stock' => 1])
->setSpecialPrice('5.99')
->save();
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->isObjectNew(true);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setId(11)
->setAttributeSetId(4)
->setName('Simple Product2')
->setSku('simple2')
->setTaxClassId('none')
->setDescription('description')
->setShortDescription('short description')
->setOptionsContainer('container1')
->setMsrpDisplayActualPriceType(\Magento\Msrp\Model\Product\Attribute\Source\Type::TYPE_ON_GESTURE)
->setPrice(20)
->setWeight(1)
->setMetaTitle('meta title')
->setMetaKeyword('meta keyword')
->setMetaDescription('meta description')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setWebsiteIds([1])
->setCategoryIds([])
->setStockData(['use_config_manage_stock' => 1, 'qty' => 50, 'is_qty_decimal' => 0, 'is_in_stock' => 1])
->setSpecialPrice('15.99')
->save();
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->isObjectNew(true);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setId(12)
->setAttributeSetId(4)
->setName('Simple Product3')
->setSku('simple3')
->setTaxClassId('none')
->setDescription('description')
->setShortDescription('short description')
->setPrice(30)
->setWeight(1)
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setWebsiteIds([1])
->setCategoryIds([])
->setStockData(['use_config_manage_stock' => 1, 'qty' => 140, 'is_qty_decimal' => 0, 'is_in_stock' => 1])
->setSpecialPrice('25.99')
->save();
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Category::class);
$category->isObjectNew(true);
$category->setId(
333
)->setCreatedAt(
'2014-06-23 09:50:07'
)->setName(
'Category 1'
)->setParentId(
2
)->setPath(
'1/2/333'
)->setLevel(
2
)->setAvailableSortBy(
['position', 'name']
)->setDefaultSortBy(
'name'
)->setIsActive(
true
)->setPosition(
1
)->setPostedProducts(
[10 => 10, 11 => 11, 12 => 12]
)->save();
/** @var \Magento\Indexer\Model\Indexer\Collection $indexerCollection */
$indexerCollection = Bootstrap::getObjectManager()->get(\Magento\Indexer\Model\Indexer\Collection::class);
$indexerCollection->load();
/** @var \Magento\Indexer\Model\Indexer $indexer */
foreach ($indexerCollection->getItems() as $indexer) {
$indexer->reindexAll();
}
@@ -0,0 +1,51 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
foreach (['simple1', 'simple2', 'simple3'] as $sku) {
try {
$product = $productRepository->get($sku, false, null, true);
$productRepository->delete($product);
} catch (\Magento\Framework\Exception\NoSuchEntityException $exception) {
//Product already removed
}
}
$productCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
foreach ($productCollection as $product) {
$product->delete();
}
/** @var $category \Magento\Catalog\Model\Category */
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Category::class);
$category->load(333);
if ($category->getId()) {
$category->delete();
}
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$attribute->loadByCode(4, 'color_swatch');
if ($attribute->getId()) {
$attribute->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,73 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Eav\Api\Data\AttributeOptionInterface;
/** @var \Magento\Framework\ObjectManagerInterface $objectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$data = [
'is_required' => 1,
'is_visible_on_front' => 1,
'is_visible_in_advanced_search' => 0,
'attribute_code' => 'color_swatch',
'backend_type' => '',
'is_searchable' => 0,
'is_filterable' => 0,
'is_user_defined' => 1,
'is_filterable_in_search' => 0,
'frontend_label' => 'Attribute ',
'entity_type_id' => 4
];
$optionsPerAttribute = 3;
$data['frontend_input'] = 'swatch_visual';
$data['swatch_input_type'] = 'visual';
$data['swatchvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = '#'
. str_repeat(
dechex(255 * $index / $optionsPerAttribute),
3
);
return $values;
},
[]
);
$data['optionvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = ['option ' . $index];
return $values;
},
[]
);
$data['options']['option'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values[] = [
'label' => 'option ' . $index,
'value' => 'option_' . $index,
];
return $values;
},
[]
);
$options = [];
foreach ($data['options']['option'] as $optionData) {
$options[] = $objectManager->get(AttributeOptionInterface::class)
->setLabel($optionData['label'])
->setValue($optionData['value']);
}
$attribute = $objectManager->create(
\Magento\Catalog\Api\Data\ProductAttributeInterface::class,
['data' => $data]
);
$attribute->setOptions($options);
$attribute->save();
@@ -0,0 +1,23 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$attribute->loadByCode(4, 'color_swatch');
if ($attribute->getId()) {
$attribute->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,103 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Setup\CategorySetup;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Swatches\Model\Swatch;
use Magento\TestFramework\Helper\Bootstrap;
/** @var $installer CategorySetup */
$installer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Setup\CategorySetup::class);
/** @var AttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class);
// Add attribute data
$data = [
'attribute_code' => 'test_configurable',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 0,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 0,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Test Configurable'],
'backend_type' => 'int',
];
$optionsPerAttribute = 3;
$data['frontend_input'] = 'select';
$data['swatch_input_type'] = Swatch::SWATCH_INPUT_TYPE_TEXT;
$data['swatchtext']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = ['option ' . $index];
return $values;
},
[]
);
$data['optiontext']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = ['option ' . $index];
return $values;
},
[]
);
$data['optiontext']['order'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = $index;
return $values;
},
[]
);
$data['options']['option'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values[] = [
'label' => 'option ' . $index,
'value' => 'option_' . $index,
];
return $values;
},
[]
);
$options = [];
foreach ($data['options']['option'] as $optionData) {
$options[] = Bootstrap::getObjectManager()->create(AttributeOptionInterface::class)
->setLabel($optionData['label'])
->setValue($optionData['value']);
}
$attribute = Bootstrap::getObjectManager()->create(
ProductAttributeInterface::class,
['data' => $data]
);
$attribute->setOptions($options);
$attributeRepository->save($attribute);
/* Assign attribute to attribute set */
$installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());
@@ -0,0 +1,23 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
$attribute = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Catalog\Model\ResourceModel\Eav\Attribute::class);
$attribute->loadByCode(4, 'test_configurable');
if ($attribute->getId()) {
$attribute->delete();
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,116 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\Data\ProductAttributeInterface;
use Magento\Catalog\Setup\CategorySetup;
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Eav\Api\Data\AttributeOptionInterface;
use Magento\Setup\Fixtures\ImagesGenerator\ImagesGenerator;
use Magento\Swatches\Helper\Media as SwatchesMedia;
use Magento\Swatches\Model\Swatch;
use Magento\TestFramework\Helper\Bootstrap;
/** @var $installer CategorySetup */
$installer = Bootstrap::getObjectManager()->create(\Magento\Catalog\Setup\CategorySetup::class);
/** @var AttributeRepositoryInterface $attributeRepository */
$attributeRepository = Bootstrap::getObjectManager()->create(AttributeRepositoryInterface::class);
// Generate swatch image
/** @var ImagesGenerator $imagesGenerator */
$imagesGenerator = Bootstrap::getObjectManager()->get(ImagesGenerator::class);
/** @var SwatchesMedia $swatchesMedia */
$swatchesMedia = Bootstrap::getObjectManager()->get(SwatchesMedia::class);
$imageName = '/visual_swatch_attribute_option_type_image.jpg';
$imagesGenerator->generate([
'image-width' => 110,
'image-height' => 90,
'image-name' => $imageName,
]);
$imagePath = substr($swatchesMedia->moveImageFromTmp($imageName), 1);
$swatchesMedia->generateSwatchVariations($imagePath);
// Add attribute data
$data = [
'attribute_code' => 'test_configurable',
'entity_type_id' => $installer->getEntityTypeId('catalog_product'),
'is_global' => 1,
'is_user_defined' => 1,
'frontend_input' => 'select',
'is_unique' => 0,
'is_required' => 0,
'is_searchable' => 0,
'is_visible_in_advanced_search' => 0,
'is_comparable' => 0,
'is_filterable' => 0,
'is_filterable_in_search' => 0,
'is_used_for_promo_rules' => 0,
'is_html_allowed_on_front' => 1,
'is_visible_on_front' => 0,
'used_in_product_listing' => 0,
'used_for_sort_by' => 0,
'frontend_label' => ['Test Configurable'],
'backend_type' => 'int',
];
$optionsPerAttribute = 3;
$data['frontend_input'] = 'select';
$data['swatch_input_type'] = Swatch::SWATCH_INPUT_TYPE_VISUAL;
$data['swatchvisual']['value'] = [
'option_1' => '#000000', // HEX color (color type)
'option_2' => $imagePath, // image path (image type)
'option_3' => null, // null (empty type)
];
$data['optionvisual']['value'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = ['option ' . $index];
return $values;
},
[]
);
$data['optionvisual']['order'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values['option_' . $index] = $index;
return $values;
},
[]
);
$data['options']['option'] = array_reduce(
range(1, $optionsPerAttribute),
function ($values, $index) use ($optionsPerAttribute) {
$values[] = [
'label' => 'option ' . $index,
'value' => 'option_' . $index,
];
return $values;
},
[]
);
$options = [];
foreach ($data['options']['option'] as $optionData) {
$options[] = Bootstrap::getObjectManager()->create(AttributeOptionInterface::class)
->setLabel($optionData['label'])
->setValue($optionData['value']);
}
$attribute = Bootstrap::getObjectManager()->create(
ProductAttributeInterface::class,
['data' => $data]
);
$attribute->setOptions($options);
$attributeRepository->save($attribute);
/* Assign attribute to attribute set */
$installer->addAttributeToGroup('catalog_product', 'Default', 'General', $attribute->getId());
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\ProductAttributeRepositoryInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Swatches\Helper\Media as SwatchesMedia;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var ProductAttributeRepositoryInterface $attributeRepository */
$attributeRepository = $objectManager->get(ProductAttributeRepositoryInterface::class);
try {
$attribute = $attributeRepository->get('test_configurable');
$attributeRepository->delete($attribute);
} catch (NoSuchEntityException $exception) {
//Product already removed
}
/** @var WriteInterface $mediaDirectory */
$mediaDirectory = $objectManager->get(Filesystem::class)
->getDirectoryWrite(
DirectoryList::MEDIA
);
/** @var SwatchesMedia $swatchesMedia */
$swatchesMedia = $objectManager->get(SwatchesMedia::class);
$testImageName = 'visual_swatch_attribute_option_type_image.jpg';
$testImageSwatchPath = $swatchesMedia->getAttributeSwatchPath($testImageName);
$mediaDirectory->delete($testImageSwatchPath);
$imageConfig = $swatchesMedia->getImageConfig();
$swatchTypes = ['swatch_image', 'swatch_thumb'];
foreach ($swatchTypes as $swatchType) {
$absolutePath = $mediaDirectory->getAbsolutePath($swatchesMedia->getSwatchCachePath($swatchType));
$swatchTypePath = $absolutePath . $swatchesMedia->getFolderNameSize($swatchType, $imageConfig) .
'/' . $testImageName;
$mediaDirectory->delete($swatchTypePath);
}
@@ -0,0 +1,38 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Model\Product;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture(
'Magento/Swatches/_files/visual_swatch_attribute_with_different_options_type.php'
);
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_products.php');
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_image.php');
// set 'Product Image for Swatch' for attribute
$attribute->setData('use_product_image_for_swatch', 1);
$attributeRepository->save($attribute);
// get first child and set image
$childrenProducts = $product->getTypeInstance()->getUsedProducts($product);
/** @var Product $firstChildSimpleProduct */
$firstChildSimpleProduct = array_shift($childrenProducts);
$firstChildSimpleProduct
->setImage('/m/a/magento_image.jpg')
->setSmallImage('/m/a/magento_image.jpg')
->setThumbnail('/m/a/magento_image.jpg')
->setData('media_gallery', ['images' => [
[
'file' => '/m/a/magento_image.jpg',
'position' => 1,
'label' => 'Image Alt Text',
'disabled' => 0,
'media_type' => 'image'
],
]])
->save();
@@ -0,0 +1,14 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture(
'Magento/Swatches/_files/visual_swatch_attribute_with_different_options_type_rollback.php'
);
Resolver::getInstance()->requireDataFixture('Magento/ConfigurableProduct/_files/configurable_products_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_image_rollback.php');