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,39 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Framework\Registry;
use Magento\TestFramework\Catalog\Model\GetCategoryByName;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/product_with_category.php');
/** @var GetCategoryByName $getCategoryByName */
$getCategoryByName = $objectManager->create(GetCategoryByName::class);
$category = $getCategoryByName->execute('category 1');
/** @var CategoryLinkManagementInterface $linkManagement */
$linkManagement = $objectManager->get(CategoryLinkManagementInterface::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get('p002');
$product->setStoreId(1);
$product->setUrlKey('store-1-key');
$product = $productRepository->save($product);
$linkManagement->assignProductToCategories($product->getSku(), [Category::TREE_ROOT_ID, $category->getEntityId()]);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -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/CatalogUrlRewrite/_files/product_with_category_rollback.php');
@@ -0,0 +1,132 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use PHPUnit\Framework\TestCase;
/**
* Base class for url rewrites tests logic
*
* @magentoDbIsolation enabled
*/
abstract class AbstractUrlRewriteTest extends TestCase
{
/** @var ObjectManagerInterface */
protected $objectManager;
/** @var StoreRepositoryInterface */
protected $storeRepository;
/** @var ScopeConfigInterface */
protected $config;
/** @var UrlRewriteCollectionFactory */
protected $urlRewriteCollectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->storeRepository = $this->objectManager->create(StoreRepositoryInterface::class);
$this->config = $this->objectManager->get(ScopeConfigInterface::class);
$this->urlRewriteCollectionFactory = $this->objectManager->get(UrlRewriteCollectionFactory::class);
}
/**
* Retrieve all rewrite ids
*
* @return array
*/
protected function getAllRewriteIds(): array
{
$urlRewriteCollection = $this->urlRewriteCollectionFactory->create();
return $urlRewriteCollection->getAllIds();
}
/**
* Check that actual data contains of expected values
*
* @param UrlRewriteCollection $collection
* @param array $expectedData
* @return void
*/
protected function assertRewrites(UrlRewriteCollection $collection, array $expectedData): void
{
$collectionItems = $collection->toArray()['items'];
$this->assertTrue(count($collectionItems) === count($expectedData));
foreach ($expectedData as $expectedItem) {
$found = false;
foreach ($collectionItems as $item) {
$found = array_intersect_assoc($item, $expectedItem) == $expectedItem;
if ($found) {
break;
}
}
$this->assertTrue($found, 'The actual data does not contains of expected values');
}
}
/**
* Get category url rewrites collection
*
* @param string|array $entityId
* @return UrlRewriteCollection
*/
protected function getEntityRewriteCollection($entityId): UrlRewriteCollection
{
$condition = is_array($entityId) ? ['in' => $entityId] : $entityId;
$entityRewriteCollection = $this->urlRewriteCollectionFactory->create();
$entityRewriteCollection->addFieldToFilter(UrlRewrite::ENTITY_ID, $condition)
->addFieldToFilter(UrlRewrite::ENTITY_TYPE, ['eq' => $this->getEntityType()]);
return $entityRewriteCollection;
}
/**
* Prepare expected data
*
* @param array $expectedData
* @param int|null $id
* @return array
*/
protected function prepareData(array $expectedData, ?int $id = null): array
{
$newData = [];
foreach ($expectedData as $key => $expectedItem) {
$newData[$key] = str_replace(['%suffix%', '%id%'], [$this->getUrlSuffix(), $id], $expectedItem);
}
return $newData;
}
/**
* Get entity type
*
* @return string
*/
abstract protected function getEntityType(): string;
/**
* Get config value for url suffix
*
* @return string
*/
abstract protected function getUrlSuffix(): string;
}
@@ -0,0 +1,201 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Model\Category\Plugin;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product as ProductEntity;
use Magento\Catalog\Model\Product\Media\ConfigInterface;
use Magento\Framework\App\Bootstrap as AppBootstrap;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\Write;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\ObjectManagerInterface;
use Magento\ImportExport\Model\Import;
use Magento\CatalogImportExport\Model\Import\ProductFactory;
use Magento\ImportExport\Model\Import\Source\Csv;
use Magento\ImportExport\Model\Import\Source\CsvFactory;
use Magento\ImportExport\Model\ResourceModel\Import\Data;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks that product import with same images can be successfully done
*
* @magentoAppArea adminhtml
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class StorageTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var Filesystem */
private $fileSystem;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var File */
private $fileDriver;
/** @var Import */
private $import;
/** @var ConfigInterface */
private $mediaConfig;
/** @var array */
private $appParams;
/** @var array */
private $createdProductsSkus = [];
/** @var array */
private $filesToRemove = [];
/** @var CsvFactory */
private $csvFactory;
/** @var Data */
private $importDataResource;
/** @var Write */
private $mediaDirectory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->fileSystem = $this->objectManager->get(Filesystem::class);
$this->fileDriver = $this->objectManager->get(File::class);
$this->mediaConfig = $this->objectManager->get(ConfigInterface::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->productRepository->cleanCache();
$this->import = $this->objectManager->get(ProductFactory::class)->create();
$this->csvFactory = $this->objectManager->get(CsvFactory::class);
$this->importDataResource = $this->objectManager->get(Data::class);
$this->appParams = Bootstrap::getInstance()->getBootstrap()->getApplication()
->getInitParams()[AppBootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS];
$this->mediaDirectory = $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA);
}
/**
* @inheritdoc
*/
protected function tearDown(): void
{
$this->removeFiles();
$this->removeProducts();
$this->importDataResource->cleanBunches();
parent::tearDown();
}
/**
* @return void
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/issue34210_structure.php
* @magentoDbIsolation disabled
*/
public function testIssue34210(): void
{
$source = $this->prepareFile('issue34210.csv');
$this->updateUploader();
$errors = $this->import->setParameters([
'behavior' => Import::BEHAVIOR_ADD_UPDATE,
'entity' => ProductEntity::ENTITY,
])
->setSource($source)->validateData();
$this->assertEmpty($errors->getAllErrors());
$result = $this->import->importData();
$this->assertTrue($result);
}
/**
* Remove created files
*
* @return void
*/
private function removeFiles(): void
{
foreach ($this->filesToRemove as $file) {
if ($this->fileDriver->isExists($file)) {
$this->fileDriver->deleteFile($file);
}
}
}
/**
* Remove created products
*
* @return void
*/
private function removeProducts(): void
{
$resource = $this->objectManager->get(ResourceConnection::class);
$connection = $resource->getConnection();
$connection->delete('catalog_category_product');
foreach ($this->createdProductsSkus as $sku) {
try {
$this->productRepository->deleteById($sku);
} catch (NoSuchEntityException $e) {
//already removed
}
}
}
/**
* Prepare file
*
* @param string $fileName
* @return Csv
*/
private function prepareFile(string $fileName): Csv
{
$tmpDirectory = $this->fileSystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$fixtureDir = realpath(__DIR__ . '/../../../_files');
$filePath = $tmpDirectory->getAbsolutePath($fileName);
$this->filesToRemove[] = $filePath;
$tmpDirectory->getDriver()->copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$source = $this->csvFactory->create(
[
'file' => $fileName,
'directory' => $tmpDirectory
]
);
return $source;
}
/**
* Update upload to use sandbox folders
*
* @return void
*/
private function updateUploader(): void
{
$mediaDir = !$this->mediaDirectory->getDriver() instanceof File ?
DirectoryList::MEDIA : $this->appParams[DirectoryList::MEDIA][DirectoryList::PATH];
$destDir = $mediaDir . DIRECTORY_SEPARATOR . $this->mediaConfig->getBaseMediaPath();
$tmpDir = $mediaDir . DIRECTORY_SEPARATOR . 'import';
$this->mediaDirectory->create($this->mediaConfig->getBaseMediaPath());
$this->mediaDirectory->create('import');
$this->import->setParameters([Import::FIELD_NAME_IMG_FILE_DIR => $tmpDir]);
$uploader = $this->import->getUploader();
$uploader->setDestDir($destDir);
$uploader->setTmpDir($tmpDir);
}
}
@@ -0,0 +1,381 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogUrlRewrite\Model;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\CategoryRepository;
use Magento\Catalog\Model\ProductRepository;
use Magento\CatalogUrlRewrite\Model\ResourceModel\Category\Product;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\OptionProvider;
use Magento\UrlRewrite\Model\Storage\DbStorage;
use Magento\UrlRewrite\Model\UrlFinderInterface;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CategoryUrlRewriteGeneratorTest extends TestCase
{
/** @var ObjectManagerInterface */
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
public function testGenerateUrlRewritesWithoutSaveHistory()
{
$resource = $this->objectManager->get(ResourceConnection::class);
$connection = $resource->getConnection();
$connection->delete(DbStorage::TABLE_NAME);
/** @var Category $category */
$category = $this->objectManager->create(Category::class);
$category->load(3);
$category->setData('save_rewrites_history', false);
$category->setUrlKey('new-url');
$category->save();
$categoryFilter = [
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::ENTITY_ID => [3, 4, 5]
];
$actualResults = $this->getActualResults($categoryFilter);
$categoryExpectedResult = [
['new-url.html', 'catalog/category/view/id/3', 1, 0],
['new-url/category-1-1.html', 'catalog/category/view/id/4', 1, 0],
['new-url/category-1-1/category-1-1-1.html', 'catalog/category/view/id/5', 1, 0],
];
$this->assertResults($categoryExpectedResult, $actualResults);
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(ProductRepository::class);
$product = $productRepository->get('12345');
$productForTest = $product->getId();
$productFilter = [
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::ENTITY_ID => [$productForTest]
];
$actualResults = $this->getActualResults($productFilter);
$productExpectedResult = [
[
'simple-product-two.html',
'catalog/product/view/id/' . $productForTest,
1,
0
],
[
'new-url/category-1-1/category-1-1-1/simple-product-two.html',
'catalog/product/view/id/' . $productForTest . '/category/5',
1,
0
],
[
'new-url/simple-product-two.html',
'catalog/product/view/id/' . $productForTest . '/category/3',
1,
0
],
[
'new-url/category-1-1/simple-product-two.html',
'catalog/product/view/id/' . $productForTest . '/category/4',
1,
0
]
];
$this->assertResults($productExpectedResult, $actualResults);
}
/**
* @magentoDbIsolation enabled
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoAppIsolation enabled
*/
public function testGenerateUrlRewritesWithSaveHistory()
{
/** @var Category $category */
$category = $this->objectManager->create(Category::class);
$category->load(3);
$category->setData('save_rewrites_history', true);
$category->setUrlKey('new-url');
$category->save();
$categoryFilter = [
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::ENTITY_ID => [3, 4, 5]
];
$actualResults = $this->getActualResults($categoryFilter);
$categoryExpectedResult = [
['new-url.html', 'catalog/category/view/id/3', 1, 0],
['new-url/category-1-1.html', 'catalog/category/view/id/4', 1, 0],
['new-url/category-1-1/category-1-1-1.html', 'catalog/category/view/id/5', 1, 0],
['category-1.html', 'new-url.html', 0, OptionProvider::PERMANENT],
['category-1/category-1-1.html', 'new-url/category-1-1.html', 0, OptionProvider::PERMANENT],
[
'category-1/category-1-1/category-1-1-1.html',
'new-url/category-1-1/category-1-1-1.html',
0,
OptionProvider::PERMANENT
],
];
$this->assertResults($categoryExpectedResult, $actualResults);
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(ProductRepository::class);
$product = $productRepository->get('12345');
$productForTest = $product->getId();
$productFilter = [
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::ENTITY_ID => [$productForTest]
];
$actualResults = $this->getActualResults($productFilter);
$productExpectedResult = [
[
'simple-product-two.html',
'catalog/product/view/id/' . $productForTest,
1,
0
],
[
'new-url/category-1-1/category-1-1-1/simple-product-two.html',
'catalog/product/view/id/' . $productForTest . '/category/5',
1,
0
],
[
'category-1/category-1-1/category-1-1-1/simple-product-two.html',
'new-url/category-1-1/category-1-1-1/simple-product-two.html',
0,
OptionProvider::PERMANENT
],
[
'new-url/simple-product-two.html',
'catalog/product/view/id/' . $productForTest . '/category/3',
1,
0
],
[
'new-url/category-1-1/simple-product-two.html',
'catalog/product/view/id/' . $productForTest . '/category/4',
1,
0
],
[
'category-1/simple-product-two.html',
'new-url/simple-product-two.html',
0,
OptionProvider::PERMANENT
],
[
'category-1/category-1-1/simple-product-two.html',
'new-url/category-1-1/simple-product-two.html',
0,
OptionProvider::PERMANENT
],
];
$this->assertResults($productExpectedResult, $actualResults);
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
* @param string $urlKey
* @throws CouldNotSaveException
* @throws NoSuchEntityException
* @throws Exception
* @dataProvider incorrectUrlRewritesDataProvider
*/
public function testGenerateUrlRewritesWithIncorrectUrlKey($urlKey)
{
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('Invalid URL key');
/** @var CategoryRepositoryInterface $repository */
$repository = $this->objectManager->get(CategoryRepositoryInterface::class);
$category = $repository->get(3);
$category->setUrlKey($urlKey);
$repository->save($category);
}
/**
* @return array
*/
public function incorrectUrlRewritesDataProvider()
{
return [
['#'],
['//']
];
}
/**
* @param array $filter
* @return array
*/
protected function getActualResults(array $filter)
{
/** @var UrlFinderInterface $urlFinder */
$urlFinder = $this->objectManager->get(UrlFinderInterface::class);
$actualResults = [];
foreach ($urlFinder->findAllByData($filter) as $url) {
$actualResults[] = [
$url->getRequestPath(),
$url->getTargetPath(),
(int)$url->getIsAutogenerated(),
$url->getRedirectType()
];
}
return $actualResults;
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 0
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
public function testGenerateUrlRewritesWithoutGenerateCategoryRewrites()
{
/** @var Category $category */
$category = $this->objectManager->create(Category::class);
$category->load(3);
$category->setData('save_rewrites_history', false);
$category->setUrlKey('new-url');
$category->save();
$categoryFilter = [
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::ENTITY_ID => [3, 4, 5]
];
$actualResults = $this->getActualResults($categoryFilter);
$categoryExpectedResult = [
['new-url.html', 'catalog/category/view/id/3', 1, 0],
['new-url/category-1-1.html', 'catalog/category/view/id/4', 1, 0],
['new-url/category-1-1/category-1-1-1.html', 'catalog/category/view/id/5', 1, 0],
];
$this->assertResults($categoryExpectedResult, $actualResults);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 0
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoAppIsolation enabled
*/
public function testGenerateUrlRewritesWithoutGenerateProductRewrites()
{
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(ProductRepository::class);
$product = $productRepository->get('12345');
$productForTest = $product->getId();
$productFilter = [
UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE,
UrlRewrite::ENTITY_ID => [$productForTest]
];
$actualResults = $this->getActualResults($productFilter);
$productExpectedResult = [
[
'simple-product-two.html',
'catalog/product/view/id/' . $productForTest,
1,
0
]
];
$this->assertResults($productExpectedResult, $actualResults);
}
/**
* Check number of records after removing product
*
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*
* @return void
* @throws NoSuchEntityException
* @throws \Magento\Framework\Exception\StateException
*/
public function testRemoveCatalogUrlRewrites()
{
/** @var CategoryRepository $categoryRepository */
$categoryRepository = $this->objectManager->create(CategoryRepository::class);
$category = $categoryRepository->get(5);
$categoryId = $category->getId();
/** @var ProductRepository $productRepository */
$productRepository = $this->objectManager->create(ProductRepository::class);
$product = $productRepository->get('12345');
$productId = $product->getId();
$countBeforeRemoving = $this->getCountOfRewrites($productId, $categoryId);
$productRepository->delete($product);
$countAfterRemoving = $this->getCountOfRewrites($productId, $categoryId);
$this->assertEquals($countBeforeRemoving - 1, $countAfterRemoving);
}
/**
* Get count of records in table
*
* @param $productId
* @param $categoryId
* @return string
*/
private function getCountOfRewrites($productId, $categoryId): string
{
/** @var Product $model */
$model = $this->objectManager->get(Product::class);
$connection = $model->getConnection();
$select = $connection->select();
$select->from($model->getTable(Product::TABLE_NAME), 'COUNT(*)');
$select->where('category_id = ?', $categoryId);
$select->where('product_id = ?', $productId);
return $connection->fetchOne($select);
}
/**
* @param array $expected
* @param array $actual
* @throws Exception
*/
protected function assertResults($expected, $actual)
{
$this->assertEquals(count($expected), count($actual), 'Number of rewrites does not match');
foreach ($expected as $row) {
$this->assertContains(
$row,
$actual,
'Expected: ' . var_export($row, true) . "\nIn Actual: " . var_export($actual, true)
);
}
}
}
@@ -0,0 +1,456 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Model;
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Catalog\Model\ResourceModel\CategoryFactory as CategoryResourceFactory;
use Magento\CatalogUrlRewrite\Model\Map\DataCategoryUrlRewriteDatabaseMap;
use Magento\CatalogUrlRewrite\Model\Map\DataProductUrlRewriteDatabaseMap;
use Magento\CatalogUrlRewrite\Model\ResourceModel\Category\Product;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException;
use Magento\UrlRewrite\Model\OptionProvider;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use PHPUnit\Framework\TestCase;
/**
* Class for category url rewrites tests
*
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CategoryUrlRewriteTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var CategoryFactory */
private $categoryFactory;
/** @var UrlRewriteCollectionFactory */
private $urlRewriteCollectionFactory;
/** @var CategoryRepositoryInterface */
private $categoryRepository;
/** @var CategoryResourceFactory */
private $categoryResourceFactory;
/** @var CategoryLinkManagementInterface */
private $categoryLinkManagment;
/** @var ProductRepositoryInterface */
private $productRepository;
/** @var StoreRepositoryInterface */
private $storeRepository;
/** @var ScopeConfigInterface */
private $config;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->categoryFactory = $this->objectManager->get(CategoryFactory::class);
$this->urlRewriteCollectionFactory = $this->objectManager->get(UrlRewriteCollectionFactory::class);
$this->categoryRepository = $this->objectManager->create(CategoryRepositoryInterface::class);
$this->categoryResourceFactory = $this->objectManager->get(CategoryResourceFactory::class);
$this->categoryLinkManagment = $this->objectManager->create(CategoryLinkManagementInterface::class);
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->storeRepository = $this->objectManager->create(StoreRepositoryInterface::class);
$this->config = $this->objectManager->get(ScopeConfigInterface::class);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/category_with_position.php
* @dataProvider categoryProvider
* @param array $data
* @return void
*/
public function testUrlRewriteOnCategorySave(array $data): void
{
$categoryModel = $this->categoryFactory->create();
$categoryModel->isObjectNew(true);
$categoryModel->setData($data['data']);
$categoryResource = $this->categoryResourceFactory->create();
$categoryResource->save($categoryModel);
$this->assertNotNull($categoryModel->getId(), 'The category was not created');
$urlRewriteCollection = $this->getCategoryRewriteCollection($categoryModel->getId());
foreach ($urlRewriteCollection as $item) {
foreach ($data['expected_data'] as $field => $expectedItem) {
$this->assertEquals(
sprintf($expectedItem, $categoryModel->getId()),
$item[$field],
'The expected data does not match actual value'
);
}
}
}
/**
* @return array
*/
public function categoryProvider(): array
{
return [
'without_url_key' => [
[
'data' => [
'name' => 'Test Category',
'attribute_set_id' => '3',
'parent_id' => 2,
'path' => '1/2',
'is_active' => true,
],
'expected_data' => [
'request_path' => 'test-category.html',
'target_path' => 'catalog/category/view/id/%s',
],
],
],
'subcategory_without_url_key' => [
[
'data' => [
'name' => 'Test Sub Category',
'attribute_set_id' => '3',
'parent_id' => 444,
'path' => '1/2/444',
'is_active' => true,
],
'expected_data' => [
'request_path' => 'category-1/test-sub-category.html',
'target_path' => 'catalog/category/view/id/%s',
],
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/category_tree.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @dataProvider productRewriteProvider
* @param array $data
* @return void
*/
public function testCategoryProductUrlRewrite(array $data): void
{
$category = $this->categoryRepository->get(402);
$this->categoryLinkManagment->assignProductToCategories('simple2', [$category->getId()]);
$productRewriteCollection = $this->getProductRewriteCollection(array_keys($category->getParentCategories()));
$this->assertRewrites($productRewriteCollection, $data);
}
/**
* @return array
*/
public function productRewriteProvider(): array
{
return [
[
[
[
'request_path' => 'category-1/category-1-1/category-1-1-1/simple-product2.html',
'target_path' => 'catalog/product/view/id/6/category/402',
],
[
'request_path' => 'category-1/simple-product2.html',
'target_path' => 'catalog/product/view/id/6/category/400',
],
[
'request_path' => 'category-1/category-1-1/simple-product2.html',
'target_path' => 'catalog/product/view/id/6/category/401',
],
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoAppIsolation enabled
* @dataProvider existingUrlProvider
* @param array $data
* @return void
*/
public function testUrlRewriteOnCategorySaveWithExistingUrlKey(array $data): void
{
$this->expectException(UrlAlreadyExistsException::class);
$this->expectExceptionMessage((string)__('URL key for specified store already exists.'));
$category = $this->categoryFactory->create();
$category->setData($data);
$categoryResource = $this->categoryResourceFactory->create();
$categoryResource->save($category);
}
/**
* @return array
*/
public function existingUrlProvider(): array
{
return [
'with_specified_existing_product_url_key' => [
'data' => [
'name' => 'Test Category',
'attribute_set_id' => '3',
'parent_id' => 2,
'path' => '1/2',
'is_active' => true,
'url_key' => 'simple-product',
],
],
'with_autogenerated_existing_product_url_key' => [
'data' => [
'name' => 'Simple Product',
'attribute_set_id' => '3',
'parent_id' => 2,
'path' => '1/2',
'is_active' => true,
],
],
'with_specified_existing_category_url_key' => [
'data' => [
'name' => 'Test Category',
'attribute_set_id' => '3',
'parent_id' => 2,
'path' => '1/2',
'is_active' => true,
'url_key' => 'category-1',
],
],
'with_autogenerated_existing_category_url_key' => [
'data' => [
'name' => 'Category 1',
'attribute_set_id' => '3',
'parent_id' => 2,
'path' => '1/2',
'is_active' => true,
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/category_product.php
* @magentoDataFixture Magento/Catalog/_files/catalog_category_with_slash.php
* @dataProvider categoryMoveProvider
* @param array $data
* @return void
*/
public function testUrlRewriteOnCategoryMove(array $data): void
{
$categoryId = $data['data']['id'];
$category = $this->categoryRepository->get($categoryId);
$category->move($data['data']['pid'], $data['data']['aid']);
$productRewriteCollection = $this->getProductRewriteCollection(array_keys($category->getParentCategories()));
$categoryRewriteCollection = $this->getCategoryRewriteCollection($categoryId);
$this->assertRewrites($categoryRewriteCollection, $data['expected_data']['category']);
$this->assertRewrites($productRewriteCollection, $data['expected_data']['product']);
}
/**
* @return array
*/
public function categoryMoveProvider(): array
{
return [
'append_category' => [
[
'data' => [
'id' => '333',
'pid' => '3331',
'aid' => '0',
],
'expected_data' => [
'category' => [
[
'request_path' => 'category-1.html',
'target_path' => 'category-with-slash-symbol/category-1.html',
'redirect_type' => OptionProvider::PERMANENT,
],
[
'request_path' => 'category-with-slash-symbol/category-1.html',
'target_path' => 'catalog/category/view/id/333',
],
],
'product' => [
[
'request_path' => 'category-with-slash-symbol/simple-product-three.html',
'target_path' => 'catalog/product/view/id/333/category/3331',
],
[
'request_path' => 'category-with-slash-symbol/category-1/simple-product-three.html',
'target_path' => 'catalog/product/view/id/333/category/333',
],
],
],
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Catalog/_files/category.php
* @magentoAppArea adminhtml
* @return void
*/
public function testUrlRewritesAfterCategoryDelete(): void
{
$categoryId = 333;
$categoryItemIds = $this->getCategoryRewriteCollection($categoryId)->getAllIds();
$this->categoryRepository->deleteByIdentifier($categoryId);
$this->assertEmpty(
array_intersect($this->getAllRewriteIds(), $categoryItemIds),
'Not all expected category url rewrites were deleted'
);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_product_ids.php
* @return void
*/
public function testUrlRewritesAfterCategoryWithProductsDelete(): void
{
$category = $this->categoryRepository->get(3);
$childIds = explode(',', $category->getAllChildren());
$productRewriteIds = $this->getProductRewriteCollection($childIds)->getAllIds();
$categoryItemIds = $this->getCategoryRewriteCollection($childIds)->getAllIds();
$this->categoryRepository->deleteByIdentifier($category->getId());
$allIds = $this->getAllRewriteIds();
$this->assertEmpty(
array_intersect($allIds, $categoryItemIds),
'Not all expected category url rewrites were deleted'
);
$this->assertEmpty(
array_intersect($allIds, $productRewriteIds),
'Not all expected category-product url rewrites were deleted'
);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoDataFixture Magento/Catalog/_files/category.php
* @return void
*/
public function testCategoryUrlRewritePerStoreViews(): void
{
$urlSuffix = $this->config->getValue(
CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX,
ScopeInterface::SCOPE_STORE
);
$urlKeySecondStore = 'url-key-for-second-store';
$secondStoreId = $this->storeRepository->get('fixture_second_store')->getId();
$categoryId = 333;
$category = $this->categoryRepository->get($categoryId);
$urlKeyFirstStore = $category->getUrlKey();
$category->setStoreId($secondStoreId);
$category->setUrlKey($urlKeySecondStore);
$categoryResource = $this->categoryResourceFactory->create();
$categoryResource->save($category);
$urlRewriteItems = $this->getCategoryRewriteCollection($categoryId)->getItems();
foreach ($urlRewriteItems as $item) {
$item->getData('store_id') == $secondStoreId
? $this->assertEquals($urlKeySecondStore . $urlSuffix, $item->getRequestPath())
: $this->assertEquals($urlKeyFirstStore . $urlSuffix, $item->getRequestPath());
}
}
/**
* Get products url rewrites collection referred to categories
*
* @param string|array $categoryId
* @return UrlRewriteCollection
*/
private function getProductRewriteCollection($categoryId): UrlRewriteCollection
{
$condition = is_array($categoryId) ? ['in' => $categoryId] : $categoryId;
$productRewriteCollection = $this->urlRewriteCollectionFactory->create();
$productRewriteCollection
->join(
['p' => Product::TABLE_NAME],
'main_table.url_rewrite_id = p.url_rewrite_id',
'category_id'
)
->addFieldToFilter('category_id', $condition)
->addFieldToFilter(UrlRewrite::ENTITY_TYPE, ['eq' => DataProductUrlRewriteDatabaseMap::ENTITY_TYPE]);
return $productRewriteCollection;
}
/**
* Retrieve all rewrite ids
*
* @return array
*/
private function getAllRewriteIds(): array
{
$urlRewriteCollection = $this->urlRewriteCollectionFactory->create();
return $urlRewriteCollection->getAllIds();
}
/**
* Get category url rewrites collection
*
* @param string|array $categoryId
* @return UrlRewriteCollection
*/
private function getCategoryRewriteCollection($categoryId): UrlRewriteCollection
{
$condition = is_array($categoryId) ? ['in' => $categoryId] : $categoryId;
$categoryRewriteCollection = $this->urlRewriteCollectionFactory->create();
$categoryRewriteCollection->addFieldToFilter(UrlRewrite::ENTITY_ID, $condition)
->addFieldToFilter(UrlRewrite::ENTITY_TYPE, ['eq' => DataCategoryUrlRewriteDatabaseMap::ENTITY_TYPE]);
return $categoryRewriteCollection;
}
/**
* Check that actual data contains of expected values
*
* @param UrlRewriteCollection $collection
* @param array $expectedData
* @return void
*/
private function assertRewrites(UrlRewriteCollection $collection, array $expectedData): void
{
$collectionItems = $collection->toArray()['items'];
foreach ($collectionItems as $item) {
$found = false;
foreach ($expectedData as $expectedItem) {
$found = array_intersect_assoc($item, $expectedItem) == $expectedItem;
if ($found) {
break;
}
}
$this->assertTrue($found, 'The actual data does not contains of expected values');
}
}
}
@@ -0,0 +1,92 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Model\Product;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\CatalogUrlRewrite\Model\ObjectRegistryFactory;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Verify generate url rewrites for anchor categories.
*/
class AnchorUrlRewriteGeneratorTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ObjectRegistryFactory
*/
private $objectRegistryFactory;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->objectRegistryFactory = $this->objectManager->create(ObjectRegistryFactory::class);
}
/**
* Verify correct generate of the relative "StoreId"
*
* @param string $expect
* @return void
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_with_stores.php
* @magentoDbIsolation disabled
* @dataProvider getConfigGenerate
*/
public function testGenerate(string $expect): void
{
$product = $this->productRepository->get('simple');
$categories = $product->getCategoryCollection();
$productCategories = $this->objectRegistryFactory->create(['entities' => $categories]);
/** @var AnchorUrlRewriteGenerator $generator */
$generator = $this->objectManager->get(AnchorUrlRewriteGenerator::class);
/** @var $store Store */
$store = Bootstrap::getObjectManager()->get(Store::class);
$store->load('fixture_second_store', 'code');
$urls = $generator->generate($store->getId(), $product, $productCategories);
$this->assertEquals($expect, $urls[0]->getRequestPath());
}
/**
* Data provider for testGenerate
*
* @return array
*/
public function getConfigGenerate(): array
{
return [
[
'expect' => 'category-1-custom/simple-product.html'
]
];
}
}
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogUrlRewrite\Model;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
*/
class ProductUrlRewriteGeneratorTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_with_category.php
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDbIsolation disabled
* @magentoAppIsolation enabled
*/
public function testGenerateWithSpecificCategoryUrlKey()
{
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get('p002');
// set global store
$product->setStoreId(0);
/** @var ProductUrlRewriteGenerator $generator */
$generator = $this->objectManager->get(ProductUrlRewriteGenerator::class);
$urls = $generator->generate($product);
$actualUrls = array_map(
function ($url) {
/** @var \Magento\UrlRewrite\Service\V1\Data\UrlRewrite $url */
return $url->getRequestPath();
},
$urls
);
self::assertTrue(in_array('p002.html', $actualUrls));
self::assertTrue(in_array('cat-1/p002.html', $actualUrls));
self::assertTrue(in_array('cat-1-2/p002.html', $actualUrls));
}
}
@@ -0,0 +1,390 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Model;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Type;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
use Magento\CatalogImportExport\Model\Import\Product;
use Magento\CatalogUrlRewrite\Model\Map\DataProductUrlRewriteDatabaseMap;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\ImportExport\Model\Import;
use Magento\ImportExport\Model\Import\Source\Csv;
use Magento\Store\Model\ScopeInterface;
use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException;
use Magento\UrlRewrite\Model\OptionProvider;
use Psr\Log\LoggerInterface;
/**
* Class for product url rewrites tests
*
* @magentoDbIsolation enabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProductUrlRewriteTest extends AbstractUrlRewriteTest
{
/** @var ProductFactory */
private $productFactory;
/** @var string */
private $suffix;
/** @var ProductResource */
private $productResource;
/** @var ProductRepositoryInterface */
private $productRepository;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->productResource = $this->objectManager->create(ProductResource::class);
$this->productFactory = $this->objectManager->get(ProductFactory::class);
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->suffix = $this->config->getValue(
ProductUrlPathGenerator::XML_PATH_PRODUCT_URL_SUFFIX,
ScopeInterface::SCOPE_STORE
);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @dataProvider productDataProvider
* @param array $data
* @return void
*/
public function testUrlRewriteOnProductSave(array $data): void
{
$product = $this->saveProduct($data['data']);
$this->assertNotNull($product->getId(), 'The product was not created');
$productUrlRewriteCollection = $this->getEntityRewriteCollection($product->getId());
$this->assertRewrites(
$productUrlRewriteCollection,
$this->prepareData($data['expected_data'], (int)$product->getId())
);
}
/**
* @return array
*/
public function productDataProvider(): array
{
return [
'without_url_key' => [
[
'data' => [
'type_id' => Type::TYPE_SIMPLE,
'visibility' => Visibility::VISIBILITY_BOTH,
'attribute_set_id' => 4,
'sku' => 'test-product',
'name' => 'test product',
'price' => 150,
'website_ids' => [1]
],
'expected_data' => [
[
'request_path' => 'test-product%suffix%',
'target_path' => 'catalog/product/view/id/%id%',
],
],
],
],
'with_url_key' => [
[
'data' => [
'type_id' => Type::TYPE_SIMPLE,
'attribute_set_id' => 4,
'sku' => 'test-product',
'visibility' => Visibility::VISIBILITY_BOTH,
'name' => 'test product',
'price' => 150,
'url_key' => 'test-product-url-key',
'website_ids' => [1]
],
'expected_data' => [
[
'request_path' => 'test-product-url-key%suffix%',
'target_path' => 'catalog/product/view/id/%id%',
],
],
],
],
'with_invisible_product' => [
[
'data' => [
'type_id' => Type::TYPE_SIMPLE,
'attribute_set_id' => 4,
'sku' => 'test-product',
'visibility' => Visibility::VISIBILITY_NOT_VISIBLE,
'name' => 'test product',
'price' => 150,
'url_key' => 'test-product-url-key',
'website_ids' => [1]
],
'expected_data' => [],
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_simple.php
* @dataProvider productEditProvider
* @param array $expectedData
* @return void
*/
public function testUrlRewriteOnProductEdit(array $expectedData): void
{
$product = $this->productRepository->get('simple');
$data = [
'url_key' => 'new-url-key',
'url_key_create_redirect' => $product->getUrlKey(),
'save_rewrites_history' => true,
];
$product = $this->saveProduct($data, $product);
$productRewriteCollection = $this->getEntityRewriteCollection($product->getId());
$this->assertRewrites(
$productRewriteCollection,
$this->prepareData($expectedData, (int)$product->getId())
);
}
/**
* @return array
*/
public function productEditProvider(): array
{
return [
[
'expected_data' => [
[
'request_path' => 'new-url-key%suffix%',
'target_path' => 'catalog/product/view/id/%id%',
],
[
'request_path' => 'simple-product%suffix%',
'target_path' => 'new-url-key%suffix%',
'redirect_type' => OptionProvider::PERMANENT,
],
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/category_with_products.php
* @dataProvider existingUrlKeyProvider
* @param array $data
* @return void
*/
public function testUrlRewriteOnProductSaveWithExistingUrlKey(array $data): void
{
$this->expectException(UrlAlreadyExistsException::class);
$this->expectExceptionMessage((string)__('URL key for specified store already exists.'));
$this->saveProduct($data);
}
/**
* @return array
*/
public function existingUrlKeyProvider(): array
{
return [
[
'with_specified_existing_product_url_key' => [
'type_id' => Type::TYPE_SIMPLE,
'attribute_set_id' => 4,
'sku' => 'test-simple-product',
'name' => 'test-simple-product',
'price' => 150,
'url_key' => 'simple-product',
'store_ids' => [1]
],
'with_autogenerated_existing_product_url_key' => [
'type_id' => Type::TYPE_SIMPLE,
'attribute_set_id' => 4,
'sku' => 'test-simple-product',
'name' => 'simple product',
'price' => 150,
'store_ids' => [1]
],
'with_specified_existing_category_url_key' => [
'type_id' => Type::TYPE_SIMPLE,
'attribute_set_id' => 4,
'sku' => 'test-simple-product',
'name' => 'test-simple-product',
'price' => 150,
'url_key' => 'category-1',
'store_ids' => [1]
],
'with_autogenerated_existing_category_url_key' => [
'type_id' => Type::TYPE_SIMPLE,
'attribute_set_id' => 4,
'sku' => 'test-simple-product',
'name' => 'category 1',
'price' => 150,
'store_ids' => [1]
],
],
];
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
*/
public function testUrlRewritesAfterProductDelete(): void
{
$product = $this->productRepository->get('simple2');
$rewriteIds = $this->getEntityRewriteCollection($product->getId())->getAllIds();
$this->productRepository->delete($product);
$this->assertEmpty(
array_intersect($this->getAllRewriteIds(), $rewriteIds),
'Not all expected category url rewrites were deleted'
);
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* @magentoDbIsolation disabled
* @magentoDataFixture Magento/Store/_files/second_store.php
* @magentoDataFixture Magento/Catalog/_files/second_product_simple.php
* @return void
*/
public function testProductUrlRewritePerStoreViews(): void
{
$urlKeySecondStore = 'url-key-for-second-store';
$secondStoreId = $this->storeRepository->get('fixture_second_store')->getId();
$product = $this->productRepository->get('simple2');
$urlKeyFirstStore = $product->getUrlKey();
$product = $this->saveProduct(
['store_id' => $secondStoreId, 'url_key' => $urlKeySecondStore],
$product
);
$urlRewriteItems = $this->getEntityRewriteCollection($product->getId())->getItems();
$this->assertTrue(count($urlRewriteItems) == 2);
foreach ($urlRewriteItems as $item) {
$item->getData('store_id') == $secondStoreId
? $this->assertEquals($urlKeySecondStore . $this->suffix, $item->getRequestPath())
: $this->assertEquals($urlKeyFirstStore . $this->suffix, $item->getRequestPath());
}
}
/**
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
* Check if redirects are generated correctly while product urls are changed during import process.
*
* @magentoDataFixture Magento/Catalog/_files/multiple_products.php
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
public function testImportProductRewrites()
{
$data = [
['sku' => 'simple1', 'request_path' => 'simple-product1', 'target_path' => 'product-1-updated'],
['sku' => 'simple2', 'request_path' => 'simple-product2', 'target_path' => 'product-2-updated'],
['sku' => 'simple3', 'request_path' => 'simple-product3', 'target_path' => 'product-3-updated'],
];
$logger = $this->getMockBuilder(LoggerInterface::class)
->disableOriginalConstructor()
->getMockForAbstractClass();
$productImport = $this->objectManager->create(
Product::class,
['logger' => $logger]
);
$filesystem = $this->objectManager->get(Filesystem::class);
foreach ($data as $datum) {
$this->assertEquals(
$datum['request_path'],
$this->productRepository->get($datum['sku'], false, null, true)->getUrlKey()
);
}
$directory = $filesystem->getDirectoryWrite(DirectoryList::ROOT);
$source = $this->objectManager->create(
Csv::class,
[
'file' => __DIR__ . '/../_files/products_to_import_with_rewrites.csv',
'directory' => $directory
]
);
$errors = $productImport->setParameters(
['behavior' => Import::BEHAVIOR_APPEND, 'entity' => 'catalog_product']
)->setSource(
$source
)->validateData();
$this->assertTrue($errors->getErrorsCount() === 0);
$productImport->importData();
foreach ($data as $datum) {
$product = $this->productRepository->get($datum['sku'], false, null, true);
$this->assertEquals(
$datum['target_path'],
$product->getUrlKey()
);
$productUrlRewriteCollection = $this->getEntityRewriteCollection($product->getId());
$rewriteExists = false;
foreach ($productUrlRewriteCollection as $item) {
if ($item->getTargetPath() === $datum['target_path'] . $this->suffix &&
$item->getRequestPath() === $datum['request_path'] . $this->suffix) {
$rewriteExists = true;
break;
}
}
$this->assertTrue($rewriteExists);
}
}
/**
* Save product with data using resource model directly
*
* @param array $data
* @param ProductInterface|null $product
* @return ProductInterface
*/
protected function saveProduct(array $data, $product = null): ProductInterface
{
$product = $product ?: $this->productFactory->create();
$product->addData($data);
$this->productResource->save($product);
return $product;
}
/**
* @inheritdoc
*/
protected function getUrlSuffix(): string
{
return $this->suffix;
}
/**
* @inheritdoc
*/
protected function getEntityType(): string
{
return DataProductUrlRewriteDatabaseMap::ENTITY_TYPE;
}
}
@@ -0,0 +1,188 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogUrlRewrite\Observer;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator;
/**
* Test Cases:
*
* - has changes for url_key, is_anchor, changed product list
* - in global scope
* - in store
* - generate canonical
* - generate children
* - has children
* - generate current
* - has rewrites history
* @magentoAppArea adminhtml
*/
class CategoryProcessUrlRewriteSavingObserverTest extends \PHPUnit\Framework\TestCase
{
/** @var \Magento\Framework\ObjectManagerInterface */
protected $objectManager;
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
}
/**
* @param array $filter
* @return array
*/
private function getActualResults(array $filter)
{
/** @var \Magento\UrlRewrite\Model\UrlFinderInterface $urlFinder */
$urlFinder = $this->objectManager->get(\Magento\UrlRewrite\Model\UrlFinderInterface::class);
$actualResults = [];
foreach ($urlFinder->findAllByData($filter) as $url) {
$actualResults[] = [
'request_path' => $url->getRequestPath(),
'target_path' => $url->getTargetPath(),
'is_auto_generated' => (int)$url->getIsAutogenerated(),
'redirect_type' => $url->getRedirectType()
];
}
return $actualResults;
}
protected function tearDown(): void
{
$category = $this->objectManager->create(\Magento\Catalog\Model\Category::class);
$category->load(3);
$category->delete();
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
public function testUrlKeyHasChanged()
{
$categoryFilter = [
UrlRewrite::ENTITY_TYPE => 'category',
];
$expected = [
[
'request_path' => "category-1.html",
'target_path' => "catalog/category/view/id/3",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-1/category-1-1.html",
'target_path' => "catalog/category/view/id/4",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-1/category-1-1/category-1-1-1.html",
'target_path' => "catalog/category/view/id/5",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-2.html",
'target_path' => "catalog/category/view/id/6",
'is_auto_generated' => 1,
'redirect_type' => 0
]
];
$actual = $this->getActualResults($categoryFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
/** @var \Magento\Catalog\Model\Category $category */
$category = $this->objectManager->create(\Magento\Catalog\Model\Category::class);
$category->load(3);
$category->setData('save_rewrites_history', false);
$category->setUrlKey('new-url');
$category->save();
$expected = [
[
'request_path' => "new-url.html",
'target_path' => "catalog/category/view/id/3",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "new-url/category-1-1.html",
'target_path' => "catalog/category/view/id/4",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "new-url/category-1-1/category-1-1-1.html",
'target_path' => "catalog/category/view/id/5",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-2.html",
'target_path' => "catalog/category/view/id/6",
'is_auto_generated' => 1,
'redirect_type' => 0
]
];
$actual = $this->getActualResults($categoryFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/categories_with_products.php
* @magentoDbIsolation enabled
* @magentoAppIsolation enabled
*/
public function testIsAnchorHasChanged()
{
$categoryFilter = [
UrlRewrite::ENTITY_TYPE => CategoryUrlRewriteGenerator::ENTITY_TYPE,
];
/** @var \Magento\Catalog\Model\Category $category */
$category = $this->objectManager->create(\Magento\Catalog\Model\Category::class);
$category->load(3);
$category->setData('is_anchor', false);
$category->save();
$expected = [
[
'request_path' => "category-1.html",
'target_path' => "catalog/category/view/id/3",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-1/category-1-1.html",
'target_path' => "catalog/category/view/id/4",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-1/category-1-1/category-1-1-1.html",
'target_path' => "catalog/category/view/id/5",
'is_auto_generated' => 1,
'redirect_type' => 0
],
[
'request_path' => "category-2.html",
'target_path' => "catalog/category/view/id/6",
'is_auto_generated' => 1,
'redirect_type' => 0
]
];
$actual = $this->getActualResults($categoryFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
}
}
@@ -0,0 +1,292 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogUrlRewrite\Observer;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Test\Fixture\Category as CategoryFixture;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Framework\Event\ManagerInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Test\Fixture\Group as StoreGroupFixture;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\Store\Test\Fixture\Website as WebsiteFixture;
use Magento\TestFramework\Fixture\AppIsolation;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\Exception\UrlAlreadyExistsException;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class ProcessUrlRewriteOnChangeVisibilityObserverTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ManagerInterface
*/
private $eventManager;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->create(ProductRepositoryInterface::class);
$this->eventManager = $this->objectManager->create(ManagerInterface::class);
$this->fixtures = Bootstrap::getObjectManager()->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @magentoAppIsolation enabled
*/
public function testMakeProductInvisibleViaMassAction()
{
/** @var \Magento\Catalog\Model\Product $product*/
$product = $this->productRepository->get('product1');
/** @var StoreManagerInterface $storeManager */
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$firstStore = current($product->getStoreIds());
$testStore = $storeManager->getStore('test');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $firstStore,
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore->getId(),
]
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
$this->eventManager->dispatch(
'catalog_product_attribute_update_before',
[
'attributes_data' => [ ProductInterface::VISIBILITY => Visibility::VISIBILITY_NOT_VISIBLE ],
'product_ids' => [$product->getId()],
'store_id' => $firstStore,
]
);
$actual = $this->getActualResults($productFilter);
//Initially count was 2, when visibility of 1 store view is set to not visible individually, the new count is 1
$this->assertCount(1, $actual);
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_invisible_multistore.php
* @magentoAppIsolation enabled
*/
public function testMakeProductVisibleViaMassAction()
{
/** @var \Magento\Catalog\Model\Product $product*/
$product = $this->productRepository->get('product1');
/** @var StoreManagerInterface $storeManager */
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$storeManager->setCurrentStore(0);
$testStore = $storeManager->getStore('test');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
$actual = $this->getActualResults($productFilter);
$this->assertCount(0, $actual);
$this->eventManager->dispatch(
'catalog_product_attribute_update_before',
[
'attributes_data' => [ ProductInterface::VISIBILITY => Visibility::VISIBILITY_BOTH ],
'product_ids' => [$product->getId()]
]
);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => '1',
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore->getId(),
]
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
}
/**
* Test for multistore properties of the product to be respected in generated UrlRewrites
* during the mass update for visibility change
*
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
*/
#[
AppIsolation(true),
DataFixture(WebsiteFixture::class, as: 'w1'),
DataFixture(StoreGroupFixture::class, ['website_id' => '$w1.id$'], 'g1'),
DataFixture(StoreFixture::class, ['store_group_id' => '$g1.id$'], 's1'),
DataFixture(CategoryFixture::class, as: 'c1'),
DataFixture(
ProductFixture::class,
['category_ids' => ['$c1.id$'], 'visibility' => 1, 'website_ids' => [1, '$w1.id$']],
'p1'
),
]
public function testMassActionUrlRewriteForStore()
{
$product = $this->fixtures->get('p1');
$category = $this->fixtures->get('c1');
$store = $this->fixtures->get('s1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
$beforeUpdate = $this->getActualResults($productFilter);
$this->assertCount(0, $beforeUpdate);
$this->eventManager->dispatch(
'catalog_product_attribute_update_before',
[
'attributes_data' => [ ProductInterface::VISIBILITY => Visibility::VISIBILITY_BOTH ],
'product_ids' => [$product->getId()],
'store_id' => Store::DEFAULT_STORE_ID
]
);
$expected = [
[
'request_path' => $product->getUrlKey() . ".html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => (String) Store::DISTRO_STORE_ID
],
[
'request_path' => $category->getUrlKey() . '/' . $product->getUrlKey() . ".html",
'target_path' => "catalog/product/view/id/" . $product->getId() . '/category/' . $category->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => (String) Store::DISTRO_STORE_ID
],
[
'request_path' => $product->getUrlKey() . ".html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => (String) $store->getId()
],
[
'request_path' => $category->getUrlKey() . '/' . $product->getUrlKey() . ".html",
'target_path' => "catalog/product/view/id/" . $product->getId() . '/category/' . $category->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => (String) $store->getId()
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/products_invisible.php
* @magentoAppIsolation enabled
*/
public function testErrorOnDuplicatedUrlKey()
{
$skus = ['product1', 'product2'];
foreach ($skus as $sku) {
/** @var \Magento\Catalog\Model\Product $product */
$productIds[] = $this->productRepository->get($sku)->getId();
}
$this->expectException(UrlAlreadyExistsException::class);
$this->expectExceptionMessage('Can not change the visibility of the product with SKU equals "product2". '
. 'URL key "product-1" for specified store already exists.');
$this->eventManager->dispatch(
'catalog_product_attribute_update_before',
[
'attributes_data' => [ ProductInterface::VISIBILITY => Visibility::VISIBILITY_BOTH ],
'product_ids' => $productIds
]
);
}
/**
* @param array $filter
* @return array
*/
private function getActualResults(array $filter)
{
/** @var \Magento\UrlRewrite\Model\UrlFinderInterface $urlFinder */
$urlFinder = $this->objectManager->get(\Magento\UrlRewrite\Model\UrlFinderInterface::class);
$actualResults = [];
foreach ($urlFinder->findAllByData($filter) as $url) {
$actualResults[] = [
'request_path' => $url->getRequestPath(),
'target_path' => $url->getTargetPath(),
'is_auto_generated' => (int)$url->getIsAutogenerated(),
'redirect_type' => $url->getRedirectType(),
'store_id' => $url->getStoreId()
];
}
return $actualResults;
}
}
@@ -0,0 +1,690 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogUrlRewrite\Observer;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Catalog\Model\ProductFactory;
use Magento\Catalog\Test\Fixture\Product as ProductFixture;
use Magento\Framework\ObjectManagerInterface;
use Magento\Store\Model\Store;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Test\Fixture\Group as GroupFixture;
use Magento\Store\Test\Fixture\Store as StoreFixture;
use Magento\Store\Test\Fixture\Website as WebsiteFixture;
use Magento\TestFramework\Fixture\DataFixture;
use Magento\TestFramework\Fixture\DataFixtureStorage;
use Magento\TestFramework\Fixture\DataFixtureStorageManager;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\UrlFinderInterface;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class ProductProcessUrlRewriteSavingObserverTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var StoreManagerInterface
*/
private $storeManager;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var DataFixtureStorage
*/
private $fixtures;
/**
* Set up
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->storeManager = $this->objectManager->get(StoreManagerInterface::class);
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->fixtures = $this->objectManager->get(DataFixtureStorageManager::class)->getStorage();
}
/**
* @param array $filter
* @return array
*/
private function getActualResults(array $filter)
{
/** @var UrlFinderInterface $urlFinder */
$urlFinder = $this->objectManager->get(UrlFinderInterface::class);
$actualResults = [];
foreach ($urlFinder->findAllByData($filter) as $url) {
$actualResults[$url->getRequestPath() . '-' . $url->getStoreId()] = [
'request_path' => $url->getRequestPath(),
'target_path' => $url->getTargetPath(),
'is_auto_generated' => (int)$url->getIsAutogenerated(),
'redirect_type' => $url->getRedirectType(),
'store_id' => $url->getStoreId()
];
}
return $actualResults;
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @magentoAppIsolation enabled
*/
public function testUrlKeyHasChangedInGlobalContext()
{
$testStore1 = $this->storeManager->getStore('default');
$testStore4 = $this->storeManager->getStore('test');
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
/** @var Product $product*/
$product = $this->productRepository->get('product1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContainsEquals($row, $actual);
}
$product->setData('save_rewrites_history', true);
$product->setUrlKey('new-url');
$product->setUrlPath('new-path');
$this->productRepository->save($product);
$expected = [
[
'request_path' => "new-url.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "new-url.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "new-url.html",
'is_auto_generated' => 0,
'redirect_type' => 301,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "new-url.html",
'is_auto_generated' => 0,
'redirect_type' => 301,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContainsEquals($row, $actual);
}
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @magentoAppIsolation enabled
*/
public function testUrlKeyHasChangedInStoreviewContextWithPermanentRedirection()
{
$testStore1 = $this->storeManager->getStore('default');
$testStore4 = $this->storeManager->getStore('test');
$this->storeManager->setCurrentStore($testStore1);
/** @var Product $product*/
$product = $this->productRepository->get('product1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
$product->setData('save_rewrites_history', true);
$product->setUrlKey('new-url');
$product->setUrlPath('new-path');
$this->productRepository->save($product);
$expected = [
[
'request_path' => "new-url.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "new-url.html",
'is_auto_generated' => 0,
'redirect_type' => 301,
'store_id' => $testStore1->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContainsEquals($row, $actual);
}
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @magentoAppIsolation enabled
*/
public function testUrlKeyHasChangedInStoreviewContextWithoutPermanentRedirection()
{
$testStore1 = $this->storeManager->getStore('default');
$testStore4 = $this->storeManager->getStore('test');
$this->storeManager->setCurrentStore(1);
/** @var Product $product*/
$product = $this->productRepository->get('product1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
$product->setData('save_rewrites_history', false);
$product->setUrlKey('new-url');
$product->setUrlPath('new-path');
$this->productRepository->save($product);
$expected = [
[
'request_path' => "new-url.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
}
/**
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @magentoAppIsolation enabled
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testAddAndRemoveProductFromWebsite()
{
$testStore1 = $this->storeManager->getStore('default');
$testStore2 = $this->storeManager->getStore('fixture_second_store');
$testStore3 = $this->storeManager->getStore('fixture_third_store');
$testStore4 = $this->storeManager->getStore('test');
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
/** @var Product $product*/
$product = $this->productRepository->get('product1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
//Product in 1st website. Should result in being in 1st and 4th stores.
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
//Add product to websites corresponding to all 4 stores.
//Rewrites should be present for all stores.
$product->setWebsiteIds(
array_unique(
[
$testStore1->getWebsiteId(),
$testStore2->getWebsiteId(),
$testStore3->getWebsiteId(),
$testStore4->getWebsiteId(),
]
)
);
$this->productRepository->save($product);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore2->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore3->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
]
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
//Remove product from stores 1 and 4 and leave assigned to stores 2 and 3.
$product->setWebsiteIds(
array_unique(
[
$testStore2->getWebsiteId(),
$testStore3->getWebsiteId(),
]
)
);
$this->productRepository->save($product);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore2->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore3->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
}
/**
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testChangeVisibilityGlobalScope()
{
$testStore1 = $this->storeManager->getStore('default');
$testStore2 = $this->storeManager->getStore('fixture_second_store');
$testStore3 = $this->storeManager->getStore('fixture_third_store');
$testStore4 = $this->storeManager->getStore('test');
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
/** @var Product $product*/
$product = $this->productRepository->get('product1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
UrlRewrite::ENTITY_ID => $product->getId(),
];
//Product in 1st website. Should result in being in 1st and 4th stores.
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
]
];
$actual = $this->getActualResults($productFilter);
$this->assertEqualsCanonicalizing($expected, $actual);
/** @var Product $product*/
$store4Product = $this->objectManager->get(ProductFactory::class)->create();
$store4Product->setStoreId($testStore4->getId());
$store4Product->setSku($product->getSku());
$store4Product->setUrlKey('product-1-store4');
$this->productRepository->save($store4Product);
//Set product to be not visible at global scope
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
$product->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE);
$this->productRepository->save($product);
$this->assertEmpty($this->getActualResults($productFilter));
//Add product to websites corresponding to all 4 stores.
//Rewrites should not be present as the product is hidden
//at the global scope.
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
$product->setWebsiteIds(
array_unique(
[
$testStore1->getWebsiteId(),
$testStore2->getWebsiteId(),
$testStore3->getWebsiteId(),
$testStore4->getWebsiteId(),
]
)
);
$this->productRepository->save($product);
$actual = $this->getActualResults($productFilter);
$this->assertEmpty($actual);
//Set product to be visible at global scope
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
$product->setVisibility(Visibility::VISIBILITY_BOTH);
$this->productRepository->save($product);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore2->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore3->getId(),
],
[
'request_path' => "product-1-store4.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
$this->assertEqualsCanonicalizing($expected, $actual);
}
/**
* @magentoDataFixture Magento/Store/_files/second_website_with_two_stores.php
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/product_rewrite_multistore.php
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function testChangeVisibilityLocalScope()
{
$testStore1 = $this->storeManager->getStore('default');
$testStore2 = $this->storeManager->getStore('fixture_second_store');
$testStore3 = $this->storeManager->getStore('fixture_third_store');
$testStore4 = $this->storeManager->getStore('test');
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
/** @var Product $product*/
$product = $this->productRepository->get('product1');
$productFilter = [
UrlRewrite::ENTITY_TYPE => 'product',
];
//Product in 1st website. Should result in being in 1st and 4th stores.
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
//Set product to be not visible at store 4 scope
//Rewrite should only be present for store 1
$this->storeManager->setCurrentStore($testStore4);
$product = $this->productRepository->get('product1');
$product->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE);
$this->productRepository->save($product);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
self::assertCount(count($expected), $actual);
//Add product to websites corresponding to all 4 stores.
//Rewrites should be present for stores 1,2 and 3.
//No rewrites should be present for store 4 as that is not visible
//at local scope.
$this->storeManager->setCurrentStore(Store::DEFAULT_STORE_ID);
$product = $this->productRepository->get('product1');
$product->getExtensionAttributes()->setWebsiteIds(
array_unique(
[
$testStore1->getWebsiteId(),
$testStore2->getWebsiteId(),
$testStore3->getWebsiteId(),
$testStore4->getWebsiteId()
],
)
);
$this->productRepository->save($product);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore2->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore3->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContains($row, $actual);
}
//Set product to be visible at store 4 scope only
$this->storeManager->setCurrentStore($testStore4);
$product = $this->productRepository->get('product1');
$product->setVisibility(Visibility::VISIBILITY_BOTH);
$this->productRepository->save($product);
$expected = [
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore2->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore3->getId(),
],
[
'request_path' => "product-1.html",
'target_path' => "catalog/product/view/id/" . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore4->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($expected as $row) {
$this->assertContainsEquals($row, $actual);
}
}
#[
DataFixture(WebsiteFixture::class, as: 'website'),
DataFixture(GroupFixture::class, ['website_id' => '$website.id$'], 'store_group'),
DataFixture(StoreFixture::class, ['store_group_id' => '$store_group.id$'], 'store'),
DataFixture(ProductFixture::class, ['sku' => 'simple1', 'website_ids' => [1,'$website.id$'], 'product']),
]
public function testRemoveProductFromAllWebsites(): void
{
$testStore1 = $this->storeManager->getStore('default');
$testStore2 = $this->fixtures->get('store');
$productFilter = [UrlRewrite::ENTITY_TYPE => 'product'];
/** @var Product $product*/
$product = $this->productRepository->get('simple1');
$product->setWebsiteIds([])
->setVisibility(Visibility::VISIBILITY_NOT_VISIBLE);
$this->productRepository->save($product);
$unexpected = [
[
'request_path' => 'simple1.html',
'target_path' => 'catalog/product/view/id/' . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore1->getId(),
],
[
'request_path' => 'simple1.html',
'target_path' => 'catalog/product/view/id/' . $product->getId(),
'is_auto_generated' => 1,
'redirect_type' => 0,
'store_id' => $testStore2->getId(),
],
];
$actual = $this->getActualResults($productFilter);
foreach ($unexpected as $row) {
$this->assertNotContains($row, $actual);
}
}
}
@@ -0,0 +1,139 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Observer;
use Magento\Catalog\Api\CategoryListInterface;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
* @magentoDbIsolation disabled
*/
class UrlRewriteHandlerTest extends TestCase
{
/**
* @var UrlRewriteHandler
*/
private $handler;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* @var ObjectManager
*/
private $objectManager;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->productRepository = $this->objectManager->get(ProductRepositoryInterface::class);
$this->handler = $this->objectManager->create(UrlRewriteHandler::class);
}
/**
* Checks category URLs rewrites generation with enabled `Use Categories Path for Product URLs` option and
* store's specific product URL key.
*
* @magentoDataFixture Magento/CatalogUrlRewrite/Fixtures/product_custom_url_key.php
* @magentoConfigFixture admin_store catalog/seo/product_use_categories 1
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
*/
public function testGenerateProductUrlRewrites()
{
$product = $this->productRepository->get('p002');
$category = $this->getCategory('category 1');
// change the category scope to the global
$category->setStoreId(0)
->setChangedProductIds([$product->getId()])
->setAffectedProductIds([$product->getId()])
->setAnchorsAbove(false);
$generatedUrls = $this->handler->generateProductUrlRewrites($category);
$actual = array_values(
array_map(
function (UrlRewrite $urlRewrite) {
return $urlRewrite->getRequestPath();
},
$generatedUrls
)
);
$expected = [
'store-1-key.html', // the Default store
'cat-1/store-1-key.html', // the Default store with Category URL key
'/store-1-key.html', // an anchor URL the Default store
'p002.html', // the Secondary store
'cat-1-2/p002.html', // the Secondary store with Category URL key
'/p002.html', // an anchor URL the Secondary store
];
self::assertEquals($expected, $actual, 'Generated URLs rewrites do not match.');
}
/**
* @magentoDataFixture Magento/CatalogUrlRewrite/_files/category_with_products.php
* @magentoConfigFixture default/catalog/seo/generate_category_product_rewrites 1
*/
public function testGenerateProductUrlRewrites2()
{
$product1 = $this->productRepository->get('simple');
$product2 = $this->productRepository->get('12345');
$category = $this->getCategory('Category 1');
$category->setChangedProductIds([$product1->getId()]);
$category->setAffectedProductIds([$product1->getId(), $product2->getId()]);
$category->setAnchorsAbove(false);
$generatedUrls = $this->handler->generateProductUrlRewrites($category);
$actual = array_values(
array_map(
function (UrlRewrite $urlRewrite) {
return $urlRewrite->getRequestPath();
},
$generatedUrls
)
);
$expected = [
'simple-product.html',
'category-1/simple-product.html',
'/simple-product.html',
];
$this->assertEquals($expected, $actual, 'Generated URLs rewrites do not match.');
}
/**
* Gets category by name.
*
* @param string $name
* @return CategoryInterface
*/
private function getCategory(string $name): CategoryInterface
{
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('name', $name)
->create();
/** @var CategoryListInterface $repository */
$repository = $this->objectManager->get(CategoryListInterface::class);
$items = $repository->getList($searchCriteria)
->getItems();
return array_pop($items);
}
}
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogUrlRewrite\Plugin\Catalog\Block\Adminhtml\Category\Tab;
use Magento\Catalog\Model\Category\DataProvider;
use Magento\Eav\Model\Config as EavConfig;
use Magento\TestFramework\Helper\Bootstrap;
/**
* @magentoAppArea adminhtml
*/
class AttributesTest extends \PHPUnit\Framework\TestCase
{
/**
* @var DataProvider
*/
private $dataProvider;
/**
* @var \Magento\Eav\Model\Entity\Type
*/
private $entityType;
/**
* {@inheritDoc}
*/
protected function setUp(): void
{
parent::setUp();
$objectManager = Bootstrap::getObjectManager();
$this->dataProvider = $objectManager->create(
DataProvider::class,
[
'name' => 'category_form_data_source',
'primaryFieldName' => 'entity_id',
'requestFieldName' => 'id'
]
);
$this->entityType = $objectManager->create(EavConfig::class)->getEntityType('catalog_category');
}
/**
* test \Magento\CatalogUrlRewrite\Plugin\Catalog\Block\Adminhtml\Category\Tab\Attributes::afterGetAttributesMeta
* @return void
*/
public function testGetAttributesMeta()
{
$meta = $this->dataProvider->getMeta();
$this->assertArrayHasKey('url_key', $meta['search_engine_optimization']['children']);
$urlKeyData = $meta['search_engine_optimization']['children']['url_key']['arguments']['data']['config'];
$this->assertEquals('text', $urlKeyData['dataType']);
$this->assertEquals('input', $urlKeyData['formElement']);
$this->assertTrue($urlKeyData['visible']);
$this->assertFalse($urlKeyData['required']);
$this->assertEquals('[STORE VIEW]', $urlKeyData['scopeLabel']);
}
}
@@ -0,0 +1,118 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\CatalogUrlRewrite\Plugin\Catalog\Model\Product;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product\Action;
use Magento\Store\Api\StoreWebsiteRelationInterface;
use Magento\Store\Model\Website;
use Magento\Store\Model\WebsiteRepository;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea crontab
* @magentoDbIsolation disabled
*/
class UpdateProductWebsiteUrlRewritesTest extends TestCase
{
/**
* @var Action
*/
private $action;
/**
* @var StoreWebsiteRelationInterface
*/
private $storeWebsiteRelation;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->action = $objectManager->get(Action::class);
$this->storeWebsiteRelation = $objectManager->get(StoreWebsiteRelationInterface::class);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_url_key.php
* @magentoDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
*/
public function testUpdateUrlRewrites()
{
/** @var Website $website */
$websiteRepository = Bootstrap::getObjectManager()->get(WebsiteRepository::class);
$website = $websiteRepository->get('test');
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
$product = $productRepository->get('simple1', false, null, true);
$this->action->updateWebsites([$product->getId()], [$website->getId()], 'add');
$storeIds = $this->storeWebsiteRelation->getStoreByWebsiteId($website->getId());
$this->assertStringContainsString(
$product->getUrlKey() . '.html',
$product->setStoreId(reset($storeIds))->getProductUrl()
);
$this->action->updateWebsites([$product->getId()], [$website->getId()], 'remove');
$product->setRequestPath('');
$url = $product->setStoreId(reset($storeIds))->getProductUrl();
$this->assertStringNotContainsString(
$product->getUrlKey() . '.html',
$url
);
}
/**
* @magentoDataFixture Magento/Catalog/_files/product_simple_with_url_key.php
* @magentoDataFixture Magento/Store/_files/second_website_with_store_group_and_store.php
*/
public function testUpdateUrlRewritesForSecondProduct()
{
/** @var Website $website */
$websiteRepository = Bootstrap::getObjectManager()->get(WebsiteRepository::class);
$website = $websiteRepository->get('test');
$productRepository = Bootstrap::getObjectManager()->get(ProductRepositoryInterface::class);
// test the first product
$product = $productRepository->get('simple1', false, null, true);
// store filter condition about the first product in collection
$productCollection = Bootstrap::getObjectManager()->get(ProductCollection::class);
$productCollection->addFieldToFilter('entity_id', $product->getId());
$this->action->updateWebsites([$product->getId()], [$website->getId()], 'add');
$storeIds = $this->storeWebsiteRelation->getStoreByWebsiteId($website->getId());
$this->assertStringContainsString(
$product->getUrlKey() . '.html',
$product->setStoreId(reset($storeIds))->getProductUrl()
);
$this->action->updateWebsites([$product->getId()], [$website->getId()], 'remove');
$product->setRequestPath('');
$url = $product->setStoreId(reset($storeIds))->getProductUrl();
$this->assertStringNotContainsString(
$product->getUrlKey() . '.htmll',
$url
);
// test the second product
$product = $productRepository->get('simple2', false, null, true);
$this->action->updateWebsites([$product->getId()], [$website->getId()], 'add');
$storeIds = $this->storeWebsiteRelation->getStoreByWebsiteId($website->getId());
$this->assertStringContainsString(
$product->getUrlKey() . '.html',
$product->setStoreId(reset($storeIds))->getProductUrl()
);
$this->action->updateWebsites([$product->getId()], [$website->getId()], 'remove');
$product->setRequestPath('');
$url = $product->setStoreId(reset($storeIds))->getProductUrl();
$this->assertStringNotContainsString(
$product->getUrlKey() . '.html',
$url
);
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
/**
* After installation system has two categories: root one with ID:1 and Default category with ID:2
*/
/** @var $category \Magento\Catalog\Model\Category */
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Category::class);
$category->isObjectNew(true);
$category->setId(3)
->setName('Category 1')
->setParentId(2)
->setPath('1/2/3')
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(1)
->save();
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Category::class);
$category->isObjectNew(true);
$category->setId(4)
->setName('Category 1.1')
->setParentId(3)
->setPath('1/2/3/4')
->setLevel(3)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setIsAnchor(true)
->setPosition(1)
->save();
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Category::class);
$category->isObjectNew(true);
$category->setId(5)
->setName('Category 1.1.1')
->setParentId(4)
->setPath('1/2/3/4/5')
->setLevel(4)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(1)
->setCustomUseParentSettings(0)
->setCustomDesign('Magento/blank')
->save();
$category = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Category::class);
$category->isObjectNew(true);
$category->setId(6)
->setName('Category 2')
->setParentId(2)
->setPath('1/2/6')
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(2)
->save();
@@ -0,0 +1,22 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/** @var \Magento\Framework\Registry $registry */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Category\Collection::class);
$collection
->addAttributeToFilter('level', 2)
->load()
->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,65 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/categories.php');
/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Setup\CategorySetup::class
);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$categoryLinkRepository = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkRepositoryInterface::class,
[
'productRepository' => $productRepository
]
);
/** @var Magento\Catalog\Api\CategoryLinkManagementInterface $linkManagement */
$categoryLinkManagement = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkManagementInterface::class,
[
'productRepository' => $productRepository,
'categoryLinkRepository' => $categoryLinkRepository
]
);
/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(1)
->setId(1)
->setWebsiteIds([1])
->setName('Simple Product')
->setSku('simple')
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [2, 3, 4]);
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(1)
->setId(2)
->setWebsiteIds([1])
->setName('Simple Product Two')
->setSku('12345') // SKU intentionally contains digits only
->setPrice(45.67)
->setWeight(56)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [5]);
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var $productCollection \Magento\Catalog\Model\ResourceModel\Product\Collection */
$productCollection = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
$productCollection->load()->delete();
$productSkuList = ['simple', '12345'];
foreach ($productSkuList as $sku) {
try {
$productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$product = $productRepository->get($sku, true);
if ($product->getId()) {
$productRepository->delete($product);
}
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
//Product already removed
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/categories_rollback.php');
@@ -0,0 +1,63 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/categories.php');
/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Setup\CategorySetup::class
);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$categoryLinkRepository = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkRepositoryInterface::class,
[
'productRepository' => $productRepository
]
);
/** @var Magento\Catalog\Api\CategoryLinkManagementInterface $linkManagement */
$categoryLinkManagement = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkManagementInterface::class,
[
'productRepository' => $productRepository,
'categoryLinkRepository' => $categoryLinkRepository
]
);
/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(1)
->setWebsiteIds([1])
->setName('Simple Product')
->setSku('simple')
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [2, 3, 4]);
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(1)
->setWebsiteIds([1])
->setName('Simple Product Two')
->setSku('12345') // SKU intentionally contains digits only
->setPrice(45.67)
->setWeight(56)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [5]);
@@ -0,0 +1,28 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSkuList = ['simple', '12345'];
foreach ($productSkuList as $sku) {
try {
$product = $productRepository->get($sku, true);
$productRepository->delete($product);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
//Product already removed
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/categories_rollback.php');
@@ -0,0 +1,82 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Backend\App\Area\FrontNameResolver;
use Magento\Catalog\Model\Category;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_store.php');
Bootstrap::getInstance()->loadArea(FrontNameResolver::AREA_CODE);
$store = Bootstrap::getObjectManager()->get(Store::class);
$store->load('fixture_second_store', 'code');
/** @var $category Category */
$category = Bootstrap::getObjectManager()->create(Category::class);
$category->isObjectNew(true);
$category->setId(3)
->setName('Category 1')
->setParentId(2)
->setPath('1/2/3')
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setUrlPath('category-1-default')
->setUrlKey('category-1-default')
->setIsActive(true)
->setPosition(1)
->save();
$category = Bootstrap::getObjectManager()->create(Category::class);
$category->isObjectNew(true);
$category->setId(4)
->setName('Category 1.1')
->setParentId(3)
->setPath('1/2/3/4')
->setLevel(3)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setUrlPath('category-1-1-default')
->setUrlKey('category-1-1-default')
->setIsActive(true)
->setPosition(1)
->save();
$category = Bootstrap::getObjectManager()->create(Category::class);
$category->isObjectNew(true);
$category->setId(3)
->setName('Category 1')
->setParentId(2)
->setPath('1/2/3')
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setStoreId($store->getId())
->setUrlPath('category-1-custom')
->setUrlKey('category-1-custom')
->setIsActive(true)
->setPosition(1)
->save();
$category = Bootstrap::getObjectManager()->create(Category::class);
$category->isObjectNew(true);
$category->setId(4)
->setName('Category 1.1')
->setParentId(3)
->setPath('1/2/3/4')
->setLevel(3)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setStoreId($store->getId())
->setUrlPath('category-1-1-custom')
->setUrlKey('category-1-1-custom')
->setIsActive(true)
->setPosition(1)
->save();
@@ -0,0 +1,27 @@
<?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/Store/_files/second_store_rollback.php');
/** @var \Magento\Framework\Registry $registry */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Category\Collection::class);
$collection
->addAttributeToFilter('level', 2)
->load()
->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$installer = $objectManager->create(\Magento\Catalog\Setup\CategorySetup::class);
\Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea(
\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE
);
$category = $objectManager->create(\Magento\Catalog\Model\Category::class);
$category->isObjectNew(true);
$category->setId(3)
->setName('Category 1')
->setParentId(2)
->setPath('1/2/3')
->setLevel(2)
->setAvailableSortBy('name')
->setDefaultSortBy('name')
->setIsActive(true)
->setPosition(1)
->save();
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$categoryLinkRepository = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkRepositoryInterface::class,
[
'productRepository' => $productRepository
]
);
$categoryLinkManagement = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkManagementInterface::class,
[
'productRepository' => $productRepository,
'categoryLinkRepository' => $categoryLinkRepository
]
);
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(1)
->setWebsiteIds([1])
->setName('Simple Product')
->setSku('simple')
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [3]);
$product =$objectManager->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(1)
->setWebsiteIds([1])
->setName('Simple Product Two')
->setSku('12345') // SKU intentionally contains digits only
->setPrice(45.67)
->setWeight(56)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [3]);
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$registry = $objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
$productRepository = $objectManager->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$productSkuList = ['simple', '12345'];
foreach ($productSkuList as $sku) {
try {
$product = $productRepository->get($sku, true, null, true);
$productRepository->delete($product);
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
//Product already removed
continue;
}
}
$collection = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Category\Collection::class);
$collection->addAttributeToFilter('level', 2)
->load()
->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,93 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Catalog\Helper\DefaultCategory;
use Magento\CatalogSearch\Model\Indexer\Fulltext;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Store\Api\Data\GroupInterface;
use Magento\Store\Api\Data\GroupInterfaceFactory;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\Data\StoreInterfaceFactory;
use \Magento\Store\Api\Data\WebsiteInterface;
use \Magento\Store\Api\Data\WebsiteInterfaceFactory;
use Magento\Store\Model\ResourceModel\Group as GroupResource;
use Magento\Store\Model\ResourceModel\Store as StoreResource;
use Magento\Store\Model\ResourceModel\Website as WebsiteResource;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->get(StoreManagerInterface::class);
/** @var WebsiteResource $websiteResource */
$websiteResource = $objectManager->get(WebsiteResource::class);
/** @var StoreResource $storeResource */
$storeResource = $objectManager->get(StoreResource::class);
/** @var GroupResource $groupResource */
$groupResource = $objectManager->get(GroupResource::class);
/** @var DefaultCategory $defaultCategory */
$defaultCategory = $objectManager->get(DefaultCategory::class);
/** @var WebsiteInterface $website */
$website = $objectManager->get(WebsiteInterfaceFactory::class)->create();
$website->setCode('che')->setName('Test Website');
$websiteResource->save($website);
/** @var GroupInterface $storeGroup */
$storeGroup = $objectManager->get(GroupInterfaceFactory::class)->create();
$storeGroup->setCode('che_group')
->setRootCategoryId($defaultCategory->getId())
->setName('second store group')
->setWebsite($website);
$groupResource->save($storeGroup);
$websiteExp = $objectManager->get(WebsiteInterfaceFactory::class)->create();
$websiteExp->setCode('exp')->setName('Test Website');
$websiteResource->save($websiteExp);
/** @var GroupInterface $storeGroup */
$storeGroupExp = $objectManager->get(GroupInterfaceFactory::class)->create();
$storeGroupExp->setCode('exp_group')
->setRootCategoryId($defaultCategory->getId())
->setName('second store group')
->setWebsite($website);
$groupResource->save($storeGroupExp);
/* Refresh stores memory cache */
$storeManager->reinitStores();
foreach (['de_ch', 'en_ch', 'es_ch', 'fr_ch', 'zh_ch'] as $storeCode) {
/** @var StoreInterface $store */
$store = $objectManager->get(StoreInterfaceFactory::class)->create();
$store->setCode($storeCode)
->setWebsiteId($website->getId())
->setGroupId($storeGroup->getId())
->setName('Store Code' . $storeCode)
->setIsActive(1);
$storeResource->save($store);
}
foreach (['de_ex', 'en_ex', 'es_ex', 'fr_ex', 'zh_ex'] as $storeCode) {
/** @var StoreInterface $store */
$store = $objectManager->get(StoreInterfaceFactory::class)->create();
$store->setCode($storeCode)
->setWebsiteId($websiteExp->getId())
->setGroupId($storeGroupExp->getId())
->setName('Store Code' . $storeCode)
->setIsActive(1);
$storeResource->save($store);
}
/* Refresh CatalogSearch index */
/** @var IndexerRegistry $indexerRegistry */
$storeManager->reinitStores();
$indexerRegistry = $objectManager->get(IndexerRegistry::class);
$indexerRegistry->get(Fulltext::INDEXER_ID)->reindexAll();
@@ -0,0 +1,61 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\CatalogSearch\Model\Indexer\Fulltext;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Framework\Registry;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Store\Api\Data\StoreInterfaceFactory;
use Magento\Store\Api\Data\WebsiteInterface;
use Magento\Store\Api\Data\WebsiteInterfaceFactory;
use Magento\Store\Model\ResourceModel\Store as StoreResource;
use Magento\Store\Model\ResourceModel\Website as WebsiteResource;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var WebsiteResource $websiteResource */
$websiteResource = $objectManager->get(WebsiteResource::class);
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->get(StoreManagerInterface::class);
/** @var StoreResource $storeResource */
$storeResource = $objectManager->get(StoreResource::class);
/** @var Registry $registry */
$registry = $objectManager->get(Registry::class);
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var WebsiteInterface $website */
$website = $objectManager->get(WebsiteInterfaceFactory::class)->create();
$websiteResource->load($website, 'che', 'code');
if ($website->getId()) {
$websiteResource->delete($website);
}
$website = $objectManager->get(WebsiteInterfaceFactory::class)->create();
$websiteResource->load($website, 'exp', 'code');
if ($website->getId()) {
$websiteResource->delete($website);
}
/** @var StoreInterface $store */
$store = $objectManager->get(StoreInterfaceFactory::class)->create();
foreach (['de_ch', 'en_ch', 'en_ch', 'es_ch', 'fr_ch', 'zh_ch',
'de_ex', 'en_ex', 'es_ex', 'fr_ex', 'zh_ex'] as $storeCode) {
$storeResource->load($store, $storeCode, 'code');
if ($store->getId()) {
$storeResource->delete($store);
}
}
/** @var IndexerRegistry $indexerRegistry */
$storeManager->reinitStores();
$indexerRegistry = $objectManager->get(IndexerRegistry::class);
$indexerRegistry->get(Fulltext::INDEXER_ID)->reindexAll();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Setup\CategorySetup;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store.php');
/** @var $installer CategorySetup */
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
$storeManager = $objectManager->get(StoreManagerInterface::class);
$storeManager->setCurrentStore(0);
/** @var $product \Magento\Catalog\Model\Product */
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(0)
->setWebsiteIds([1])
->setName('Product1')
->setSku('product1')
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setUrlKey('product-1')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$productRepository->save($product);
@@ -0,0 +1,34 @@
<?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\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()->getInstance()->reinitialize();
/** @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 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
try {
$product = $productRepository->get('product1', true);
if ($product->getId()) {
$productRepository->delete($product);
}
} catch (NoSuchEntityException $e) {
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_store_rollback.php');
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Setup\CategorySetup;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store.php');
/** @var $installer CategorySetup */
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
$storeManager = $objectManager->get(StoreManagerInterface::class);
$storeManager->setCurrentStore(0);
/** @var $product \Magento\Catalog\Model\Product */
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(0)
->setWebsiteIds([1])
->setName('Product1')
->setSku('product1')
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setUrlKey('product-1')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$productRepository->save($product);
@@ -0,0 +1,34 @@
<?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\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()->getInstance()->reinitialize();
/** @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 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
try {
$product = $productRepository->get('product1', true);
if ($product->getId()) {
$productRepository->delete($product);
}
} catch (NoSuchEntityException $e) {
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_store_rollback.php');
@@ -0,0 +1,12 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_simple.php');
@@ -0,0 +1,29 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Exception\NoSuchEntityException;
\Magento\TestFramework\Helper\Bootstrap::getInstance()->getInstance()->reinitialize();
/** @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 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
try {
$product = $productRepository->get('simple', true);
if ($product->getId()) {
$productRepository->delete($product);
}
} catch (NoSuchEntityException $e) {
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,96 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Type;
use Magento\CatalogSearch\Model\Indexer\Fulltext;
use Magento\Framework\Indexer\IndexerRegistry;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\UrlRewrite;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store.php');
$objectManager = Bootstrap::getObjectManager();
/** @var StoreRepositoryInterface $storeRepository */
$storeRepository = $objectManager->get(StoreRepositoryInterface::class);
$store = $storeRepository->get('test');
// reindex catalog search to create store's specific temporary tables
$indexerRegistry = $objectManager->create(IndexerRegistry::class);
$indexerRegistry->get(Fulltext::INDEXER_ID)
->reindexAll();
/** @var Category $category */
$category = $objectManager->create(Category::class);
$category->setName('category 1')
->setUrlKey('cat-1')
->setIsActive(true)
->setStoreId(1);
/** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class);
$categoryRepository->save($category);
/** @var StoreManagerInterface $storeManager */
$storeManager = $objectManager->get(StoreManagerInterface::class);
$store = $storeManager->getStore('test');
// change default store, otherwise store won't be updated for the category
$storeManager->setCurrentStore($store->getId());
$category->setUrlKey('cat-1-2')
->setUrlPath('cat-1-2')
->setStoreId($store->getId());
$categoryRepository->save($category);
// back to default store
$storeManager->setCurrentStore(1);
/** @var Product $product */
$product = $objectManager->create(Product::class);
$product->setStoreId(0)
->setTypeId(Type::TYPE_SIMPLE)
->setName('p002')
->setSku('p002')
->setAttributeSetId(4)
->setWebsiteIds([1])
->setPrice(10)
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->setStockData(
[
'use_config_manage_stock' => 1,
'qty' => 100,
'is_qty_decimal' => 0,
'is_in_stock' => 1,
]
)
->setQty(100)
->setWeight(1);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->save($product);
/** @var CategoryLinkManagementInterface $linkManagement */
$linkManagement = $objectManager->get(CategoryLinkManagementInterface::class);
$linkManagement->assignProductToCategories($product->getSku(), [Category::TREE_ROOT_ID, $category->getEntityId()]);
/** @var UrlRewrite $urlRewrite */
$urlRewrite = $objectManager->create(UrlRewrite::class);
$urlRewrite->setEntityType('custom')
->setRequestPath('non-exist-product.html')
->setTargetPath('catalog/product/view/id/' . $product->getId())
->setRedirectType(0)
->setStoreId(1)
->setDescription(null)
->setIsAutogenerated(0);
$urlRewrite->save();
@@ -0,0 +1,19 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var ConfigInterface $config */
$config = $objectManager->get(ConfigInterface::class);
$config->saveConfig('catalog/seo/product_url_suffix', null);
$config->saveConfig('catalog/seo/category_url_suffix', null);
$objectManager->get(ReinitableConfigInterface::class)->reinit();
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/product_with_category.php');
@@ -0,0 +1,19 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var ConfigInterface $config */
$config = $objectManager->get(ConfigInterface::class);
$config->deleteConfig('catalog/seo/product_url_suffix');
$config->deleteConfig('catalog/seo/category_url_suffix');
$objectManager->get(ReinitableConfigInterface::class)->reinit();
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/product_with_category_rollback.php');
@@ -0,0 +1,55 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\CategoryListInterface;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\UrlRewrite\Model\UrlRewrite;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = 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 ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$product = $productRepository->get('p002', false, null, true);
$productRepository->delete($product);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter('name', 'category 1')
->create();
/** @var CategoryListInterface $categoryList */
$categoryList = $objectManager->get(CategoryListInterface::class);
$categories = $categoryList->getList($searchCriteria)
->getItems();
/** @var CategoryRepositoryInterface $categoryRepository */
$categoryRepository = $objectManager->get(CategoryRepositoryInterface::class);
foreach ($categories as $category) {
$categoryRepository->delete($category);
}
/** @var UrlRewrite $urlRewrite */
$urlRewrite = $objectManager->create(UrlRewrite::class);
$urlRewrite->load('non-exist-product.html', 'request_path');
$urlRewrite->delete();
$urlRewrite->load('.html', 'request_path');
$urlRewrite->delete();
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store_rollback.php');
@@ -0,0 +1,47 @@
<?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/CatalogUrlRewrite/_files/categories_with_stores.php');
/** @var \Magento\Catalog\Setup\CategorySetup $installer */
$installer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Catalog\Setup\CategorySetup::class
);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$productRepository = $objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$categoryLinkRepository = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkRepositoryInterface::class,
[
'productRepository' => $productRepository
]
);
/** @var Magento\Catalog\Api\CategoryLinkManagementInterface $linkManagement */
$categoryLinkManagement = $objectManager->create(
\Magento\Catalog\Api\CategoryLinkManagementInterface::class,
[
'productRepository' => $productRepository,
'categoryLinkRepository' => $categoryLinkRepository
]
);
/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setName('Simple Product')
->setSku('simple')
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->save();
$categoryLinkManagement->assignProductToCategories($product->getSku(), [4]);
@@ -0,0 +1,32 @@
<?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\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()->getInstance()->reinitialize();
Resolver::getInstance()->requireDataFixture('Magento/CatalogUrlRewrite/_files/categories_with_stores_rollback.php');
/** @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 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
try {
$product = $productRepository->get('simple', true);
if ($product->getId()) {
$productRepository->delete($product);
}
} catch (NoSuchEntityException $e) {
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
@@ -0,0 +1,38 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Setup\CategorySetup;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
\Magento\TestFramework\Helper\Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
/** @var $installer CategorySetup */
$objectManager = Bootstrap::getObjectManager();
$installer = $objectManager->create(CategorySetup::class);
/** @var ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->get(ProductRepositoryInterface::class);
$skus = ['product1', 'product2'];
foreach ($skus as $sku) {
/** @var $product \Magento\Catalog\Model\Product */
$product = $objectManager->create(\Magento\Catalog\Model\Product::class);
$product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
->setStoreId(0)
->setWebsiteIds([1])
->setName('Product1')
->setSku($sku)
->setPrice(10)
->setWeight(18)
->setStockData(['use_config_manage_stock' => 0])
->setUrlKey('product-1')
->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE)
->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
$productRepository->save($product);
}
@@ -0,0 +1,38 @@
<?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\Workaround\Override\Fixture\Resolver;
\Magento\TestFramework\Helper\Bootstrap::getInstance()->getInstance()->reinitialize();
/** @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 = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Catalog\Api\ProductRepositoryInterface::class);
$skus = ['product1', 'product2'];
foreach ($skus as $sku) {
try {
$product = $productRepository->get($sku, true);
if ($product->getId()) {
$productRepository->delete($product);
}
} catch (NoSuchEntityException $e) {
}
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store_rollback.php');
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_store_rollback.php');
@@ -0,0 +1,4 @@
sku,product_type,store_view_code,name,price,attribute_set_code,categories,product_websites,url_key,save_rewrites_history
simple1,simple,,"simple 1",25,Default,"Default Category/Category 1",base,product-1-updated,1
simple2,simple,,"simple 2",34,Default,"Default Category/Category 1",base,product-2-updated,1
simple3,simple,,"simple 3",58,Default,"Default Category/Category 1",base,product-3-updated,1
1 sku product_type store_view_code name price attribute_set_code categories product_websites url_key save_rewrites_history
2 simple1 simple simple 1 25 Default Default Category/Category 1 base product-1-updated 1
3 simple2 simple simple 2 34 Default Default Category/Category 1 base product-2-updated 1
4 simple3 simple simple 3 58 Default Default Category/Category 1 base product-3-updated 1