Skip to content

Commit

Permalink
Decrease overall product repository complexity.
Browse files Browse the repository at this point in the history
  • Loading branch information
nmalevanec committed Apr 25, 2019
1 parent bd46d50 commit 96b6feb
Show file tree
Hide file tree
Showing 3 changed files with 322 additions and 164 deletions.
154 changes: 28 additions & 126 deletions app/code/Magento/Catalog/Model/ProductRepository.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
Expand All @@ -11,9 +10,9 @@
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 @@ -26,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 @@ -123,11 +122,15 @@ class ProductRepository implements \Magento\Catalog\Api\ProductRepositoryInterfa
protected $fileSystem;

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

/**
* @deprecated
*
* @var ImageProcessorInterface
*/
protected $imageProcessor;
Expand All @@ -138,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 Down Expand Up @@ -192,8 +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 Magento\Catalog\Api\CategoryLinkManagementInterface|null $linkManagement
* @param ReadExtensions $readExtensions
* @param CategoryLinkManagementInterface $linkManagement
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
Expand Down Expand Up @@ -391,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 @@ -402,40 +415,8 @@ protected function processNewMediaGalleryEntry(
ProductInterface $product,
array $newEntry
) {
/** @var ImageContentInterface $contentDataObject */
$contentDataObject = $newEntry['content'];

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

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

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 @@ -510,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 Down Expand Up @@ -781,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 @@ -930,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

0 comments on commit 96b6feb

Please sign in to comment.