Skip to content

MAGETWO-99236 Fix for #22063 Category data is changed after saving category linkfor different stores #34226

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: 2.4-develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions app/code/Magento/Catalog/Model/CategoryLinkRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class CategoryLinkRepository implements CategoryLinkRepositoryInterface, Categor
protected $categoryRepository;

/**
* @deprecated
* @see Product use faster resource model
* @var ProductRepositoryInterface
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I googled a bit this class and it looks like there is not modules that add peference for it or replace this dependecy. Anyway they would preference the interface, so maybe it's worth to just delete the product repo from here and infrom about minor BIC changes in new release?
Just waiting for approval from the core team

*/
protected $productRepository;
Expand Down Expand Up @@ -56,17 +58,17 @@ public function __construct(
public function save(\Magento\Catalog\Api\Data\CategoryProductLinkInterface $productLink)
{
$category = $this->categoryRepository->get($productLink->getCategoryId());
$product = $this->productRepository->get($productLink->getSku());
$productId = $this->productResource->getIdBySku($productLink->getSku());
$productPositions = $category->getProductsPosition();
$productPositions[$product->getId()] = $productLink->getPosition();
$productPositions[$productId] = $productLink->getPosition();
$category->setPostedProducts($productPositions);
try {
$category->save();
} catch (\Exception $e) {
throw new CouldNotSaveException(
__(
'Could not save product "%1" with position %2 to category %3',
$product->getId(),
$productId,
$productLink->getPosition(),
$category->getId()
),
Expand All @@ -90,15 +92,14 @@ public function delete(\Magento\Catalog\Api\Data\CategoryProductLinkInterface $p
public function deleteByIds($categoryId, $sku)
{
$category = $this->categoryRepository->get($categoryId);
$product = $this->productRepository->get($sku);
$productId = $this->productResource->getIdBySku($sku);
$productPositions = $category->getProductsPosition();

$productID = $product->getId();
if (!isset($productPositions[$productID])) {
if (!isset($productPositions[$productId])) {
throw new InputException(__("The category doesn't contain the specified product."));
}
$backupPosition = $productPositions[$productID];
unset($productPositions[$productID]);
$backupPosition = $productPositions[$productId];
unset($productPositions[$productId]);

$category->setPostedProducts($productPositions);
try {
Expand All @@ -108,7 +109,7 @@ public function deleteByIds($categoryId, $sku)
__(
'Could not save product "%product" with position %position to category %category',
[
"product" => $product->getId(),
"product" => $productId,
"position" => $backupPosition,
"category" => $category->getId()
]
Expand Down
8 changes: 4 additions & 4 deletions app/code/Magento/Catalog/Model/CategoryRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,14 @@ class CategoryRepository implements CategoryRepositoryInterface, ResetAfterReque
* @var ExtensibleDataObjectConverter
*/
private $extensibleDataObjectConverter;

// @codingStandardsIgnoreStart
/**
* List of fields that can used config values in case when value does not defined directly
* List of fields that can use config values in case when value does not defined directly
*
* @var array
*/
protected $useConfigFields = ['available_sort_by', 'default_sort_by', 'filter_price_range'];

// @codingStandardsIgnoreEnd
/**
* @var PopulateWithValues
*/
Expand Down Expand Up @@ -149,7 +149,7 @@ public function save(CategoryInterface $category)
*/
public function get($categoryId, $storeId = null)
{
$cacheKey = $storeId ?? 'all';
$cacheKey = $storeId ?? $this->storeManager->getStore()->getId();
if (!isset($this->instances[$categoryId][$cacheKey])) {
/** @var Category $category */
$category = $this->categoryFactory->create();
Expand Down
8 changes: 1 addition & 7 deletions app/code/Magento/Catalog/Model/ResourceModel/Category.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ class Category extends AbstractResource implements ResetAfterRequestInterface
protected $_tree;

/**
* Catalog products table name
*
* @var string
*/
protected $_categoryProductTable;
Expand All @@ -49,15 +47,11 @@ class Category extends AbstractResource implements ResetAfterRequestInterface
private $entitiesWhereAttributesIs;

/**
* Id of 'is_active' category attribute
*
* @var int
*/
protected $_isActiveAttributeId = null;

/**
* Id of store
*
* @var int
*/
protected $_storeId = null;
Expand Down Expand Up @@ -455,7 +449,7 @@ protected function _saveCategoryProducts($category)
'position' => (int)$position,
];
}
$connection->insertMultiple($this->getCategoryProductTable(), $data);
$connection->insertOnDuplicate($this->getCategoryProductTable(), $data, ['position']);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\CategoryLinkRepository;
use Magento\Catalog\Model\Product as ProductModel;
use Magento\Catalog\Model\ResourceModel\Product;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\InputException;
Expand All @@ -37,6 +36,8 @@ class CategoryLinkRepositoryTest extends TestCase
private $categoryRepositoryMock;

/**
* @deprecated
* @see \Magento\Catalog\Model\CategoryLinkRepository
* @var ProductRepositoryInterface|MockObject
*/
private $productRepositoryMock;
Expand All @@ -58,7 +59,7 @@ protected function setUp(): void
{
$this->productResourceMock = $this->getMockBuilder(Product::class)
->disableOriginalConstructor()
->onlyMethods(['getProductsIdsBySkus'])
->onlyMethods(['getProductsIdsBySkus', 'getIdBySku'])
->getMock();
$this->categoryRepositoryMock = $this->getMockForAbstractClass(CategoryRepositoryInterface::class);
$this->productRepositoryMock = $this->getMockForAbstractClass(ProductRepositoryInterface::class);
Expand Down Expand Up @@ -87,14 +88,12 @@ public function testSave(): void
->onlyMethods(['getProductsPosition', 'save'])
->disableOriginalConstructor()
->getMock();
$productMock = $this->createMock(ProductModel::class);
$this->productLinkMock->expects($this->once())->method('getCategoryId')->willReturn($categoryId);
$this->productLinkMock->expects($this->once())->method('getSku')->willReturn($sku);
$this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId)
->willReturn($categoryMock);
$this->productRepositoryMock->expects($this->once())->method('get')->with($sku)->willReturn($productMock);
$categoryMock->expects($this->once())->method('getProductsPosition')->willReturn([]);
$productMock->expects($this->once())->method('getId')->willReturn($productId);
$this->productResourceMock->expects($this->once())->method('getIdBySku')->willReturn($productId);
$this->productLinkMock->expects($this->once())->method('getPosition')->willReturn($productPosition);
$categoryMock->expects($this->once())->method('setPostedProducts')->with($productPositions);
$categoryMock->expects($this->once())->method('save');
Expand All @@ -119,14 +118,12 @@ public function testSaveWithCouldNotSaveException(): void
->onlyMethods(['getProductsPosition', 'save', 'getId'])
->disableOriginalConstructor()
->getMock();
$productMock = $this->createMock(ProductModel::class);
$this->productLinkMock->expects($this->once())->method('getCategoryId')->willReturn($categoryId);
$this->productLinkMock->expects($this->once())->method('getSku')->willReturn($sku);
$this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId)
->willReturn($categoryMock);
$this->productRepositoryMock->expects($this->once())->method('get')->with($sku)->willReturn($productMock);
$categoryMock->expects($this->once())->method('getProductsPosition')->willReturn([]);
$productMock->expects($this->exactly(2))->method('getId')->willReturn($productId);
$this->productResourceMock->expects($this->once())->method('getIdBySku')->willReturn($productId);
$this->productLinkMock->expects($this->exactly(2))->method('getPosition')->willReturn($productPosition);
$categoryMock->expects($this->once())->method('setPostedProducts')->with($productPositions);
$categoryMock->expects($this->once())->method('getId')->willReturn($categoryId);
Expand All @@ -153,13 +150,10 @@ public function testDeleteByIds(): void
->onlyMethods(['getProductsPosition', 'save', 'getId'])
->disableOriginalConstructor()
->getMock();
$productMock = $this->createMock(ProductModel::class);
$this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId)
->willReturn($categoryMock);
$this->productRepositoryMock->expects($this->once())->method('get')->with($productSku)
->willReturn($productMock);
$categoryMock->expects($this->once())->method('getProductsPosition')->willReturn($productPositions);
$productMock->expects($this->once())->method('getId')->willReturn($productId);
$this->productResourceMock->expects($this->once())->method('getIdBySku')->willReturn($productId);
$categoryMock->expects($this->once())->method('setPostedProducts')->with([]);
$categoryMock->expects($this->once())->method('save');

Expand All @@ -182,13 +176,10 @@ public function testDeleteByIdsWithCouldNotSaveException(): void
->onlyMethods(['getProductsPosition', 'save', 'getId'])
->disableOriginalConstructor()
->getMock();
$productMock = $this->createMock(ProductModel::class);
$this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId)
->willReturn($categoryMock);
$this->productRepositoryMock->expects($this->once())->method('get')->with($productSku)
->willReturn($productMock);
$categoryMock->expects($this->once())->method('getProductsPosition')->willReturn($productPositions);
$productMock->expects($this->exactly(2))->method('getId')->willReturn($productId);
$this->productResourceMock->expects($this->once())->method('getIdBySku')->willReturn($productId);
$categoryMock->expects($this->once())->method('setPostedProducts')->with([]);
$categoryMock->expects($this->once())->method('getId')->willReturn($categoryId);
$categoryMock->expects($this->once())->method('save')->willThrowException(new \Exception());
Expand Down Expand Up @@ -216,13 +207,10 @@ public function testDeleteWithInputException(): void
->onlyMethods(['getProductsPosition', 'save', 'getId'])
->disableOriginalConstructor()
->getMock();
$productMock = $this->createMock(ProductModel::class);
$this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId)
->willReturn($categoryMock);
$this->productRepositoryMock->expects($this->once())->method('get')->with($productSku)
->willReturn($productMock);
$categoryMock->expects($this->once())->method('getProductsPosition')->willReturn($productPositions);
$productMock->expects($this->once())->method('getId')->willReturn($productId);
$this->productResourceMock->expects($this->once())->method('getIdBySku')->willReturn($productId);
$categoryMock->expects($this->never())->method('save');

$this->expectExceptionMessage('The category doesn\'t contain the specified product.');
Expand All @@ -248,13 +236,10 @@ public function testDelete(): void
->onlyMethods(['getProductsPosition', 'save', 'getId'])
->disableOriginalConstructor()
->getMock();
$productMock = $this->createMock(ProductModel::class);
$this->categoryRepositoryMock->expects($this->once())->method('get')->with($categoryId)
->willReturn($categoryMock);
$this->productRepositoryMock->expects($this->once())->method('get')->with($productSku)
->willReturn($productMock);
$categoryMock->expects($this->once())->method('getProductsPosition')->willReturn($productPositions);
$productMock->expects($this->once())->method('getId')->willReturn($productId);
$this->productResourceMock->expects($this->once())->method('getIdBySku')->willReturn($productId);
$categoryMock->expects($this->once())->method('setPostedProducts')->with([]);
$categoryMock->expects($this->once())->method('save');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,13 @@ public function testUpdateCategoryForDefaultStoreView(array $postData): void
$postData = array_merge($postData, ['store_id' => $storeId]);
$responseData = $this->performSaveCategoryRequest($postData);
$this->assertRequestIsSuccessfullyPerformed($responseData);
$category = $this->categoryRepository->get($postData['entity_id'], $postData['store_id']);
/**
* The problem is that
* @see \Magento\Catalog\Controller\Adminhtml\Category\Save::execute
* saves the category via resource model, so the cache in the repository is not cleaned
*/
$newCategoryRepository = $this->_objectManager->create(CategoryRepositoryInterface::class);
$category = $newCategoryRepository->get($postData['entity_id'], $postData['store_id']);
unset($postData['use_default']);
unset($postData['use_config']);
foreach ($postData as $key => $value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,13 @@ public function testDefaultValueForCategoryUrlPath(): void
$this->equalTo([(string)__('You saved the category.')]),
MessageInterface::TYPE_SUCCESS
);
$category = $this->categoryRepository->get($categoryId);
/**
* The problem is that
* @see \Magento\Catalog\Controller\Adminhtml\Category\Save::execute
* saves the category via resource model, so the cache in the repository is not cleaned
*/
$newCategoryRepository = $this->_objectManager->create(CategoryRepositoryInterface::class);
$category = $newCategoryRepository->get($categoryId);
$this->assertEquals($defaultUrlPath, $category->getData('url_key'));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\Catalog\Model;

use Magento\Catalog\Api\CategoryLinkRepositoryInterface;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\Data\CategoryProductLinkInterface;
use Magento\Framework\App\Area;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Model\App\Emulation;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;

class CategoryLinkRepositoryTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;

/**
* @var CategoryLinkRepositoryInterface
*/
private $categoryLinkRepository;

/**
* @var CategoryRepositoryInterface
*/
private $categoryRepository;

/**
* @var StoreRepositoryInterface
*/
private $storeRepository;

/**
* @var Emulation
*/
private $appEmulation;

protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->categoryLinkRepository = $this->objectManager->get(CategoryLinkRepositoryInterface::class);
$this->storeRepository = $this->objectManager->get(StoreRepositoryInterface::class);
$this->categoryRepository = $this->objectManager->get(CategoryRepositoryInterface::class);
$this->appEmulation = $this->objectManager->get(Emulation::class);
parent::setUp();
}

/**
* Make sure that if some custom code uses emulation and assigns products to categories,
* the categories are not overwritten by loading data via category repository from wrong store.
* The default store is used in
* @see \Magento\Catalog\Model\CategoryLinkRepository::save
*
* @magentoAppArea crontab
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Catalog/_files/saving_product_category_link_under_different_stores.php
*/
public function testCategoryDataNotChanged()
{
$secondStore = $this->storeRepository->get('fixture_second_store');
$secondStoreId = (int)$secondStore->getId();
/** @var CategoryProductLinkInterface $categoryProductLink */
$categoryProductLink = $this->objectManager->create(CategoryProductLinkInterface::class);

$this->appEmulation->startEnvironmentEmulation($secondStoreId, Area::AREA_FRONTEND, true);

$categoryProductLink
->setCategoryId(113)
->setSku('simple116')
->setPosition(2);

$this->categoryLinkRepository->save($categoryProductLink);

$this->appEmulation->stopEnvironmentEmulation();

$categoryFromDefaultStore = $this->categoryRepository->get(113);
$categoryFromSecondStore = $this->categoryRepository->get(113, $secondStoreId);

$categoryNameFromDefaultStore = $categoryFromDefaultStore->getName();
$categoryDescriptionFromDefaultStore = $categoryFromDefaultStore->getDescription();

$categoryNameFromSecondStore = $categoryFromSecondStore->getName();
$categoryDescriptionFromSecondStore = $categoryFromSecondStore->getDescription();

$this->assertEquals('Test Category In Default Store', $categoryNameFromDefaultStore);
$this->assertEquals('Test description in default store', $categoryDescriptionFromDefaultStore);
$this->assertEquals('Test Category In Second Store', $categoryNameFromSecondStore);
$this->assertEquals('Test description in second store', $categoryDescriptionFromSecondStore);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -376,8 +376,13 @@ public function testDeleteChildren(): void
*/
public function testChildrenCountAfterDeleteParentCategory(): void
{
$childrenCountInParent = $this->categoryResource->getChildrenCount(1);
$childrenCountInChild = $this->categoryResource->getChildrenCount(3);

$this->categoryRepository->deleteByIdentifier(3);
$this->assertEquals(8, $this->categoryResource->getChildrenCount(1));

$expectedCountAfterDelete = $childrenCountInParent - $childrenCountInChild - 1;
$this->assertEquals($expectedCountAfterDelete, $this->categoryResource->getChildrenCount(1));
}

/**
Expand Down
Loading