• Модуль: catalogmobile
  • Путь к файлу: ~/bitrix/modules/catalogmobile/lib/Controller/StoreDocumentDetails.php
  • Класс: BitrixCatalogMobileControllerStoreDocumentDetails
  • Вызов: StoreDocumentDetails::updateCatalogProducts
private function updateCatalogProducts(array $products): void
{
	if (!$this->checkProductModifyRights())
	{
		return;
	}

	foreach ($products as $product)
	{
		$productDto = new DocumentProductRecord($product);
		$sku = ServiceContainer::getRepositoryFacade()->loadVariation((int)$productDto->productId);
		if (!$sku)
		{
			continue;
		}

		/**
		 * Name
		 */
		$sku->setField('NAME', $productDto->name);

		/**
		 * Measure
		 */
		$measure = $productDto->measure ?? null;
		if ($measure && $measure->id)
		{
			$sku->setField('MEASURE', $measure->id);
		}

		/**
		 * Sections
		 */
		$sections = [];
		if (!empty($productDto->sections))
		{
			foreach ($productDto->sections as $section)
			{
				$sections[] = (int)$section['id'];
			}
		}

		$sku->getParent()->getSectionCollection()->setValues(
			empty($sections) ? [0] : $sections
		);

		/**
		 * Images
		 */
		$gallery = $productDto->gallery ?? [];
		$receivedFileIds = [];
		$newImageIds = [];
		$tokens = [];

		foreach ($gallery as $file)
		{
			if (is_array($file))
			{
				if (!empty($file['token']))
				{
					$tokens[] = $file['token'];
				}
			}
			else
			{
				$receivedFileIds[] = (int)$file;
			}
		}

		$pendingFiles = null;
		if (!empty($tokens))
		{
			$pendingFiles = $this->getProductPendingFiles($tokens, $sku);
			$newImageIds = $pendingFiles->getFileIds();
		}

		/**
		 * Remove
		 */
		$imageCollection = $sku->getImageCollection();
		foreach ($imageCollection as $image)
		{
			if (in_array((int)$image->getFields()['ID'], $receivedFileIds, true))
			{
				continue;
			}

			$image->remove();
		}

		/**
		 * Add new
		 */
		$morePhotoProperty = $sku->getPropertyCollection()->findByCode(MorePhotoImage::CODE);
		$hasMorePhoto = $morePhotoProperty && $morePhotoProperty->isActive();

		foreach ($newImageIds as $newImage)
		{
			$fileArray = CFile::MakeFileArray($newImage);

			if ($hasMorePhoto)
			{
				$imageCollection->addValues([$fileArray]);
			}
			else
			{
				$previewImage = $imageCollection->getPreviewImage();
				$previewImageValue = $previewImage->getFileStructure();
				if (empty($previewImageValue))
				{
					$previewImage->setFileStructure($fileArray);
					continue;
				}

				$detailImage = $imageCollection->getDetailImage();
				$detailImageValue = $detailImage->getFileStructure();
				if (empty($detailImageValue))
				{
					$detailImage->setFileStructure($fileArray);
					continue;
				}

				break;
			}
		}

		$result = $sku->save();
		if ($result->isSuccess())
		{
			if ($pendingFiles)
			{
				$pendingFiles->makePersistent();
			}
		}
		else
		{
			$this->addNonCriticalErrors($result->getErrors());
		}
	}
}