77 lines
2.9 KiB
PHP
77 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace Stemcell\ProductImport\Helper;
|
|
|
|
use Magento\Catalog\Api\ProductRepositoryInterface;
|
|
use Magento\Catalog\Model\Product\Visibility;
|
|
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;
|
|
use Magento\Framework\App\Helper\AbstractHelper;
|
|
use Magento\Framework\App\Helper\Context;
|
|
use Magento\Framework\Exception\CouldNotSaveException;
|
|
use Magento\Framework\Exception\InputException;
|
|
use Magento\Framework\Exception\StateException;
|
|
use Symfony\Component\Console\Output\OutputInterface;
|
|
|
|
/**
|
|
* 如果产品parent sku的sku都没有对应的产品,就就此产品的Visibility改成Not Visible Individually
|
|
* 如果产品parent sku中只有部分sku有对应的产品, 那么就去掉没有对应产品的sku
|
|
*
|
|
*/
|
|
class ParentSkuClean extends AbstractHelper
|
|
{
|
|
private OutputInterface $output;
|
|
|
|
public function __construct(
|
|
Context $context,
|
|
protected ProductRepositoryInterface $productRepository,
|
|
protected ProductCollectionFactory $productCollectionFactory,
|
|
) {
|
|
parent::__construct($context);
|
|
}
|
|
|
|
/**
|
|
* @return array
|
|
*/
|
|
public function execute()
|
|
{
|
|
$collection = $this->productCollectionFactory->create()
|
|
->addAttributeToFilter('parent_skus', ['neq' => null]);
|
|
|
|
$updateFails = [];
|
|
/* @var $item \Magento\Catalog\Model\Product */
|
|
foreach ($collection as $item) {
|
|
// $product = $this->productRepository->get($item->getSku(), true);
|
|
|
|
$parentSkus = explode(',', $item->getData('parent_skus'));
|
|
$parentSKusProduct = $this->productCollectionFactory->create()
|
|
->addAttributeToFilter('sku', ['in' => $parentSkus]);
|
|
|
|
$validParentSkuCount = $parentSKusProduct->getSize();
|
|
$validParentSkus = $parentSKusProduct->getColumnValues('sku');
|
|
|
|
try {
|
|
if ($validParentSkuCount) {
|
|
if ($validParentSkuCount < count($parentSkus)) {
|
|
|
|
$item->setData('parent_skus', implode(',', $validParentSkus))->setData('_edit_mode', true);
|
|
$this->productRepository->save($item, true);
|
|
echo 'product '.$item->getSku(). " updated, \033[32m part valid parent sku \033[0m: ".
|
|
implode(', ', $validParentSkus).
|
|
', original parent sku: '.$item->getData('parent_skus').PHP_EOL;
|
|
}
|
|
|
|
} else {
|
|
|
|
$item->setData('visibility', Visibility::VISIBILITY_NOT_VISIBLE)->setData('_edit_mode', true);
|
|
$this->productRepository->save($item, true);
|
|
echo 'product '.$item->getSku()." updated, \033[32m all parent skus \033[0m are invalid: ".$item->getData('parent_skus').PHP_EOL;
|
|
}
|
|
} catch (\Exception $e) {
|
|
$updateFails[$item->getSku()] = $e->getMessage();
|
|
}
|
|
|
|
}
|
|
return $updateFails;
|
|
}
|
|
}
|