Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

REST products update category_ids cannot be removed #20842

Merged
merged 6 commits into from
Apr 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

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

namespace Magento\Catalog\Model;

use Magento\Catalog\Api\CategoryLinkManagementInterface;
use Magento\Catalog\Api\Data\ProductExtension;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Product\Gallery\MimeTypeExtensionMap;
use Magento\Catalog\Model\ProductRepository\MediaGalleryProcessor;
use Magento\Catalog\Model\ResourceModel\Product\Collection;
use Magento\Eav\Model\Entity\Attribute\Exception as AttributeException;
use Magento\Framework\Api\Data\ImageContentInterface;
use Magento\Framework\Api\Data\ImageContentInterfaceFactory;
use Magento\Framework\Api\ImageContentValidatorInterface;
use Magento\Framework\Api\ImageProcessorInterface;
Expand All @@ -25,8 +25,8 @@
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\TemporaryState\CouldNotSaveException as TemporaryCouldNotSaveException;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Exception\TemporaryState\CouldNotSaveException as TemporaryCouldNotSaveException;
use Magento\Framework\Exception\ValidatorException;

/**
Expand Down Expand Up @@ -122,11 +122,15 @@ class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterfa
protected $fileSystem;

/**
* @deprecated
*
* @var ImageContentInterfaceFactory
*/
protected $contentFactory;

/**
* @deprecated
*
* @var ImageProcessorInterface
*/
protected $imageProcessor;
Expand All @@ -137,10 +141,17 @@ class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterfa
protected $extensionAttributesJoinProcessor;

/**
* @deprecated
*
* @var \Magento\Catalog\Model\Product\Gallery\Processor
*/
protected $mediaGalleryProcessor;

/**
* @var MediaGalleryProcessor
*/
private $mediaProcessor;

/**
* @var CollectionProcessorInterface
*/
Expand All @@ -161,6 +172,11 @@ class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterfa
*/
private $readExtensions;

/**
* @var CategoryLinkManagementInterface
*/
private $linkManagement;

/**
* ProductRepository constructor.
* @param ProductFactory $productFactory
Expand All @@ -186,7 +202,8 @@ class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterfa
* @param CollectionProcessorInterface $collectionProcessor [optional]
* @param \Magento\Framework\Serialize\Serializer\Json|null $serializer
* @param int $cacheLimit [optional]
* @param ReadExtensions|null $readExtensions
* @param ReadExtensions $readExtensions
* @param CategoryLinkManagementInterface $linkManagement
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
Expand Down Expand Up @@ -214,7 +231,8 @@ public function __construct(
CollectionProcessorInterface $collectionProcessor = null,
\Magento\Framework\Serialize\Serializer\Json $serializer = null,
$cacheLimit = 1000,
ReadExtensions $readExtensions = null
ReadExtensions $readExtensions = null,
CategoryLinkManagementInterface $linkManagement = null
) {
$this->productFactory = $productFactory;
$this->collectionFactory = $collectionFactory;
Expand All @@ -239,6 +257,8 @@ public function __construct(
$this->cacheLimit = (int)$cacheLimit;
$this->readExtensions = $readExtensions ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(ReadExtensions::class);
$this->linkManagement = $linkManagement ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(CategoryLinkManagementInterface::class);
}

/**
Expand Down Expand Up @@ -381,6 +401,9 @@ private function assignProductToWebsites(\Magento\Catalog\Model\Product $product
/**
* Process new gallery media entry.
*
* @deprecated
* @see MediaGalleryProcessor::processNewMediaGalleryEntry()
*
* @param ProductInterface $product
* @param array $newEntry
* @return $this
Expand All @@ -392,40 +415,8 @@ protected function processNewMediaGalleryEntry(
ProductInterface $product,
array $newEntry
) {
/** @var ImageContentInterface $contentDataObject */
$contentDataObject = $newEntry['content'];
$this->getMediaGalleryProcessor()->processNewMediaGalleryEntry($product, $newEntry);

/** @var \Magento\Catalog\Model\Product\Media\Config $mediaConfig */
$mediaConfig = $product->getMediaConfig();
$mediaTmpPath = $mediaConfig->getBaseTmpMediaPath();

$relativeFilePath = $this->imageProcessor->processImageContent($mediaTmpPath, $contentDataObject);
$tmpFilePath = $mediaConfig->getTmpMediaShortUrl($relativeFilePath);

if (!$product->hasGalleryAttribute()) {
throw new StateException(
__("The product that was requested doesn't exist. Verify the product and try again.")
);
}

$imageFileUri = $this->getMediaGalleryProcessor()->addImage(
$product,
$tmpFilePath,
isset($newEntry['types']) ? $newEntry['types'] : [],
true,
isset($newEntry['disabled']) ? $newEntry['disabled'] : true
);
// Update additional fields that are still empty after addImage call
$this->getMediaGalleryProcessor()->updateImage(
$product,
$imageFileUri,
[
'label' => $newEntry['label'],
'position' => $newEntry['position'],
'disabled' => $newEntry['disabled'],
'media_type' => $newEntry['media_type'],
]
);
return $this;
}

Expand Down Expand Up @@ -500,68 +491,13 @@ private function processLinks(ProductInterface $product, $newLinks)
* @return $this
* @throws InputException
* @throws StateException
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function processMediaGallery(ProductInterface $product, $mediaGalleryEntries)
{
$existingMediaGallery = $product->getMediaGallery('images');
$newEntries = [];
$entriesById = [];
if (!empty($existingMediaGallery)) {
foreach ($mediaGalleryEntries as $entry) {
if (isset($entry['value_id'])) {
$entriesById[$entry['value_id']] = $entry;
} else {
$newEntries[] = $entry;
}
}
foreach ($existingMediaGallery as $key => &$existingEntry) {
if (isset($entriesById[$existingEntry['value_id']])) {
$updatedEntry = $entriesById[$existingEntry['value_id']];
if ($updatedEntry['file'] === null) {
unset($updatedEntry['file']);
}
$existingMediaGallery[$key] = array_merge($existingEntry, $updatedEntry);
} else {
//set the removed flag
$existingEntry['removed'] = true;
}
}
$product->setData('media_gallery', ["images" => $existingMediaGallery]);
} else {
$newEntries = $mediaGalleryEntries;
}

$images = (array)$product->getMediaGallery('images');
$images = $this->determineImageRoles($product, $images);

$this->getMediaGalleryProcessor()->clearMediaAttribute($product, array_keys($product->getMediaAttributes()));

foreach ($images as $image) {
if (!isset($image['removed']) && !empty($image['types'])) {
$this->getMediaGalleryProcessor()->setMediaAttribute($product, $image['types'], $image['file']);
}
}
$this->getMediaGalleryProcessor()->processMediaGallery($product, $mediaGalleryEntries);

foreach ($newEntries as $newEntry) {
if (!isset($newEntry['content'])) {
throw new InputException(__('The image content is invalid. Verify the content and try again.'));
}
/** @var ImageContentInterface $contentDataObject */
$contentDataObject = $this->contentFactory->create()
->setName($newEntry['content']['data'][ImageContentInterface::NAME])
->setBase64EncodedData($newEntry['content']['data'][ImageContentInterface::BASE64_ENCODED_DATA])
->setType($newEntry['content']['data'][ImageContentInterface::TYPE]);
$newEntry['content'] = $contentDataObject;
$this->processNewMediaGalleryEntry($product, $newEntry);

$finalGallery = $product->getData('media_gallery');
$newEntryId = key(array_diff_key($product->getData('media_gallery')['images'], $entriesById));
$newEntry = array_replace_recursive($newEntry, $finalGallery['images'][$newEntryId]);
$entriesById[$newEntryId] = $newEntry;
$finalGallery['images'][$newEntryId] = $newEntry;
$product->setData('media_gallery', $finalGallery);
}
return $this;
}

Expand All @@ -572,6 +508,7 @@ protected function processMediaGallery(ProductInterface $product, $mediaGalleryE
*/
public function save(ProductInterface $product, $saveOptions = false)
{
$assignToCategories = false;
$tierPrices = $product->getData('tier_price');

try {
Expand All @@ -589,6 +526,7 @@ public function save(ProductInterface $product, $saveOptions = false)
$extensionAttributes = $product->getExtensionAttributes();
if (empty($extensionAttributes->__toArray())) {
$product->setExtensionAttributes($existingProduct->getExtensionAttributes());
$assignToCategories = true;
}
} catch (NoSuchEntityException $e) {
$existingProduct = null;
Expand Down Expand Up @@ -626,6 +564,12 @@ public function save(ProductInterface $product, $saveOptions = false)
}

$this->saveProduct($product);
if ($assignToCategories === true && $product->getCategoryIds()) {
$this->linkManagement->assignProductToCategories(
$product->getSku(),
$product->getCategoryIds()
);
}
$this->removeProductFromLocalCache($product->getSku());
unset($this->instancesById[$product->getId()]);

Expand Down Expand Up @@ -763,44 +707,19 @@ public function cleanCache()
$this->instancesById = null;
}

/**
* Ascertain image roles, if they are not set against the gallery entries
*
* @param ProductInterface $product
* @param array $images
* @return array
*/
private function determineImageRoles(ProductInterface $product, array $images) : array
{
$imagesWithRoles = [];
foreach ($images as $image) {
if (!isset($image['types'])) {
$image['types'] = [];
if (isset($image['file'])) {
foreach (array_keys($product->getMediaAttributes()) as $attribute) {
if ($image['file'] == $product->getData($attribute)) {
$image['types'][] = $attribute;
}
}
}
}
$imagesWithRoles[] = $image;
}
return $imagesWithRoles;
}

/**
* Retrieve media gallery processor.
*
* @return Product\Gallery\Processor
* @return MediaGalleryProcessor
*/
private function getMediaGalleryProcessor()
{
if (null === $this->mediaGalleryProcessor) {
$this->mediaGalleryProcessor = \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Catalog\Model\Product\Gallery\Processor::class);
if (null === $this->mediaProcessor) {
$this->mediaProcessor = \Magento\Framework\App\ObjectManager::getInstance()
->get(MediaGalleryProcessor::class);
}
return $this->mediaGalleryProcessor;

return $this->mediaProcessor;
}

/**
Expand Down Expand Up @@ -912,6 +831,7 @@ private function saveProduct($product): void
throw new CouldNotSaveException(__($e->getMessage()));
} catch (LocalizedException $e) {
throw $e;
// phpcs:disable Magento2.Exceptions.ThrowCatch
} catch (\Exception $e) {
throw new CouldNotSaveException(
__('The product was unable to be saved. Please try again.'),
Expand Down
Loading